base.py 180 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175
  1. # dialects/postgresql/base.py
  2. # Copyright (C) 2005-2025 the SQLAlchemy authors and contributors
  3. # <see AUTHORS file>
  4. #
  5. # This module is part of SQLAlchemy and is released under
  6. # the MIT License: https://www.opensource.org/licenses/mit-license.php
  7. # mypy: ignore-errors
  8. r"""
  9. .. dialect:: postgresql
  10. :name: PostgreSQL
  11. :normal_support: 9.6+
  12. :best_effort: 9+
  13. .. _postgresql_sequences:
  14. Sequences/SERIAL/IDENTITY
  15. -------------------------
  16. PostgreSQL supports sequences, and SQLAlchemy uses these as the default means
  17. of creating new primary key values for integer-based primary key columns. When
  18. creating tables, SQLAlchemy will issue the ``SERIAL`` datatype for
  19. integer-based primary key columns, which generates a sequence and server side
  20. default corresponding to the column.
  21. To specify a specific named sequence to be used for primary key generation,
  22. use the :func:`~sqlalchemy.schema.Sequence` construct::
  23. Table(
  24. "sometable",
  25. metadata,
  26. Column(
  27. "id", Integer, Sequence("some_id_seq", start=1), primary_key=True
  28. ),
  29. )
  30. When SQLAlchemy issues a single INSERT statement, to fulfill the contract of
  31. having the "last insert identifier" available, a RETURNING clause is added to
  32. the INSERT statement which specifies the primary key columns should be
  33. returned after the statement completes. The RETURNING functionality only takes
  34. place if PostgreSQL 8.2 or later is in use. As a fallback approach, the
  35. sequence, whether specified explicitly or implicitly via ``SERIAL``, is
  36. executed independently beforehand, the returned value to be used in the
  37. subsequent insert. Note that when an
  38. :func:`~sqlalchemy.sql.expression.insert()` construct is executed using
  39. "executemany" semantics, the "last inserted identifier" functionality does not
  40. apply; no RETURNING clause is emitted nor is the sequence pre-executed in this
  41. case.
  42. PostgreSQL 10 and above IDENTITY columns
  43. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  44. PostgreSQL 10 and above have a new IDENTITY feature that supersedes the use
  45. of SERIAL. The :class:`_schema.Identity` construct in a
  46. :class:`_schema.Column` can be used to control its behavior::
  47. from sqlalchemy import Table, Column, MetaData, Integer, Computed
  48. metadata = MetaData()
  49. data = Table(
  50. "data",
  51. metadata,
  52. Column(
  53. "id", Integer, Identity(start=42, cycle=True), primary_key=True
  54. ),
  55. Column("data", String),
  56. )
  57. The CREATE TABLE for the above :class:`_schema.Table` object would be:
  58. .. sourcecode:: sql
  59. CREATE TABLE data (
  60. id INTEGER GENERATED BY DEFAULT AS IDENTITY (START WITH 42 CYCLE),
  61. data VARCHAR,
  62. PRIMARY KEY (id)
  63. )
  64. .. versionchanged:: 1.4 Added :class:`_schema.Identity` construct
  65. in a :class:`_schema.Column` to specify the option of an autoincrementing
  66. column.
  67. .. note::
  68. Previous versions of SQLAlchemy did not have built-in support for rendering
  69. of IDENTITY, and could use the following compilation hook to replace
  70. occurrences of SERIAL with IDENTITY::
  71. from sqlalchemy.schema import CreateColumn
  72. from sqlalchemy.ext.compiler import compiles
  73. @compiles(CreateColumn, "postgresql")
  74. def use_identity(element, compiler, **kw):
  75. text = compiler.visit_create_column(element, **kw)
  76. text = text.replace("SERIAL", "INT GENERATED BY DEFAULT AS IDENTITY")
  77. return text
  78. Using the above, a table such as::
  79. t = Table(
  80. "t", m, Column("id", Integer, primary_key=True), Column("data", String)
  81. )
  82. Will generate on the backing database as:
  83. .. sourcecode:: sql
  84. CREATE TABLE t (
  85. id INT GENERATED BY DEFAULT AS IDENTITY,
  86. data VARCHAR,
  87. PRIMARY KEY (id)
  88. )
  89. .. _postgresql_ss_cursors:
  90. Server Side Cursors
  91. -------------------
  92. Server-side cursor support is available for the psycopg2, asyncpg
  93. dialects and may also be available in others.
  94. Server side cursors are enabled on a per-statement basis by using the
  95. :paramref:`.Connection.execution_options.stream_results` connection execution
  96. option::
  97. with engine.connect() as conn:
  98. result = conn.execution_options(stream_results=True).execute(
  99. text("select * from table")
  100. )
  101. Note that some kinds of SQL statements may not be supported with
  102. server side cursors; generally, only SQL statements that return rows should be
  103. used with this option.
  104. .. deprecated:: 1.4 The dialect-level server_side_cursors flag is deprecated
  105. and will be removed in a future release. Please use the
  106. :paramref:`_engine.Connection.stream_results` execution option for
  107. unbuffered cursor support.
  108. .. seealso::
  109. :ref:`engine_stream_results`
  110. .. _postgresql_isolation_level:
  111. Transaction Isolation Level
  112. ---------------------------
  113. Most SQLAlchemy dialects support setting of transaction isolation level
  114. using the :paramref:`_sa.create_engine.isolation_level` parameter
  115. at the :func:`_sa.create_engine` level, and at the :class:`_engine.Connection`
  116. level via the :paramref:`.Connection.execution_options.isolation_level`
  117. parameter.
  118. For PostgreSQL dialects, this feature works either by making use of the
  119. DBAPI-specific features, such as psycopg2's isolation level flags which will
  120. embed the isolation level setting inline with the ``"BEGIN"`` statement, or for
  121. DBAPIs with no direct support by emitting ``SET SESSION CHARACTERISTICS AS
  122. TRANSACTION ISOLATION LEVEL <level>`` ahead of the ``"BEGIN"`` statement
  123. emitted by the DBAPI. For the special AUTOCOMMIT isolation level,
  124. DBAPI-specific techniques are used which is typically an ``.autocommit``
  125. flag on the DBAPI connection object.
  126. To set isolation level using :func:`_sa.create_engine`::
  127. engine = create_engine(
  128. "postgresql+pg8000://scott:tiger@localhost/test",
  129. isolation_level="REPEATABLE READ",
  130. )
  131. To set using per-connection execution options::
  132. with engine.connect() as conn:
  133. conn = conn.execution_options(isolation_level="REPEATABLE READ")
  134. with conn.begin():
  135. ... # work with transaction
  136. There are also more options for isolation level configurations, such as
  137. "sub-engine" objects linked to a main :class:`_engine.Engine` which each apply
  138. different isolation level settings. See the discussion at
  139. :ref:`dbapi_autocommit` for background.
  140. Valid values for ``isolation_level`` on most PostgreSQL dialects include:
  141. * ``READ COMMITTED``
  142. * ``READ UNCOMMITTED``
  143. * ``REPEATABLE READ``
  144. * ``SERIALIZABLE``
  145. * ``AUTOCOMMIT``
  146. .. seealso::
  147. :ref:`dbapi_autocommit`
  148. :ref:`postgresql_readonly_deferrable`
  149. :ref:`psycopg2_isolation_level`
  150. :ref:`pg8000_isolation_level`
  151. .. _postgresql_readonly_deferrable:
  152. Setting READ ONLY / DEFERRABLE
  153. ------------------------------
  154. Most PostgreSQL dialects support setting the "READ ONLY" and "DEFERRABLE"
  155. characteristics of the transaction, which is in addition to the isolation level
  156. setting. These two attributes can be established either in conjunction with or
  157. independently of the isolation level by passing the ``postgresql_readonly`` and
  158. ``postgresql_deferrable`` flags with
  159. :meth:`_engine.Connection.execution_options`. The example below illustrates
  160. passing the ``"SERIALIZABLE"`` isolation level at the same time as setting
  161. "READ ONLY" and "DEFERRABLE"::
  162. with engine.connect() as conn:
  163. conn = conn.execution_options(
  164. isolation_level="SERIALIZABLE",
  165. postgresql_readonly=True,
  166. postgresql_deferrable=True,
  167. )
  168. with conn.begin():
  169. ... # work with transaction
  170. Note that some DBAPIs such as asyncpg only support "readonly" with
  171. SERIALIZABLE isolation.
  172. .. versionadded:: 1.4 added support for the ``postgresql_readonly``
  173. and ``postgresql_deferrable`` execution options.
  174. .. _postgresql_reset_on_return:
  175. Temporary Table / Resource Reset for Connection Pooling
  176. -------------------------------------------------------
  177. The :class:`.QueuePool` connection pool implementation used
  178. by the SQLAlchemy :class:`.Engine` object includes
  179. :ref:`reset on return <pool_reset_on_return>` behavior that will invoke
  180. the DBAPI ``.rollback()`` method when connections are returned to the pool.
  181. While this rollback will clear out the immediate state used by the previous
  182. transaction, it does not cover a wider range of session-level state, including
  183. temporary tables as well as other server state such as prepared statement
  184. handles and statement caches. The PostgreSQL database includes a variety
  185. of commands which may be used to reset this state, including
  186. ``DISCARD``, ``RESET``, ``DEALLOCATE``, and ``UNLISTEN``.
  187. To install
  188. one or more of these commands as the means of performing reset-on-return,
  189. the :meth:`.PoolEvents.reset` event hook may be used, as demonstrated
  190. in the example below. The implementation
  191. will end transactions in progress as well as discard temporary tables
  192. using the ``CLOSE``, ``RESET`` and ``DISCARD`` commands; see the PostgreSQL
  193. documentation for background on what each of these statements do.
  194. The :paramref:`_sa.create_engine.pool_reset_on_return` parameter
  195. is set to ``None`` so that the custom scheme can replace the default behavior
  196. completely. The custom hook implementation calls ``.rollback()`` in any case,
  197. as it's usually important that the DBAPI's own tracking of commit/rollback
  198. will remain consistent with the state of the transaction::
  199. from sqlalchemy import create_engine
  200. from sqlalchemy import event
  201. postgresql_engine = create_engine(
  202. "postgresql+psycopg2://scott:tiger@hostname/dbname",
  203. # disable default reset-on-return scheme
  204. pool_reset_on_return=None,
  205. )
  206. @event.listens_for(postgresql_engine, "reset")
  207. def _reset_postgresql(dbapi_connection, connection_record, reset_state):
  208. if not reset_state.terminate_only:
  209. dbapi_connection.execute("CLOSE ALL")
  210. dbapi_connection.execute("RESET ALL")
  211. dbapi_connection.execute("DISCARD TEMP")
  212. # so that the DBAPI itself knows that the connection has been
  213. # reset
  214. dbapi_connection.rollback()
  215. .. versionchanged:: 2.0.0b3 Added additional state arguments to
  216. the :meth:`.PoolEvents.reset` event and additionally ensured the event
  217. is invoked for all "reset" occurrences, so that it's appropriate
  218. as a place for custom "reset" handlers. Previous schemes which
  219. use the :meth:`.PoolEvents.checkin` handler remain usable as well.
  220. .. seealso::
  221. :ref:`pool_reset_on_return` - in the :ref:`pooling_toplevel` documentation
  222. .. _postgresql_alternate_search_path:
  223. Setting Alternate Search Paths on Connect
  224. ------------------------------------------
  225. The PostgreSQL ``search_path`` variable refers to the list of schema names
  226. that will be implicitly referenced when a particular table or other
  227. object is referenced in a SQL statement. As detailed in the next section
  228. :ref:`postgresql_schema_reflection`, SQLAlchemy is generally organized around
  229. the concept of keeping this variable at its default value of ``public``,
  230. however, in order to have it set to any arbitrary name or names when connections
  231. are used automatically, the "SET SESSION search_path" command may be invoked
  232. for all connections in a pool using the following event handler, as discussed
  233. at :ref:`schema_set_default_connections`::
  234. from sqlalchemy import event
  235. from sqlalchemy import create_engine
  236. engine = create_engine("postgresql+psycopg2://scott:tiger@host/dbname")
  237. @event.listens_for(engine, "connect", insert=True)
  238. def set_search_path(dbapi_connection, connection_record):
  239. existing_autocommit = dbapi_connection.autocommit
  240. dbapi_connection.autocommit = True
  241. cursor = dbapi_connection.cursor()
  242. cursor.execute("SET SESSION search_path='%s'" % schema_name)
  243. cursor.close()
  244. dbapi_connection.autocommit = existing_autocommit
  245. The reason the recipe is complicated by use of the ``.autocommit`` DBAPI
  246. attribute is so that when the ``SET SESSION search_path`` directive is invoked,
  247. it is invoked outside of the scope of any transaction and therefore will not
  248. be reverted when the DBAPI connection has a rollback.
  249. .. seealso::
  250. :ref:`schema_set_default_connections` - in the :ref:`metadata_toplevel` documentation
  251. .. _postgresql_schema_reflection:
  252. Remote-Schema Table Introspection and PostgreSQL search_path
  253. ------------------------------------------------------------
  254. .. admonition:: Section Best Practices Summarized
  255. keep the ``search_path`` variable set to its default of ``public``, without
  256. any other schema names. Ensure the username used to connect **does not**
  257. match remote schemas, or ensure the ``"$user"`` token is **removed** from
  258. ``search_path``. For other schema names, name these explicitly
  259. within :class:`_schema.Table` definitions. Alternatively, the
  260. ``postgresql_ignore_search_path`` option will cause all reflected
  261. :class:`_schema.Table` objects to have a :attr:`_schema.Table.schema`
  262. attribute set up.
  263. The PostgreSQL dialect can reflect tables from any schema, as outlined in
  264. :ref:`metadata_reflection_schemas`.
  265. In all cases, the first thing SQLAlchemy does when reflecting tables is
  266. to **determine the default schema for the current database connection**.
  267. It does this using the PostgreSQL ``current_schema()``
  268. function, illustated below using a PostgreSQL client session (i.e. using
  269. the ``psql`` tool):
  270. .. sourcecode:: sql
  271. test=> select current_schema();
  272. current_schema
  273. ----------------
  274. public
  275. (1 row)
  276. Above we see that on a plain install of PostgreSQL, the default schema name
  277. is the name ``public``.
  278. However, if your database username **matches the name of a schema**, PostgreSQL's
  279. default is to then **use that name as the default schema**. Below, we log in
  280. using the username ``scott``. When we create a schema named ``scott``, **it
  281. implicitly changes the default schema**:
  282. .. sourcecode:: sql
  283. test=> select current_schema();
  284. current_schema
  285. ----------------
  286. public
  287. (1 row)
  288. test=> create schema scott;
  289. CREATE SCHEMA
  290. test=> select current_schema();
  291. current_schema
  292. ----------------
  293. scott
  294. (1 row)
  295. The behavior of ``current_schema()`` is derived from the
  296. `PostgreSQL search path
  297. <https://www.postgresql.org/docs/current/static/ddl-schemas.html#DDL-SCHEMAS-PATH>`_
  298. variable ``search_path``, which in modern PostgreSQL versions defaults to this:
  299. .. sourcecode:: sql
  300. test=> show search_path;
  301. search_path
  302. -----------------
  303. "$user", public
  304. (1 row)
  305. Where above, the ``"$user"`` variable will inject the current username as the
  306. default schema, if one exists. Otherwise, ``public`` is used.
  307. When a :class:`_schema.Table` object is reflected, if it is present in the
  308. schema indicated by the ``current_schema()`` function, **the schema name assigned
  309. to the ".schema" attribute of the Table is the Python "None" value**. Otherwise, the
  310. ".schema" attribute will be assigned the string name of that schema.
  311. With regards to tables which these :class:`_schema.Table`
  312. objects refer to via foreign key constraint, a decision must be made as to how
  313. the ``.schema`` is represented in those remote tables, in the case where that
  314. remote schema name is also a member of the current ``search_path``.
  315. By default, the PostgreSQL dialect mimics the behavior encouraged by
  316. PostgreSQL's own ``pg_get_constraintdef()`` builtin procedure. This function
  317. returns a sample definition for a particular foreign key constraint,
  318. omitting the referenced schema name from that definition when the name is
  319. also in the PostgreSQL schema search path. The interaction below
  320. illustrates this behavior:
  321. .. sourcecode:: sql
  322. test=> CREATE TABLE test_schema.referred(id INTEGER PRIMARY KEY);
  323. CREATE TABLE
  324. test=> CREATE TABLE referring(
  325. test(> id INTEGER PRIMARY KEY,
  326. test(> referred_id INTEGER REFERENCES test_schema.referred(id));
  327. CREATE TABLE
  328. test=> SET search_path TO public, test_schema;
  329. test=> SELECT pg_catalog.pg_get_constraintdef(r.oid, true) FROM
  330. test-> pg_catalog.pg_class c JOIN pg_catalog.pg_namespace n
  331. test-> ON n.oid = c.relnamespace
  332. test-> JOIN pg_catalog.pg_constraint r ON c.oid = r.conrelid
  333. test-> WHERE c.relname='referring' AND r.contype = 'f'
  334. test-> ;
  335. pg_get_constraintdef
  336. ---------------------------------------------------
  337. FOREIGN KEY (referred_id) REFERENCES referred(id)
  338. (1 row)
  339. Above, we created a table ``referred`` as a member of the remote schema
  340. ``test_schema``, however when we added ``test_schema`` to the
  341. PG ``search_path`` and then asked ``pg_get_constraintdef()`` for the
  342. ``FOREIGN KEY`` syntax, ``test_schema`` was not included in the output of
  343. the function.
  344. On the other hand, if we set the search path back to the typical default
  345. of ``public``:
  346. .. sourcecode:: sql
  347. test=> SET search_path TO public;
  348. SET
  349. The same query against ``pg_get_constraintdef()`` now returns the fully
  350. schema-qualified name for us:
  351. .. sourcecode:: sql
  352. test=> SELECT pg_catalog.pg_get_constraintdef(r.oid, true) FROM
  353. test-> pg_catalog.pg_class c JOIN pg_catalog.pg_namespace n
  354. test-> ON n.oid = c.relnamespace
  355. test-> JOIN pg_catalog.pg_constraint r ON c.oid = r.conrelid
  356. test-> WHERE c.relname='referring' AND r.contype = 'f';
  357. pg_get_constraintdef
  358. ---------------------------------------------------------------
  359. FOREIGN KEY (referred_id) REFERENCES test_schema.referred(id)
  360. (1 row)
  361. SQLAlchemy will by default use the return value of ``pg_get_constraintdef()``
  362. in order to determine the remote schema name. That is, if our ``search_path``
  363. were set to include ``test_schema``, and we invoked a table
  364. reflection process as follows::
  365. >>> from sqlalchemy import Table, MetaData, create_engine, text
  366. >>> engine = create_engine("postgresql+psycopg2://scott:tiger@localhost/test")
  367. >>> with engine.connect() as conn:
  368. ... conn.execute(text("SET search_path TO test_schema, public"))
  369. ... metadata_obj = MetaData()
  370. ... referring = Table("referring", metadata_obj, autoload_with=conn)
  371. <sqlalchemy.engine.result.CursorResult object at 0x101612ed0>
  372. The above process would deliver to the :attr:`_schema.MetaData.tables`
  373. collection
  374. ``referred`` table named **without** the schema::
  375. >>> metadata_obj.tables["referred"].schema is None
  376. True
  377. To alter the behavior of reflection such that the referred schema is
  378. maintained regardless of the ``search_path`` setting, use the
  379. ``postgresql_ignore_search_path`` option, which can be specified as a
  380. dialect-specific argument to both :class:`_schema.Table` as well as
  381. :meth:`_schema.MetaData.reflect`::
  382. >>> with engine.connect() as conn:
  383. ... conn.execute(text("SET search_path TO test_schema, public"))
  384. ... metadata_obj = MetaData()
  385. ... referring = Table(
  386. ... "referring",
  387. ... metadata_obj,
  388. ... autoload_with=conn,
  389. ... postgresql_ignore_search_path=True,
  390. ... )
  391. <sqlalchemy.engine.result.CursorResult object at 0x1016126d0>
  392. We will now have ``test_schema.referred`` stored as schema-qualified::
  393. >>> metadata_obj.tables["test_schema.referred"].schema
  394. 'test_schema'
  395. .. sidebar:: Best Practices for PostgreSQL Schema reflection
  396. The description of PostgreSQL schema reflection behavior is complex, and
  397. is the product of many years of dealing with widely varied use cases and
  398. user preferences. But in fact, there's no need to understand any of it if
  399. you just stick to the simplest use pattern: leave the ``search_path`` set
  400. to its default of ``public`` only, never refer to the name ``public`` as
  401. an explicit schema name otherwise, and refer to all other schema names
  402. explicitly when building up a :class:`_schema.Table` object. The options
  403. described here are only for those users who can't, or prefer not to, stay
  404. within these guidelines.
  405. .. seealso::
  406. :ref:`reflection_schema_qualified_interaction` - discussion of the issue
  407. from a backend-agnostic perspective
  408. `The Schema Search Path
  409. <https://www.postgresql.org/docs/current/static/ddl-schemas.html#DDL-SCHEMAS-PATH>`_
  410. - on the PostgreSQL website.
  411. INSERT/UPDATE...RETURNING
  412. -------------------------
  413. The dialect supports PG 8.2's ``INSERT..RETURNING``, ``UPDATE..RETURNING`` and
  414. ``DELETE..RETURNING`` syntaxes. ``INSERT..RETURNING`` is used by default
  415. for single-row INSERT statements in order to fetch newly generated
  416. primary key identifiers. To specify an explicit ``RETURNING`` clause,
  417. use the :meth:`._UpdateBase.returning` method on a per-statement basis::
  418. # INSERT..RETURNING
  419. result = (
  420. table.insert().returning(table.c.col1, table.c.col2).values(name="foo")
  421. )
  422. print(result.fetchall())
  423. # UPDATE..RETURNING
  424. result = (
  425. table.update()
  426. .returning(table.c.col1, table.c.col2)
  427. .where(table.c.name == "foo")
  428. .values(name="bar")
  429. )
  430. print(result.fetchall())
  431. # DELETE..RETURNING
  432. result = (
  433. table.delete()
  434. .returning(table.c.col1, table.c.col2)
  435. .where(table.c.name == "foo")
  436. )
  437. print(result.fetchall())
  438. .. _postgresql_insert_on_conflict:
  439. INSERT...ON CONFLICT (Upsert)
  440. ------------------------------
  441. Starting with version 9.5, PostgreSQL allows "upserts" (update or insert) of
  442. rows into a table via the ``ON CONFLICT`` clause of the ``INSERT`` statement. A
  443. candidate row will only be inserted if that row does not violate any unique
  444. constraints. In the case of a unique constraint violation, a secondary action
  445. can occur which can be either "DO UPDATE", indicating that the data in the
  446. target row should be updated, or "DO NOTHING", which indicates to silently skip
  447. this row.
  448. Conflicts are determined using existing unique constraints and indexes. These
  449. constraints may be identified either using their name as stated in DDL,
  450. or they may be inferred by stating the columns and conditions that comprise
  451. the indexes.
  452. SQLAlchemy provides ``ON CONFLICT`` support via the PostgreSQL-specific
  453. :func:`_postgresql.insert()` function, which provides
  454. the generative methods :meth:`_postgresql.Insert.on_conflict_do_update`
  455. and :meth:`~.postgresql.Insert.on_conflict_do_nothing`:
  456. .. sourcecode:: pycon+sql
  457. >>> from sqlalchemy.dialects.postgresql import insert
  458. >>> insert_stmt = insert(my_table).values(
  459. ... id="some_existing_id", data="inserted value"
  460. ... )
  461. >>> do_nothing_stmt = insert_stmt.on_conflict_do_nothing(index_elements=["id"])
  462. >>> print(do_nothing_stmt)
  463. {printsql}INSERT INTO my_table (id, data) VALUES (%(id)s, %(data)s)
  464. ON CONFLICT (id) DO NOTHING
  465. {stop}
  466. >>> do_update_stmt = insert_stmt.on_conflict_do_update(
  467. ... constraint="pk_my_table", set_=dict(data="updated value")
  468. ... )
  469. >>> print(do_update_stmt)
  470. {printsql}INSERT INTO my_table (id, data) VALUES (%(id)s, %(data)s)
  471. ON CONFLICT ON CONSTRAINT pk_my_table DO UPDATE SET data = %(param_1)s
  472. .. seealso::
  473. `INSERT .. ON CONFLICT
  474. <https://www.postgresql.org/docs/current/static/sql-insert.html#SQL-ON-CONFLICT>`_
  475. - in the PostgreSQL documentation.
  476. Specifying the Target
  477. ^^^^^^^^^^^^^^^^^^^^^
  478. Both methods supply the "target" of the conflict using either the
  479. named constraint or by column inference:
  480. * The :paramref:`_postgresql.Insert.on_conflict_do_update.index_elements` argument
  481. specifies a sequence containing string column names, :class:`_schema.Column`
  482. objects, and/or SQL expression elements, which would identify a unique
  483. index:
  484. .. sourcecode:: pycon+sql
  485. >>> do_update_stmt = insert_stmt.on_conflict_do_update(
  486. ... index_elements=["id"], set_=dict(data="updated value")
  487. ... )
  488. >>> print(do_update_stmt)
  489. {printsql}INSERT INTO my_table (id, data) VALUES (%(id)s, %(data)s)
  490. ON CONFLICT (id) DO UPDATE SET data = %(param_1)s
  491. {stop}
  492. >>> do_update_stmt = insert_stmt.on_conflict_do_update(
  493. ... index_elements=[my_table.c.id], set_=dict(data="updated value")
  494. ... )
  495. >>> print(do_update_stmt)
  496. {printsql}INSERT INTO my_table (id, data) VALUES (%(id)s, %(data)s)
  497. ON CONFLICT (id) DO UPDATE SET data = %(param_1)s
  498. * When using :paramref:`_postgresql.Insert.on_conflict_do_update.index_elements` to
  499. infer an index, a partial index can be inferred by also specifying the
  500. use the :paramref:`_postgresql.Insert.on_conflict_do_update.index_where` parameter:
  501. .. sourcecode:: pycon+sql
  502. >>> stmt = insert(my_table).values(user_email="a@b.com", data="inserted data")
  503. >>> stmt = stmt.on_conflict_do_update(
  504. ... index_elements=[my_table.c.user_email],
  505. ... index_where=my_table.c.user_email.like("%@gmail.com"),
  506. ... set_=dict(data=stmt.excluded.data),
  507. ... )
  508. >>> print(stmt)
  509. {printsql}INSERT INTO my_table (data, user_email)
  510. VALUES (%(data)s, %(user_email)s) ON CONFLICT (user_email)
  511. WHERE user_email LIKE %(user_email_1)s DO UPDATE SET data = excluded.data
  512. * The :paramref:`_postgresql.Insert.on_conflict_do_update.constraint` argument is
  513. used to specify an index directly rather than inferring it. This can be
  514. the name of a UNIQUE constraint, a PRIMARY KEY constraint, or an INDEX:
  515. .. sourcecode:: pycon+sql
  516. >>> do_update_stmt = insert_stmt.on_conflict_do_update(
  517. ... constraint="my_table_idx_1", set_=dict(data="updated value")
  518. ... )
  519. >>> print(do_update_stmt)
  520. {printsql}INSERT INTO my_table (id, data) VALUES (%(id)s, %(data)s)
  521. ON CONFLICT ON CONSTRAINT my_table_idx_1 DO UPDATE SET data = %(param_1)s
  522. {stop}
  523. >>> do_update_stmt = insert_stmt.on_conflict_do_update(
  524. ... constraint="my_table_pk", set_=dict(data="updated value")
  525. ... )
  526. >>> print(do_update_stmt)
  527. {printsql}INSERT INTO my_table (id, data) VALUES (%(id)s, %(data)s)
  528. ON CONFLICT ON CONSTRAINT my_table_pk DO UPDATE SET data = %(param_1)s
  529. {stop}
  530. * The :paramref:`_postgresql.Insert.on_conflict_do_update.constraint` argument may
  531. also refer to a SQLAlchemy construct representing a constraint,
  532. e.g. :class:`.UniqueConstraint`, :class:`.PrimaryKeyConstraint`,
  533. :class:`.Index`, or :class:`.ExcludeConstraint`. In this use,
  534. if the constraint has a name, it is used directly. Otherwise, if the
  535. constraint is unnamed, then inference will be used, where the expressions
  536. and optional WHERE clause of the constraint will be spelled out in the
  537. construct. This use is especially convenient
  538. to refer to the named or unnamed primary key of a :class:`_schema.Table`
  539. using the
  540. :attr:`_schema.Table.primary_key` attribute:
  541. .. sourcecode:: pycon+sql
  542. >>> do_update_stmt = insert_stmt.on_conflict_do_update(
  543. ... constraint=my_table.primary_key, set_=dict(data="updated value")
  544. ... )
  545. >>> print(do_update_stmt)
  546. {printsql}INSERT INTO my_table (id, data) VALUES (%(id)s, %(data)s)
  547. ON CONFLICT (id) DO UPDATE SET data = %(param_1)s
  548. The SET Clause
  549. ^^^^^^^^^^^^^^^
  550. ``ON CONFLICT...DO UPDATE`` is used to perform an update of the already
  551. existing row, using any combination of new values as well as values
  552. from the proposed insertion. These values are specified using the
  553. :paramref:`_postgresql.Insert.on_conflict_do_update.set_` parameter. This
  554. parameter accepts a dictionary which consists of direct values
  555. for UPDATE:
  556. .. sourcecode:: pycon+sql
  557. >>> stmt = insert(my_table).values(id="some_id", data="inserted value")
  558. >>> do_update_stmt = stmt.on_conflict_do_update(
  559. ... index_elements=["id"], set_=dict(data="updated value")
  560. ... )
  561. >>> print(do_update_stmt)
  562. {printsql}INSERT INTO my_table (id, data) VALUES (%(id)s, %(data)s)
  563. ON CONFLICT (id) DO UPDATE SET data = %(param_1)s
  564. .. warning::
  565. The :meth:`_expression.Insert.on_conflict_do_update`
  566. method does **not** take into
  567. account Python-side default UPDATE values or generation functions, e.g.
  568. those specified using :paramref:`_schema.Column.onupdate`.
  569. These values will not be exercised for an ON CONFLICT style of UPDATE,
  570. unless they are manually specified in the
  571. :paramref:`_postgresql.Insert.on_conflict_do_update.set_` dictionary.
  572. Updating using the Excluded INSERT Values
  573. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  574. In order to refer to the proposed insertion row, the special alias
  575. :attr:`~.postgresql.Insert.excluded` is available as an attribute on
  576. the :class:`_postgresql.Insert` object; this object is a
  577. :class:`_expression.ColumnCollection`
  578. which alias contains all columns of the target
  579. table:
  580. .. sourcecode:: pycon+sql
  581. >>> stmt = insert(my_table).values(
  582. ... id="some_id", data="inserted value", author="jlh"
  583. ... )
  584. >>> do_update_stmt = stmt.on_conflict_do_update(
  585. ... index_elements=["id"],
  586. ... set_=dict(data="updated value", author=stmt.excluded.author),
  587. ... )
  588. >>> print(do_update_stmt)
  589. {printsql}INSERT INTO my_table (id, data, author)
  590. VALUES (%(id)s, %(data)s, %(author)s)
  591. ON CONFLICT (id) DO UPDATE SET data = %(param_1)s, author = excluded.author
  592. Additional WHERE Criteria
  593. ^^^^^^^^^^^^^^^^^^^^^^^^^
  594. The :meth:`_expression.Insert.on_conflict_do_update` method also accepts
  595. a WHERE clause using the :paramref:`_postgresql.Insert.on_conflict_do_update.where`
  596. parameter, which will limit those rows which receive an UPDATE:
  597. .. sourcecode:: pycon+sql
  598. >>> stmt = insert(my_table).values(
  599. ... id="some_id", data="inserted value", author="jlh"
  600. ... )
  601. >>> on_update_stmt = stmt.on_conflict_do_update(
  602. ... index_elements=["id"],
  603. ... set_=dict(data="updated value", author=stmt.excluded.author),
  604. ... where=(my_table.c.status == 2),
  605. ... )
  606. >>> print(on_update_stmt)
  607. {printsql}INSERT INTO my_table (id, data, author)
  608. VALUES (%(id)s, %(data)s, %(author)s)
  609. ON CONFLICT (id) DO UPDATE SET data = %(param_1)s, author = excluded.author
  610. WHERE my_table.status = %(status_1)s
  611. Skipping Rows with DO NOTHING
  612. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  613. ``ON CONFLICT`` may be used to skip inserting a row entirely
  614. if any conflict with a unique or exclusion constraint occurs; below
  615. this is illustrated using the
  616. :meth:`~.postgresql.Insert.on_conflict_do_nothing` method:
  617. .. sourcecode:: pycon+sql
  618. >>> stmt = insert(my_table).values(id="some_id", data="inserted value")
  619. >>> stmt = stmt.on_conflict_do_nothing(index_elements=["id"])
  620. >>> print(stmt)
  621. {printsql}INSERT INTO my_table (id, data) VALUES (%(id)s, %(data)s)
  622. ON CONFLICT (id) DO NOTHING
  623. If ``DO NOTHING`` is used without specifying any columns or constraint,
  624. it has the effect of skipping the INSERT for any unique or exclusion
  625. constraint violation which occurs:
  626. .. sourcecode:: pycon+sql
  627. >>> stmt = insert(my_table).values(id="some_id", data="inserted value")
  628. >>> stmt = stmt.on_conflict_do_nothing()
  629. >>> print(stmt)
  630. {printsql}INSERT INTO my_table (id, data) VALUES (%(id)s, %(data)s)
  631. ON CONFLICT DO NOTHING
  632. .. _postgresql_match:
  633. Full Text Search
  634. ----------------
  635. PostgreSQL's full text search system is available through the use of the
  636. :data:`.func` namespace, combined with the use of custom operators
  637. via the :meth:`.Operators.bool_op` method. For simple cases with some
  638. degree of cross-backend compatibility, the :meth:`.Operators.match` operator
  639. may also be used.
  640. .. _postgresql_simple_match:
  641. Simple plain text matching with ``match()``
  642. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  643. The :meth:`.Operators.match` operator provides for cross-compatible simple
  644. text matching. For the PostgreSQL backend, it's hardcoded to generate
  645. an expression using the ``@@`` operator in conjunction with the
  646. ``plainto_tsquery()`` PostgreSQL function.
  647. On the PostgreSQL dialect, an expression like the following::
  648. select(sometable.c.text.match("search string"))
  649. would emit to the database:
  650. .. sourcecode:: sql
  651. SELECT text @@ plainto_tsquery('search string') FROM table
  652. Above, passing a plain string to :meth:`.Operators.match` will automatically
  653. make use of ``plainto_tsquery()`` to specify the type of tsquery. This
  654. establishes basic database cross-compatibility for :meth:`.Operators.match`
  655. with other backends.
  656. .. versionchanged:: 2.0 The default tsquery generation function used by the
  657. PostgreSQL dialect with :meth:`.Operators.match` is ``plainto_tsquery()``.
  658. To render exactly what was rendered in 1.4, use the following form::
  659. from sqlalchemy import func
  660. select(sometable.c.text.bool_op("@@")(func.to_tsquery("search string")))
  661. Which would emit:
  662. .. sourcecode:: sql
  663. SELECT text @@ to_tsquery('search string') FROM table
  664. Using PostgreSQL full text functions and operators directly
  665. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  666. Text search operations beyond the simple use of :meth:`.Operators.match`
  667. may make use of the :data:`.func` namespace to generate PostgreSQL full-text
  668. functions, in combination with :meth:`.Operators.bool_op` to generate
  669. any boolean operator.
  670. For example, the query::
  671. select(func.to_tsquery("cat").bool_op("@>")(func.to_tsquery("cat & rat")))
  672. would generate:
  673. .. sourcecode:: sql
  674. SELECT to_tsquery('cat') @> to_tsquery('cat & rat')
  675. The :class:`_postgresql.TSVECTOR` type can provide for explicit CAST::
  676. from sqlalchemy.dialects.postgresql import TSVECTOR
  677. from sqlalchemy import select, cast
  678. select(cast("some text", TSVECTOR))
  679. produces a statement equivalent to:
  680. .. sourcecode:: sql
  681. SELECT CAST('some text' AS TSVECTOR) AS anon_1
  682. The ``func`` namespace is augmented by the PostgreSQL dialect to set up
  683. correct argument and return types for most full text search functions.
  684. These functions are used automatically by the :attr:`_sql.func` namespace
  685. assuming the ``sqlalchemy.dialects.postgresql`` package has been imported,
  686. or :func:`_sa.create_engine` has been invoked using a ``postgresql``
  687. dialect. These functions are documented at:
  688. * :class:`_postgresql.to_tsvector`
  689. * :class:`_postgresql.to_tsquery`
  690. * :class:`_postgresql.plainto_tsquery`
  691. * :class:`_postgresql.phraseto_tsquery`
  692. * :class:`_postgresql.websearch_to_tsquery`
  693. * :class:`_postgresql.ts_headline`
  694. Specifying the "regconfig" with ``match()`` or custom operators
  695. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  696. PostgreSQL's ``plainto_tsquery()`` function accepts an optional
  697. "regconfig" argument that is used to instruct PostgreSQL to use a
  698. particular pre-computed GIN or GiST index in order to perform the search.
  699. When using :meth:`.Operators.match`, this additional parameter may be
  700. specified using the ``postgresql_regconfig`` parameter, such as::
  701. select(mytable.c.id).where(
  702. mytable.c.title.match("somestring", postgresql_regconfig="english")
  703. )
  704. Which would emit:
  705. .. sourcecode:: sql
  706. SELECT mytable.id FROM mytable
  707. WHERE mytable.title @@ plainto_tsquery('english', 'somestring')
  708. When using other PostgreSQL search functions with :data:`.func`, the
  709. "regconfig" parameter may be passed directly as the initial argument::
  710. select(mytable.c.id).where(
  711. func.to_tsvector("english", mytable.c.title).bool_op("@@")(
  712. func.to_tsquery("english", "somestring")
  713. )
  714. )
  715. produces a statement equivalent to:
  716. .. sourcecode:: sql
  717. SELECT mytable.id FROM mytable
  718. WHERE to_tsvector('english', mytable.title) @@
  719. to_tsquery('english', 'somestring')
  720. It is recommended that you use the ``EXPLAIN ANALYZE...`` tool from
  721. PostgreSQL to ensure that you are generating queries with SQLAlchemy that
  722. take full advantage of any indexes you may have created for full text search.
  723. .. seealso::
  724. `Full Text Search <https://www.postgresql.org/docs/current/textsearch-controls.html>`_ - in the PostgreSQL documentation
  725. FROM ONLY ...
  726. -------------
  727. The dialect supports PostgreSQL's ONLY keyword for targeting only a particular
  728. table in an inheritance hierarchy. This can be used to produce the
  729. ``SELECT ... FROM ONLY``, ``UPDATE ONLY ...``, and ``DELETE FROM ONLY ...``
  730. syntaxes. It uses SQLAlchemy's hints mechanism::
  731. # SELECT ... FROM ONLY ...
  732. result = table.select().with_hint(table, "ONLY", "postgresql")
  733. print(result.fetchall())
  734. # UPDATE ONLY ...
  735. table.update(values=dict(foo="bar")).with_hint(
  736. "ONLY", dialect_name="postgresql"
  737. )
  738. # DELETE FROM ONLY ...
  739. table.delete().with_hint("ONLY", dialect_name="postgresql")
  740. .. _postgresql_indexes:
  741. PostgreSQL-Specific Index Options
  742. ---------------------------------
  743. Several extensions to the :class:`.Index` construct are available, specific
  744. to the PostgreSQL dialect.
  745. .. _postgresql_covering_indexes:
  746. Covering Indexes
  747. ^^^^^^^^^^^^^^^^
  748. The ``postgresql_include`` option renders INCLUDE(colname) for the given
  749. string names::
  750. Index("my_index", table.c.x, postgresql_include=["y"])
  751. would render the index as ``CREATE INDEX my_index ON table (x) INCLUDE (y)``
  752. Note that this feature requires PostgreSQL 11 or later.
  753. .. seealso::
  754. :ref:`postgresql_constraint_options`
  755. .. versionadded:: 1.4
  756. .. _postgresql_partial_indexes:
  757. Partial Indexes
  758. ^^^^^^^^^^^^^^^
  759. Partial indexes add criterion to the index definition so that the index is
  760. applied to a subset of rows. These can be specified on :class:`.Index`
  761. using the ``postgresql_where`` keyword argument::
  762. Index("my_index", my_table.c.id, postgresql_where=my_table.c.value > 10)
  763. .. _postgresql_operator_classes:
  764. Operator Classes
  765. ^^^^^^^^^^^^^^^^
  766. PostgreSQL allows the specification of an *operator class* for each column of
  767. an index (see
  768. https://www.postgresql.org/docs/current/interactive/indexes-opclass.html).
  769. The :class:`.Index` construct allows these to be specified via the
  770. ``postgresql_ops`` keyword argument::
  771. Index(
  772. "my_index",
  773. my_table.c.id,
  774. my_table.c.data,
  775. postgresql_ops={"data": "text_pattern_ops", "id": "int4_ops"},
  776. )
  777. Note that the keys in the ``postgresql_ops`` dictionaries are the
  778. "key" name of the :class:`_schema.Column`, i.e. the name used to access it from
  779. the ``.c`` collection of :class:`_schema.Table`, which can be configured to be
  780. different than the actual name of the column as expressed in the database.
  781. If ``postgresql_ops`` is to be used against a complex SQL expression such
  782. as a function call, then to apply to the column it must be given a label
  783. that is identified in the dictionary by name, e.g.::
  784. Index(
  785. "my_index",
  786. my_table.c.id,
  787. func.lower(my_table.c.data).label("data_lower"),
  788. postgresql_ops={"data_lower": "text_pattern_ops", "id": "int4_ops"},
  789. )
  790. Operator classes are also supported by the
  791. :class:`_postgresql.ExcludeConstraint` construct using the
  792. :paramref:`_postgresql.ExcludeConstraint.ops` parameter. See that parameter for
  793. details.
  794. .. versionadded:: 1.3.21 added support for operator classes with
  795. :class:`_postgresql.ExcludeConstraint`.
  796. Index Types
  797. ^^^^^^^^^^^
  798. PostgreSQL provides several index types: B-Tree, Hash, GiST, and GIN, as well
  799. as the ability for users to create their own (see
  800. https://www.postgresql.org/docs/current/static/indexes-types.html). These can be
  801. specified on :class:`.Index` using the ``postgresql_using`` keyword argument::
  802. Index("my_index", my_table.c.data, postgresql_using="gin")
  803. The value passed to the keyword argument will be simply passed through to the
  804. underlying CREATE INDEX command, so it *must* be a valid index type for your
  805. version of PostgreSQL.
  806. .. _postgresql_index_storage:
  807. Index Storage Parameters
  808. ^^^^^^^^^^^^^^^^^^^^^^^^
  809. PostgreSQL allows storage parameters to be set on indexes. The storage
  810. parameters available depend on the index method used by the index. Storage
  811. parameters can be specified on :class:`.Index` using the ``postgresql_with``
  812. keyword argument::
  813. Index("my_index", my_table.c.data, postgresql_with={"fillfactor": 50})
  814. PostgreSQL allows to define the tablespace in which to create the index.
  815. The tablespace can be specified on :class:`.Index` using the
  816. ``postgresql_tablespace`` keyword argument::
  817. Index("my_index", my_table.c.data, postgresql_tablespace="my_tablespace")
  818. Note that the same option is available on :class:`_schema.Table` as well.
  819. .. _postgresql_index_concurrently:
  820. Indexes with CONCURRENTLY
  821. ^^^^^^^^^^^^^^^^^^^^^^^^^
  822. The PostgreSQL index option CONCURRENTLY is supported by passing the
  823. flag ``postgresql_concurrently`` to the :class:`.Index` construct::
  824. tbl = Table("testtbl", m, Column("data", Integer))
  825. idx1 = Index("test_idx1", tbl.c.data, postgresql_concurrently=True)
  826. The above index construct will render DDL for CREATE INDEX, assuming
  827. PostgreSQL 8.2 or higher is detected or for a connection-less dialect, as:
  828. .. sourcecode:: sql
  829. CREATE INDEX CONCURRENTLY test_idx1 ON testtbl (data)
  830. For DROP INDEX, assuming PostgreSQL 9.2 or higher is detected or for
  831. a connection-less dialect, it will emit:
  832. .. sourcecode:: sql
  833. DROP INDEX CONCURRENTLY test_idx1
  834. When using CONCURRENTLY, the PostgreSQL database requires that the statement
  835. be invoked outside of a transaction block. The Python DBAPI enforces that
  836. even for a single statement, a transaction is present, so to use this
  837. construct, the DBAPI's "autocommit" mode must be used::
  838. metadata = MetaData()
  839. table = Table("foo", metadata, Column("id", String))
  840. index = Index("foo_idx", table.c.id, postgresql_concurrently=True)
  841. with engine.connect() as conn:
  842. with conn.execution_options(isolation_level="AUTOCOMMIT"):
  843. table.create(conn)
  844. .. seealso::
  845. :ref:`postgresql_isolation_level`
  846. .. _postgresql_index_reflection:
  847. PostgreSQL Index Reflection
  848. ---------------------------
  849. The PostgreSQL database creates a UNIQUE INDEX implicitly whenever the
  850. UNIQUE CONSTRAINT construct is used. When inspecting a table using
  851. :class:`_reflection.Inspector`, the :meth:`_reflection.Inspector.get_indexes`
  852. and the :meth:`_reflection.Inspector.get_unique_constraints`
  853. will report on these
  854. two constructs distinctly; in the case of the index, the key
  855. ``duplicates_constraint`` will be present in the index entry if it is
  856. detected as mirroring a constraint. When performing reflection using
  857. ``Table(..., autoload_with=engine)``, the UNIQUE INDEX is **not** returned
  858. in :attr:`_schema.Table.indexes` when it is detected as mirroring a
  859. :class:`.UniqueConstraint` in the :attr:`_schema.Table.constraints` collection
  860. .
  861. Special Reflection Options
  862. --------------------------
  863. The :class:`_reflection.Inspector`
  864. used for the PostgreSQL backend is an instance
  865. of :class:`.PGInspector`, which offers additional methods::
  866. from sqlalchemy import create_engine, inspect
  867. engine = create_engine("postgresql+psycopg2://localhost/test")
  868. insp = inspect(engine) # will be a PGInspector
  869. print(insp.get_enums())
  870. .. autoclass:: PGInspector
  871. :members:
  872. .. _postgresql_table_options:
  873. PostgreSQL Table Options
  874. ------------------------
  875. Several options for CREATE TABLE are supported directly by the PostgreSQL
  876. dialect in conjunction with the :class:`_schema.Table` construct:
  877. * ``INHERITS``::
  878. Table("some_table", metadata, ..., postgresql_inherits="some_supertable")
  879. Table("some_table", metadata, ..., postgresql_inherits=("t1", "t2", ...))
  880. * ``ON COMMIT``::
  881. Table("some_table", metadata, ..., postgresql_on_commit="PRESERVE ROWS")
  882. *
  883. ``PARTITION BY``::
  884. Table(
  885. "some_table",
  886. metadata,
  887. ...,
  888. postgresql_partition_by="LIST (part_column)",
  889. )
  890. .. versionadded:: 1.2.6
  891. *
  892. ``TABLESPACE``::
  893. Table("some_table", metadata, ..., postgresql_tablespace="some_tablespace")
  894. The above option is also available on the :class:`.Index` construct.
  895. *
  896. ``USING``::
  897. Table("some_table", metadata, ..., postgresql_using="heap")
  898. .. versionadded:: 2.0.26
  899. * ``WITH OIDS``::
  900. Table("some_table", metadata, ..., postgresql_with_oids=True)
  901. * ``WITHOUT OIDS``::
  902. Table("some_table", metadata, ..., postgresql_with_oids=False)
  903. .. seealso::
  904. `PostgreSQL CREATE TABLE options
  905. <https://www.postgresql.org/docs/current/static/sql-createtable.html>`_ -
  906. in the PostgreSQL documentation.
  907. .. _postgresql_constraint_options:
  908. PostgreSQL Constraint Options
  909. -----------------------------
  910. The following option(s) are supported by the PostgreSQL dialect in conjunction
  911. with selected constraint constructs:
  912. * ``NOT VALID``: This option applies towards CHECK and FOREIGN KEY constraints
  913. when the constraint is being added to an existing table via ALTER TABLE,
  914. and has the effect that existing rows are not scanned during the ALTER
  915. operation against the constraint being added.
  916. When using a SQL migration tool such as `Alembic <https://alembic.sqlalchemy.org>`_
  917. that renders ALTER TABLE constructs, the ``postgresql_not_valid`` argument
  918. may be specified as an additional keyword argument within the operation
  919. that creates the constraint, as in the following Alembic example::
  920. def update():
  921. op.create_foreign_key(
  922. "fk_user_address",
  923. "address",
  924. "user",
  925. ["user_id"],
  926. ["id"],
  927. postgresql_not_valid=True,
  928. )
  929. The keyword is ultimately accepted directly by the
  930. :class:`_schema.CheckConstraint`, :class:`_schema.ForeignKeyConstraint`
  931. and :class:`_schema.ForeignKey` constructs; when using a tool like
  932. Alembic, dialect-specific keyword arguments are passed through to
  933. these constructs from the migration operation directives::
  934. CheckConstraint("some_field IS NOT NULL", postgresql_not_valid=True)
  935. ForeignKeyConstraint(
  936. ["some_id"], ["some_table.some_id"], postgresql_not_valid=True
  937. )
  938. .. versionadded:: 1.4.32
  939. .. seealso::
  940. `PostgreSQL ALTER TABLE options
  941. <https://www.postgresql.org/docs/current/static/sql-altertable.html>`_ -
  942. in the PostgreSQL documentation.
  943. * ``INCLUDE``: This option adds one or more columns as a "payload" to the
  944. unique index created automatically by PostgreSQL for the constraint.
  945. For example, the following table definition::
  946. Table(
  947. "mytable",
  948. metadata,
  949. Column("id", Integer, nullable=False),
  950. Column("value", Integer, nullable=False),
  951. UniqueConstraint("id", postgresql_include=["value"]),
  952. )
  953. would produce the DDL statement
  954. .. sourcecode:: sql
  955. CREATE TABLE mytable (
  956. id INTEGER NOT NULL,
  957. value INTEGER NOT NULL,
  958. UNIQUE (id) INCLUDE (value)
  959. )
  960. Note that this feature requires PostgreSQL 11 or later.
  961. .. versionadded:: 2.0.41
  962. .. seealso::
  963. :ref:`postgresql_covering_indexes`
  964. .. seealso::
  965. `PostgreSQL CREATE TABLE options
  966. <https://www.postgresql.org/docs/current/static/sql-createtable.html>`_ -
  967. in the PostgreSQL documentation.
  968. * Column list with foreign key ``ON DELETE SET`` actions: This applies to
  969. :class:`.ForeignKey` and :class:`.ForeignKeyConstraint`, the :paramref:`.ForeignKey.ondelete`
  970. parameter will accept on the PostgreSQL backend only a string list of column
  971. names inside parenthesis, following the ``SET NULL`` or ``SET DEFAULT``
  972. phrases, which will limit the set of columns that are subject to the
  973. action::
  974. fktable = Table(
  975. "fktable",
  976. metadata,
  977. Column("tid", Integer),
  978. Column("id", Integer),
  979. Column("fk_id_del_set_null", Integer),
  980. ForeignKeyConstraint(
  981. columns=["tid", "fk_id_del_set_null"],
  982. refcolumns=[pktable.c.tid, pktable.c.id],
  983. ondelete="SET NULL (fk_id_del_set_null)",
  984. ),
  985. )
  986. .. versionadded:: 2.0.40
  987. .. _postgresql_table_valued_overview:
  988. Table values, Table and Column valued functions, Row and Tuple objects
  989. -----------------------------------------------------------------------
  990. PostgreSQL makes great use of modern SQL forms such as table-valued functions,
  991. tables and rows as values. These constructs are commonly used as part
  992. of PostgreSQL's support for complex datatypes such as JSON, ARRAY, and other
  993. datatypes. SQLAlchemy's SQL expression language has native support for
  994. most table-valued and row-valued forms.
  995. .. _postgresql_table_valued:
  996. Table-Valued Functions
  997. ^^^^^^^^^^^^^^^^^^^^^^^
  998. Many PostgreSQL built-in functions are intended to be used in the FROM clause
  999. of a SELECT statement, and are capable of returning table rows or sets of table
  1000. rows. A large portion of PostgreSQL's JSON functions for example such as
  1001. ``json_array_elements()``, ``json_object_keys()``, ``json_each_text()``,
  1002. ``json_each()``, ``json_to_record()``, ``json_populate_recordset()`` use such
  1003. forms. These classes of SQL function calling forms in SQLAlchemy are available
  1004. using the :meth:`_functions.FunctionElement.table_valued` method in conjunction
  1005. with :class:`_functions.Function` objects generated from the :data:`_sql.func`
  1006. namespace.
  1007. Examples from PostgreSQL's reference documentation follow below:
  1008. * ``json_each()``:
  1009. .. sourcecode:: pycon+sql
  1010. >>> from sqlalchemy import select, func
  1011. >>> stmt = select(
  1012. ... func.json_each('{"a":"foo", "b":"bar"}').table_valued("key", "value")
  1013. ... )
  1014. >>> print(stmt)
  1015. {printsql}SELECT anon_1.key, anon_1.value
  1016. FROM json_each(:json_each_1) AS anon_1
  1017. * ``json_populate_record()``:
  1018. .. sourcecode:: pycon+sql
  1019. >>> from sqlalchemy import select, func, literal_column
  1020. >>> stmt = select(
  1021. ... func.json_populate_record(
  1022. ... literal_column("null::myrowtype"), '{"a":1,"b":2}'
  1023. ... ).table_valued("a", "b", name="x")
  1024. ... )
  1025. >>> print(stmt)
  1026. {printsql}SELECT x.a, x.b
  1027. FROM json_populate_record(null::myrowtype, :json_populate_record_1) AS x
  1028. * ``json_to_record()`` - this form uses a PostgreSQL specific form of derived
  1029. columns in the alias, where we may make use of :func:`_sql.column` elements with
  1030. types to produce them. The :meth:`_functions.FunctionElement.table_valued`
  1031. method produces a :class:`_sql.TableValuedAlias` construct, and the method
  1032. :meth:`_sql.TableValuedAlias.render_derived` method sets up the derived
  1033. columns specification:
  1034. .. sourcecode:: pycon+sql
  1035. >>> from sqlalchemy import select, func, column, Integer, Text
  1036. >>> stmt = select(
  1037. ... func.json_to_record('{"a":1,"b":[1,2,3],"c":"bar"}')
  1038. ... .table_valued(
  1039. ... column("a", Integer),
  1040. ... column("b", Text),
  1041. ... column("d", Text),
  1042. ... )
  1043. ... .render_derived(name="x", with_types=True)
  1044. ... )
  1045. >>> print(stmt)
  1046. {printsql}SELECT x.a, x.b, x.d
  1047. FROM json_to_record(:json_to_record_1) AS x(a INTEGER, b TEXT, d TEXT)
  1048. * ``WITH ORDINALITY`` - part of the SQL standard, ``WITH ORDINALITY`` adds an
  1049. ordinal counter to the output of a function and is accepted by a limited set
  1050. of PostgreSQL functions including ``unnest()`` and ``generate_series()``. The
  1051. :meth:`_functions.FunctionElement.table_valued` method accepts a keyword
  1052. parameter ``with_ordinality`` for this purpose, which accepts the string name
  1053. that will be applied to the "ordinality" column:
  1054. .. sourcecode:: pycon+sql
  1055. >>> from sqlalchemy import select, func
  1056. >>> stmt = select(
  1057. ... func.generate_series(4, 1, -1)
  1058. ... .table_valued("value", with_ordinality="ordinality")
  1059. ... .render_derived()
  1060. ... )
  1061. >>> print(stmt)
  1062. {printsql}SELECT anon_1.value, anon_1.ordinality
  1063. FROM generate_series(:generate_series_1, :generate_series_2, :generate_series_3)
  1064. WITH ORDINALITY AS anon_1(value, ordinality)
  1065. .. versionadded:: 1.4.0b2
  1066. .. seealso::
  1067. :ref:`tutorial_functions_table_valued` - in the :ref:`unified_tutorial`
  1068. .. _postgresql_column_valued:
  1069. Column Valued Functions
  1070. ^^^^^^^^^^^^^^^^^^^^^^^
  1071. Similar to the table valued function, a column valued function is present
  1072. in the FROM clause, but delivers itself to the columns clause as a single
  1073. scalar value. PostgreSQL functions such as ``json_array_elements()``,
  1074. ``unnest()`` and ``generate_series()`` may use this form. Column valued functions are available using the
  1075. :meth:`_functions.FunctionElement.column_valued` method of :class:`_functions.FunctionElement`:
  1076. * ``json_array_elements()``:
  1077. .. sourcecode:: pycon+sql
  1078. >>> from sqlalchemy import select, func
  1079. >>> stmt = select(
  1080. ... func.json_array_elements('["one", "two"]').column_valued("x")
  1081. ... )
  1082. >>> print(stmt)
  1083. {printsql}SELECT x
  1084. FROM json_array_elements(:json_array_elements_1) AS x
  1085. * ``unnest()`` - in order to generate a PostgreSQL ARRAY literal, the
  1086. :func:`_postgresql.array` construct may be used:
  1087. .. sourcecode:: pycon+sql
  1088. >>> from sqlalchemy.dialects.postgresql import array
  1089. >>> from sqlalchemy import select, func
  1090. >>> stmt = select(func.unnest(array([1, 2])).column_valued())
  1091. >>> print(stmt)
  1092. {printsql}SELECT anon_1
  1093. FROM unnest(ARRAY[%(param_1)s, %(param_2)s]) AS anon_1
  1094. The function can of course be used against an existing table-bound column
  1095. that's of type :class:`_types.ARRAY`:
  1096. .. sourcecode:: pycon+sql
  1097. >>> from sqlalchemy import table, column, ARRAY, Integer
  1098. >>> from sqlalchemy import select, func
  1099. >>> t = table("t", column("value", ARRAY(Integer)))
  1100. >>> stmt = select(func.unnest(t.c.value).column_valued("unnested_value"))
  1101. >>> print(stmt)
  1102. {printsql}SELECT unnested_value
  1103. FROM unnest(t.value) AS unnested_value
  1104. .. seealso::
  1105. :ref:`tutorial_functions_column_valued` - in the :ref:`unified_tutorial`
  1106. Row Types
  1107. ^^^^^^^^^
  1108. Built-in support for rendering a ``ROW`` may be approximated using
  1109. ``func.ROW`` with the :attr:`_sa.func` namespace, or by using the
  1110. :func:`_sql.tuple_` construct:
  1111. .. sourcecode:: pycon+sql
  1112. >>> from sqlalchemy import table, column, func, tuple_
  1113. >>> t = table("t", column("id"), column("fk"))
  1114. >>> stmt = (
  1115. ... t.select()
  1116. ... .where(tuple_(t.c.id, t.c.fk) > (1, 2))
  1117. ... .where(func.ROW(t.c.id, t.c.fk) < func.ROW(3, 7))
  1118. ... )
  1119. >>> print(stmt)
  1120. {printsql}SELECT t.id, t.fk
  1121. FROM t
  1122. WHERE (t.id, t.fk) > (:param_1, :param_2) AND ROW(t.id, t.fk) < ROW(:ROW_1, :ROW_2)
  1123. .. seealso::
  1124. `PostgreSQL Row Constructors
  1125. <https://www.postgresql.org/docs/current/sql-expressions.html#SQL-SYNTAX-ROW-CONSTRUCTORS>`_
  1126. `PostgreSQL Row Constructor Comparison
  1127. <https://www.postgresql.org/docs/current/functions-comparisons.html#ROW-WISE-COMPARISON>`_
  1128. Table Types passed to Functions
  1129. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  1130. PostgreSQL supports passing a table as an argument to a function, which is
  1131. known as a "record" type. SQLAlchemy :class:`_sql.FromClause` objects
  1132. such as :class:`_schema.Table` support this special form using the
  1133. :meth:`_sql.FromClause.table_valued` method, which is comparable to the
  1134. :meth:`_functions.FunctionElement.table_valued` method except that the collection
  1135. of columns is already established by that of the :class:`_sql.FromClause`
  1136. itself:
  1137. .. sourcecode:: pycon+sql
  1138. >>> from sqlalchemy import table, column, func, select
  1139. >>> a = table("a", column("id"), column("x"), column("y"))
  1140. >>> stmt = select(func.row_to_json(a.table_valued()))
  1141. >>> print(stmt)
  1142. {printsql}SELECT row_to_json(a) AS row_to_json_1
  1143. FROM a
  1144. .. versionadded:: 1.4.0b2
  1145. """ # noqa: E501
  1146. from __future__ import annotations
  1147. from collections import defaultdict
  1148. from functools import lru_cache
  1149. import re
  1150. from typing import Any
  1151. from typing import cast
  1152. from typing import Dict
  1153. from typing import List
  1154. from typing import Optional
  1155. from typing import Tuple
  1156. from typing import TYPE_CHECKING
  1157. from typing import Union
  1158. from . import arraylib as _array
  1159. from . import json as _json
  1160. from . import pg_catalog
  1161. from . import ranges as _ranges
  1162. from .ext import _regconfig_fn
  1163. from .ext import aggregate_order_by
  1164. from .hstore import HSTORE
  1165. from .named_types import CreateDomainType as CreateDomainType # noqa: F401
  1166. from .named_types import CreateEnumType as CreateEnumType # noqa: F401
  1167. from .named_types import DOMAIN as DOMAIN # noqa: F401
  1168. from .named_types import DropDomainType as DropDomainType # noqa: F401
  1169. from .named_types import DropEnumType as DropEnumType # noqa: F401
  1170. from .named_types import ENUM as ENUM # noqa: F401
  1171. from .named_types import NamedType as NamedType # noqa: F401
  1172. from .types import _DECIMAL_TYPES # noqa: F401
  1173. from .types import _FLOAT_TYPES # noqa: F401
  1174. from .types import _INT_TYPES # noqa: F401
  1175. from .types import BIT as BIT
  1176. from .types import BYTEA as BYTEA
  1177. from .types import CIDR as CIDR
  1178. from .types import CITEXT as CITEXT
  1179. from .types import INET as INET
  1180. from .types import INTERVAL as INTERVAL
  1181. from .types import MACADDR as MACADDR
  1182. from .types import MACADDR8 as MACADDR8
  1183. from .types import MONEY as MONEY
  1184. from .types import OID as OID
  1185. from .types import PGBit as PGBit # noqa: F401
  1186. from .types import PGCidr as PGCidr # noqa: F401
  1187. from .types import PGInet as PGInet # noqa: F401
  1188. from .types import PGInterval as PGInterval # noqa: F401
  1189. from .types import PGMacAddr as PGMacAddr # noqa: F401
  1190. from .types import PGMacAddr8 as PGMacAddr8 # noqa: F401
  1191. from .types import PGUuid as PGUuid
  1192. from .types import REGCLASS as REGCLASS
  1193. from .types import REGCONFIG as REGCONFIG # noqa: F401
  1194. from .types import TIME as TIME
  1195. from .types import TIMESTAMP as TIMESTAMP
  1196. from .types import TSVECTOR as TSVECTOR
  1197. from ... import exc
  1198. from ... import schema
  1199. from ... import select
  1200. from ... import sql
  1201. from ... import util
  1202. from ...engine import characteristics
  1203. from ...engine import default
  1204. from ...engine import interfaces
  1205. from ...engine import ObjectKind
  1206. from ...engine import ObjectScope
  1207. from ...engine import reflection
  1208. from ...engine import URL
  1209. from ...engine.reflection import ReflectionDefaults
  1210. from ...sql import bindparam
  1211. from ...sql import coercions
  1212. from ...sql import compiler
  1213. from ...sql import elements
  1214. from ...sql import expression
  1215. from ...sql import roles
  1216. from ...sql import sqltypes
  1217. from ...sql import util as sql_util
  1218. from ...sql.compiler import InsertmanyvaluesSentinelOpts
  1219. from ...sql.visitors import InternalTraversal
  1220. from ...types import BIGINT
  1221. from ...types import BOOLEAN
  1222. from ...types import CHAR
  1223. from ...types import DATE
  1224. from ...types import DOUBLE_PRECISION
  1225. from ...types import FLOAT
  1226. from ...types import INTEGER
  1227. from ...types import NUMERIC
  1228. from ...types import REAL
  1229. from ...types import SMALLINT
  1230. from ...types import TEXT
  1231. from ...types import UUID as UUID
  1232. from ...types import VARCHAR
  1233. from ...util.typing import TypedDict
  1234. IDX_USING = re.compile(r"^(?:btree|hash|gist|gin|[\w_]+)$", re.I)
  1235. RESERVED_WORDS = {
  1236. "all",
  1237. "analyse",
  1238. "analyze",
  1239. "and",
  1240. "any",
  1241. "array",
  1242. "as",
  1243. "asc",
  1244. "asymmetric",
  1245. "both",
  1246. "case",
  1247. "cast",
  1248. "check",
  1249. "collate",
  1250. "column",
  1251. "constraint",
  1252. "create",
  1253. "current_catalog",
  1254. "current_date",
  1255. "current_role",
  1256. "current_time",
  1257. "current_timestamp",
  1258. "current_user",
  1259. "default",
  1260. "deferrable",
  1261. "desc",
  1262. "distinct",
  1263. "do",
  1264. "else",
  1265. "end",
  1266. "except",
  1267. "false",
  1268. "fetch",
  1269. "for",
  1270. "foreign",
  1271. "from",
  1272. "grant",
  1273. "group",
  1274. "having",
  1275. "in",
  1276. "initially",
  1277. "intersect",
  1278. "into",
  1279. "leading",
  1280. "limit",
  1281. "localtime",
  1282. "localtimestamp",
  1283. "new",
  1284. "not",
  1285. "null",
  1286. "of",
  1287. "off",
  1288. "offset",
  1289. "old",
  1290. "on",
  1291. "only",
  1292. "or",
  1293. "order",
  1294. "placing",
  1295. "primary",
  1296. "references",
  1297. "returning",
  1298. "select",
  1299. "session_user",
  1300. "some",
  1301. "symmetric",
  1302. "table",
  1303. "then",
  1304. "to",
  1305. "trailing",
  1306. "true",
  1307. "union",
  1308. "unique",
  1309. "user",
  1310. "using",
  1311. "variadic",
  1312. "when",
  1313. "where",
  1314. "window",
  1315. "with",
  1316. "authorization",
  1317. "between",
  1318. "binary",
  1319. "cross",
  1320. "current_schema",
  1321. "freeze",
  1322. "full",
  1323. "ilike",
  1324. "inner",
  1325. "is",
  1326. "isnull",
  1327. "join",
  1328. "left",
  1329. "like",
  1330. "natural",
  1331. "notnull",
  1332. "outer",
  1333. "over",
  1334. "overlaps",
  1335. "right",
  1336. "similar",
  1337. "verbose",
  1338. }
  1339. colspecs = {
  1340. sqltypes.ARRAY: _array.ARRAY,
  1341. sqltypes.Interval: INTERVAL,
  1342. sqltypes.Enum: ENUM,
  1343. sqltypes.JSON.JSONPathType: _json.JSONPATH,
  1344. sqltypes.JSON: _json.JSON,
  1345. sqltypes.Uuid: PGUuid,
  1346. }
  1347. ischema_names = {
  1348. "_array": _array.ARRAY,
  1349. "hstore": HSTORE,
  1350. "json": _json.JSON,
  1351. "jsonb": _json.JSONB,
  1352. "int4range": _ranges.INT4RANGE,
  1353. "int8range": _ranges.INT8RANGE,
  1354. "numrange": _ranges.NUMRANGE,
  1355. "daterange": _ranges.DATERANGE,
  1356. "tsrange": _ranges.TSRANGE,
  1357. "tstzrange": _ranges.TSTZRANGE,
  1358. "int4multirange": _ranges.INT4MULTIRANGE,
  1359. "int8multirange": _ranges.INT8MULTIRANGE,
  1360. "nummultirange": _ranges.NUMMULTIRANGE,
  1361. "datemultirange": _ranges.DATEMULTIRANGE,
  1362. "tsmultirange": _ranges.TSMULTIRANGE,
  1363. "tstzmultirange": _ranges.TSTZMULTIRANGE,
  1364. "integer": INTEGER,
  1365. "bigint": BIGINT,
  1366. "smallint": SMALLINT,
  1367. "character varying": VARCHAR,
  1368. "character": CHAR,
  1369. '"char"': sqltypes.String,
  1370. "name": sqltypes.String,
  1371. "text": TEXT,
  1372. "numeric": NUMERIC,
  1373. "float": FLOAT,
  1374. "real": REAL,
  1375. "inet": INET,
  1376. "cidr": CIDR,
  1377. "citext": CITEXT,
  1378. "uuid": UUID,
  1379. "bit": BIT,
  1380. "bit varying": BIT,
  1381. "macaddr": MACADDR,
  1382. "macaddr8": MACADDR8,
  1383. "money": MONEY,
  1384. "oid": OID,
  1385. "regclass": REGCLASS,
  1386. "double precision": DOUBLE_PRECISION,
  1387. "timestamp": TIMESTAMP,
  1388. "timestamp with time zone": TIMESTAMP,
  1389. "timestamp without time zone": TIMESTAMP,
  1390. "time with time zone": TIME,
  1391. "time without time zone": TIME,
  1392. "date": DATE,
  1393. "time": TIME,
  1394. "bytea": BYTEA,
  1395. "boolean": BOOLEAN,
  1396. "interval": INTERVAL,
  1397. "tsvector": TSVECTOR,
  1398. }
  1399. class PGCompiler(compiler.SQLCompiler):
  1400. def visit_to_tsvector_func(self, element, **kw):
  1401. return self._assert_pg_ts_ext(element, **kw)
  1402. def visit_to_tsquery_func(self, element, **kw):
  1403. return self._assert_pg_ts_ext(element, **kw)
  1404. def visit_plainto_tsquery_func(self, element, **kw):
  1405. return self._assert_pg_ts_ext(element, **kw)
  1406. def visit_phraseto_tsquery_func(self, element, **kw):
  1407. return self._assert_pg_ts_ext(element, **kw)
  1408. def visit_websearch_to_tsquery_func(self, element, **kw):
  1409. return self._assert_pg_ts_ext(element, **kw)
  1410. def visit_ts_headline_func(self, element, **kw):
  1411. return self._assert_pg_ts_ext(element, **kw)
  1412. def _assert_pg_ts_ext(self, element, **kw):
  1413. if not isinstance(element, _regconfig_fn):
  1414. # other options here include trying to rewrite the function
  1415. # with the correct types. however, that means we have to
  1416. # "un-SQL-ize" the first argument, which can't work in a
  1417. # generalized way. Also, parent compiler class has already added
  1418. # the incorrect return type to the result map. So let's just
  1419. # make sure the function we want is used up front.
  1420. raise exc.CompileError(
  1421. f'Can\'t compile "{element.name}()" full text search '
  1422. f"function construct that does not originate from the "
  1423. f'"sqlalchemy.dialects.postgresql" package. '
  1424. f'Please ensure "import sqlalchemy.dialects.postgresql" is '
  1425. f"called before constructing "
  1426. f'"sqlalchemy.func.{element.name}()" to ensure registration '
  1427. f"of the correct argument and return types."
  1428. )
  1429. return f"{element.name}{self.function_argspec(element, **kw)}"
  1430. def render_bind_cast(self, type_, dbapi_type, sqltext):
  1431. if dbapi_type._type_affinity is sqltypes.String and dbapi_type.length:
  1432. # use VARCHAR with no length for VARCHAR cast.
  1433. # see #9511
  1434. dbapi_type = sqltypes.STRINGTYPE
  1435. return f"""{sqltext}::{
  1436. self.dialect.type_compiler_instance.process(
  1437. dbapi_type, identifier_preparer=self.preparer
  1438. )
  1439. }"""
  1440. def visit_array(self, element, **kw):
  1441. if not element.clauses and not element.type.item_type._isnull:
  1442. return "ARRAY[]::%s" % element.type.compile(self.dialect)
  1443. return "ARRAY[%s]" % self.visit_clauselist(element, **kw)
  1444. def visit_slice(self, element, **kw):
  1445. return "%s:%s" % (
  1446. self.process(element.start, **kw),
  1447. self.process(element.stop, **kw),
  1448. )
  1449. def visit_bitwise_xor_op_binary(self, binary, operator, **kw):
  1450. return self._generate_generic_binary(binary, " # ", **kw)
  1451. def visit_json_getitem_op_binary(
  1452. self, binary, operator, _cast_applied=False, **kw
  1453. ):
  1454. if (
  1455. not _cast_applied
  1456. and binary.type._type_affinity is not sqltypes.JSON
  1457. ):
  1458. kw["_cast_applied"] = True
  1459. return self.process(sql.cast(binary, binary.type), **kw)
  1460. kw["eager_grouping"] = True
  1461. return self._generate_generic_binary(
  1462. binary, " -> " if not _cast_applied else " ->> ", **kw
  1463. )
  1464. def visit_json_path_getitem_op_binary(
  1465. self, binary, operator, _cast_applied=False, **kw
  1466. ):
  1467. if (
  1468. not _cast_applied
  1469. and binary.type._type_affinity is not sqltypes.JSON
  1470. ):
  1471. kw["_cast_applied"] = True
  1472. return self.process(sql.cast(binary, binary.type), **kw)
  1473. kw["eager_grouping"] = True
  1474. return self._generate_generic_binary(
  1475. binary, " #> " if not _cast_applied else " #>> ", **kw
  1476. )
  1477. def visit_getitem_binary(self, binary, operator, **kw):
  1478. return "%s[%s]" % (
  1479. self.process(binary.left, **kw),
  1480. self.process(binary.right, **kw),
  1481. )
  1482. def visit_aggregate_order_by(self, element, **kw):
  1483. return "%s ORDER BY %s" % (
  1484. self.process(element.target, **kw),
  1485. self.process(element.order_by, **kw),
  1486. )
  1487. def visit_match_op_binary(self, binary, operator, **kw):
  1488. if "postgresql_regconfig" in binary.modifiers:
  1489. regconfig = self.render_literal_value(
  1490. binary.modifiers["postgresql_regconfig"], sqltypes.STRINGTYPE
  1491. )
  1492. if regconfig:
  1493. return "%s @@ plainto_tsquery(%s, %s)" % (
  1494. self.process(binary.left, **kw),
  1495. regconfig,
  1496. self.process(binary.right, **kw),
  1497. )
  1498. return "%s @@ plainto_tsquery(%s)" % (
  1499. self.process(binary.left, **kw),
  1500. self.process(binary.right, **kw),
  1501. )
  1502. def visit_ilike_case_insensitive_operand(self, element, **kw):
  1503. return element.element._compiler_dispatch(self, **kw)
  1504. def visit_ilike_op_binary(self, binary, operator, **kw):
  1505. escape = binary.modifiers.get("escape", None)
  1506. return "%s ILIKE %s" % (
  1507. self.process(binary.left, **kw),
  1508. self.process(binary.right, **kw),
  1509. ) + (
  1510. " ESCAPE " + self.render_literal_value(escape, sqltypes.STRINGTYPE)
  1511. if escape is not None
  1512. else ""
  1513. )
  1514. def visit_not_ilike_op_binary(self, binary, operator, **kw):
  1515. escape = binary.modifiers.get("escape", None)
  1516. return "%s NOT ILIKE %s" % (
  1517. self.process(binary.left, **kw),
  1518. self.process(binary.right, **kw),
  1519. ) + (
  1520. " ESCAPE " + self.render_literal_value(escape, sqltypes.STRINGTYPE)
  1521. if escape is not None
  1522. else ""
  1523. )
  1524. def _regexp_match(self, base_op, binary, operator, kw):
  1525. flags = binary.modifiers["flags"]
  1526. if flags is None:
  1527. return self._generate_generic_binary(
  1528. binary, " %s " % base_op, **kw
  1529. )
  1530. if flags == "i":
  1531. return self._generate_generic_binary(
  1532. binary, " %s* " % base_op, **kw
  1533. )
  1534. return "%s %s CONCAT('(?', %s, ')', %s)" % (
  1535. self.process(binary.left, **kw),
  1536. base_op,
  1537. self.render_literal_value(flags, sqltypes.STRINGTYPE),
  1538. self.process(binary.right, **kw),
  1539. )
  1540. def visit_regexp_match_op_binary(self, binary, operator, **kw):
  1541. return self._regexp_match("~", binary, operator, kw)
  1542. def visit_not_regexp_match_op_binary(self, binary, operator, **kw):
  1543. return self._regexp_match("!~", binary, operator, kw)
  1544. def visit_regexp_replace_op_binary(self, binary, operator, **kw):
  1545. string = self.process(binary.left, **kw)
  1546. pattern_replace = self.process(binary.right, **kw)
  1547. flags = binary.modifiers["flags"]
  1548. if flags is None:
  1549. return "REGEXP_REPLACE(%s, %s)" % (
  1550. string,
  1551. pattern_replace,
  1552. )
  1553. else:
  1554. return "REGEXP_REPLACE(%s, %s, %s)" % (
  1555. string,
  1556. pattern_replace,
  1557. self.render_literal_value(flags, sqltypes.STRINGTYPE),
  1558. )
  1559. def visit_empty_set_expr(self, element_types, **kw):
  1560. # cast the empty set to the type we are comparing against. if
  1561. # we are comparing against the null type, pick an arbitrary
  1562. # datatype for the empty set
  1563. return "SELECT %s WHERE 1!=1" % (
  1564. ", ".join(
  1565. "CAST(NULL AS %s)"
  1566. % self.dialect.type_compiler_instance.process(
  1567. INTEGER() if type_._isnull else type_
  1568. )
  1569. for type_ in element_types or [INTEGER()]
  1570. ),
  1571. )
  1572. def render_literal_value(self, value, type_):
  1573. value = super().render_literal_value(value, type_)
  1574. if self.dialect._backslash_escapes:
  1575. value = value.replace("\\", "\\\\")
  1576. return value
  1577. def visit_aggregate_strings_func(self, fn, **kw):
  1578. return "string_agg%s" % self.function_argspec(fn)
  1579. def visit_sequence(self, seq, **kw):
  1580. return "nextval('%s')" % self.preparer.format_sequence(seq)
  1581. def limit_clause(self, select, **kw):
  1582. text = ""
  1583. if select._limit_clause is not None:
  1584. text += " \n LIMIT " + self.process(select._limit_clause, **kw)
  1585. if select._offset_clause is not None:
  1586. if select._limit_clause is None:
  1587. text += "\n LIMIT ALL"
  1588. text += " OFFSET " + self.process(select._offset_clause, **kw)
  1589. return text
  1590. def format_from_hint_text(self, sqltext, table, hint, iscrud):
  1591. if hint.upper() != "ONLY":
  1592. raise exc.CompileError("Unrecognized hint: %r" % hint)
  1593. return "ONLY " + sqltext
  1594. def get_select_precolumns(self, select, **kw):
  1595. # Do not call super().get_select_precolumns because
  1596. # it will warn/raise when distinct on is present
  1597. if select._distinct or select._distinct_on:
  1598. if select._distinct_on:
  1599. return (
  1600. "DISTINCT ON ("
  1601. + ", ".join(
  1602. [
  1603. self.process(col, **kw)
  1604. for col in select._distinct_on
  1605. ]
  1606. )
  1607. + ") "
  1608. )
  1609. else:
  1610. return "DISTINCT "
  1611. else:
  1612. return ""
  1613. def for_update_clause(self, select, **kw):
  1614. if select._for_update_arg.read:
  1615. if select._for_update_arg.key_share:
  1616. tmp = " FOR KEY SHARE"
  1617. else:
  1618. tmp = " FOR SHARE"
  1619. elif select._for_update_arg.key_share:
  1620. tmp = " FOR NO KEY UPDATE"
  1621. else:
  1622. tmp = " FOR UPDATE"
  1623. if select._for_update_arg.of:
  1624. tables = util.OrderedSet()
  1625. for c in select._for_update_arg.of:
  1626. tables.update(sql_util.surface_selectables_only(c))
  1627. of_kw = dict(kw)
  1628. of_kw.update(ashint=True, use_schema=False)
  1629. tmp += " OF " + ", ".join(
  1630. self.process(table, **of_kw) for table in tables
  1631. )
  1632. if select._for_update_arg.nowait:
  1633. tmp += " NOWAIT"
  1634. if select._for_update_arg.skip_locked:
  1635. tmp += " SKIP LOCKED"
  1636. return tmp
  1637. def visit_substring_func(self, func, **kw):
  1638. s = self.process(func.clauses.clauses[0], **kw)
  1639. start = self.process(func.clauses.clauses[1], **kw)
  1640. if len(func.clauses.clauses) > 2:
  1641. length = self.process(func.clauses.clauses[2], **kw)
  1642. return "SUBSTRING(%s FROM %s FOR %s)" % (s, start, length)
  1643. else:
  1644. return "SUBSTRING(%s FROM %s)" % (s, start)
  1645. def _on_conflict_target(self, clause, **kw):
  1646. if clause.constraint_target is not None:
  1647. # target may be a name of an Index, UniqueConstraint or
  1648. # ExcludeConstraint. While there is a separate
  1649. # "max_identifier_length" for indexes, PostgreSQL uses the same
  1650. # length for all objects so we can use
  1651. # truncate_and_render_constraint_name
  1652. target_text = (
  1653. "ON CONSTRAINT %s"
  1654. % self.preparer.truncate_and_render_constraint_name(
  1655. clause.constraint_target
  1656. )
  1657. )
  1658. elif clause.inferred_target_elements is not None:
  1659. target_text = "(%s)" % ", ".join(
  1660. (
  1661. self.preparer.quote(c)
  1662. if isinstance(c, str)
  1663. else self.process(c, include_table=False, use_schema=False)
  1664. )
  1665. for c in clause.inferred_target_elements
  1666. )
  1667. if clause.inferred_target_whereclause is not None:
  1668. target_text += " WHERE %s" % self.process(
  1669. clause.inferred_target_whereclause,
  1670. include_table=False,
  1671. use_schema=False,
  1672. )
  1673. else:
  1674. target_text = ""
  1675. return target_text
  1676. def visit_on_conflict_do_nothing(self, on_conflict, **kw):
  1677. target_text = self._on_conflict_target(on_conflict, **kw)
  1678. if target_text:
  1679. return "ON CONFLICT %s DO NOTHING" % target_text
  1680. else:
  1681. return "ON CONFLICT DO NOTHING"
  1682. def visit_on_conflict_do_update(self, on_conflict, **kw):
  1683. clause = on_conflict
  1684. target_text = self._on_conflict_target(on_conflict, **kw)
  1685. action_set_ops = []
  1686. set_parameters = dict(clause.update_values_to_set)
  1687. # create a list of column assignment clauses as tuples
  1688. insert_statement = self.stack[-1]["selectable"]
  1689. cols = insert_statement.table.c
  1690. for c in cols:
  1691. col_key = c.key
  1692. if col_key in set_parameters:
  1693. value = set_parameters.pop(col_key)
  1694. elif c in set_parameters:
  1695. value = set_parameters.pop(c)
  1696. else:
  1697. continue
  1698. # TODO: this coercion should be up front. we can't cache
  1699. # SQL constructs with non-bound literals buried in them
  1700. if coercions._is_literal(value):
  1701. value = elements.BindParameter(None, value, type_=c.type)
  1702. else:
  1703. if (
  1704. isinstance(value, elements.BindParameter)
  1705. and value.type._isnull
  1706. ):
  1707. value = value._clone()
  1708. value.type = c.type
  1709. value_text = self.process(value.self_group(), use_schema=False)
  1710. key_text = self.preparer.quote(c.name)
  1711. action_set_ops.append("%s = %s" % (key_text, value_text))
  1712. # check for names that don't match columns
  1713. if set_parameters:
  1714. util.warn(
  1715. "Additional column names not matching "
  1716. "any column keys in table '%s': %s"
  1717. % (
  1718. self.current_executable.table.name,
  1719. (", ".join("'%s'" % c for c in set_parameters)),
  1720. )
  1721. )
  1722. for k, v in set_parameters.items():
  1723. key_text = (
  1724. self.preparer.quote(k)
  1725. if isinstance(k, str)
  1726. else self.process(k, use_schema=False)
  1727. )
  1728. value_text = self.process(
  1729. coercions.expect(roles.ExpressionElementRole, v),
  1730. use_schema=False,
  1731. )
  1732. action_set_ops.append("%s = %s" % (key_text, value_text))
  1733. action_text = ", ".join(action_set_ops)
  1734. if clause.update_whereclause is not None:
  1735. action_text += " WHERE %s" % self.process(
  1736. clause.update_whereclause, include_table=True, use_schema=False
  1737. )
  1738. return "ON CONFLICT %s DO UPDATE SET %s" % (target_text, action_text)
  1739. def update_from_clause(
  1740. self, update_stmt, from_table, extra_froms, from_hints, **kw
  1741. ):
  1742. kw["asfrom"] = True
  1743. return "FROM " + ", ".join(
  1744. t._compiler_dispatch(self, fromhints=from_hints, **kw)
  1745. for t in extra_froms
  1746. )
  1747. def delete_extra_from_clause(
  1748. self, delete_stmt, from_table, extra_froms, from_hints, **kw
  1749. ):
  1750. """Render the DELETE .. USING clause specific to PostgreSQL."""
  1751. kw["asfrom"] = True
  1752. return "USING " + ", ".join(
  1753. t._compiler_dispatch(self, fromhints=from_hints, **kw)
  1754. for t in extra_froms
  1755. )
  1756. def fetch_clause(self, select, **kw):
  1757. # pg requires parens for non literal clauses. It's also required for
  1758. # bind parameters if a ::type casts is used by the driver (asyncpg),
  1759. # so it's easiest to just always add it
  1760. text = ""
  1761. if select._offset_clause is not None:
  1762. text += "\n OFFSET (%s) ROWS" % self.process(
  1763. select._offset_clause, **kw
  1764. )
  1765. if select._fetch_clause is not None:
  1766. text += "\n FETCH FIRST (%s)%s ROWS %s" % (
  1767. self.process(select._fetch_clause, **kw),
  1768. " PERCENT" if select._fetch_clause_options["percent"] else "",
  1769. (
  1770. "WITH TIES"
  1771. if select._fetch_clause_options["with_ties"]
  1772. else "ONLY"
  1773. ),
  1774. )
  1775. return text
  1776. class PGDDLCompiler(compiler.DDLCompiler):
  1777. def get_column_specification(self, column, **kwargs):
  1778. colspec = self.preparer.format_column(column)
  1779. impl_type = column.type.dialect_impl(self.dialect)
  1780. if isinstance(impl_type, sqltypes.TypeDecorator):
  1781. impl_type = impl_type.impl
  1782. has_identity = (
  1783. column.identity is not None
  1784. and self.dialect.supports_identity_columns
  1785. )
  1786. if (
  1787. column.primary_key
  1788. and column is column.table._autoincrement_column
  1789. and (
  1790. self.dialect.supports_smallserial
  1791. or not isinstance(impl_type, sqltypes.SmallInteger)
  1792. )
  1793. and not has_identity
  1794. and (
  1795. column.default is None
  1796. or (
  1797. isinstance(column.default, schema.Sequence)
  1798. and column.default.optional
  1799. )
  1800. )
  1801. ):
  1802. if isinstance(impl_type, sqltypes.BigInteger):
  1803. colspec += " BIGSERIAL"
  1804. elif isinstance(impl_type, sqltypes.SmallInteger):
  1805. colspec += " SMALLSERIAL"
  1806. else:
  1807. colspec += " SERIAL"
  1808. else:
  1809. colspec += " " + self.dialect.type_compiler_instance.process(
  1810. column.type,
  1811. type_expression=column,
  1812. identifier_preparer=self.preparer,
  1813. )
  1814. default = self.get_column_default_string(column)
  1815. if default is not None:
  1816. colspec += " DEFAULT " + default
  1817. if column.computed is not None:
  1818. colspec += " " + self.process(column.computed)
  1819. if has_identity:
  1820. colspec += " " + self.process(column.identity)
  1821. if not column.nullable and not has_identity:
  1822. colspec += " NOT NULL"
  1823. elif column.nullable and has_identity:
  1824. colspec += " NULL"
  1825. return colspec
  1826. def _define_constraint_validity(self, constraint):
  1827. not_valid = constraint.dialect_options["postgresql"]["not_valid"]
  1828. return " NOT VALID" if not_valid else ""
  1829. def _define_include(self, obj):
  1830. includeclause = obj.dialect_options["postgresql"]["include"]
  1831. if not includeclause:
  1832. return ""
  1833. inclusions = [
  1834. obj.table.c[col] if isinstance(col, str) else col
  1835. for col in includeclause
  1836. ]
  1837. return " INCLUDE (%s)" % ", ".join(
  1838. [self.preparer.quote(c.name) for c in inclusions]
  1839. )
  1840. def visit_check_constraint(self, constraint, **kw):
  1841. if constraint._type_bound:
  1842. typ = list(constraint.columns)[0].type
  1843. if (
  1844. isinstance(typ, sqltypes.ARRAY)
  1845. and isinstance(typ.item_type, sqltypes.Enum)
  1846. and not typ.item_type.native_enum
  1847. ):
  1848. raise exc.CompileError(
  1849. "PostgreSQL dialect cannot produce the CHECK constraint "
  1850. "for ARRAY of non-native ENUM; please specify "
  1851. "create_constraint=False on this Enum datatype."
  1852. )
  1853. text = super().visit_check_constraint(constraint)
  1854. text += self._define_constraint_validity(constraint)
  1855. return text
  1856. def visit_foreign_key_constraint(self, constraint, **kw):
  1857. text = super().visit_foreign_key_constraint(constraint)
  1858. text += self._define_constraint_validity(constraint)
  1859. return text
  1860. def visit_primary_key_constraint(self, constraint, **kw):
  1861. text = super().visit_primary_key_constraint(constraint)
  1862. text += self._define_include(constraint)
  1863. return text
  1864. def visit_unique_constraint(self, constraint, **kw):
  1865. text = super().visit_unique_constraint(constraint)
  1866. text += self._define_include(constraint)
  1867. return text
  1868. @util.memoized_property
  1869. def _fk_ondelete_pattern(self):
  1870. return re.compile(
  1871. r"^(?:RESTRICT|CASCADE|SET (?:NULL|DEFAULT)(?:\s*\(.+\))?"
  1872. r"|NO ACTION)$",
  1873. re.I,
  1874. )
  1875. def define_constraint_ondelete_cascade(self, constraint):
  1876. return " ON DELETE %s" % self.preparer.validate_sql_phrase(
  1877. constraint.ondelete, self._fk_ondelete_pattern
  1878. )
  1879. def visit_create_enum_type(self, create, **kw):
  1880. type_ = create.element
  1881. return "CREATE TYPE %s AS ENUM (%s)" % (
  1882. self.preparer.format_type(type_),
  1883. ", ".join(
  1884. self.sql_compiler.process(sql.literal(e), literal_binds=True)
  1885. for e in type_.enums
  1886. ),
  1887. )
  1888. def visit_drop_enum_type(self, drop, **kw):
  1889. type_ = drop.element
  1890. return "DROP TYPE %s" % (self.preparer.format_type(type_))
  1891. def visit_create_domain_type(self, create, **kw):
  1892. domain: DOMAIN = create.element
  1893. options = []
  1894. if domain.collation is not None:
  1895. options.append(f"COLLATE {self.preparer.quote(domain.collation)}")
  1896. if domain.default is not None:
  1897. default = self.render_default_string(domain.default)
  1898. options.append(f"DEFAULT {default}")
  1899. if domain.constraint_name is not None:
  1900. name = self.preparer.truncate_and_render_constraint_name(
  1901. domain.constraint_name
  1902. )
  1903. options.append(f"CONSTRAINT {name}")
  1904. if domain.not_null:
  1905. options.append("NOT NULL")
  1906. if domain.check is not None:
  1907. check = self.sql_compiler.process(
  1908. domain.check, include_table=False, literal_binds=True
  1909. )
  1910. options.append(f"CHECK ({check})")
  1911. return (
  1912. f"CREATE DOMAIN {self.preparer.format_type(domain)} AS "
  1913. f"{self.type_compiler.process(domain.data_type)} "
  1914. f"{' '.join(options)}"
  1915. )
  1916. def visit_drop_domain_type(self, drop, **kw):
  1917. domain = drop.element
  1918. return f"DROP DOMAIN {self.preparer.format_type(domain)}"
  1919. def visit_create_index(self, create, **kw):
  1920. preparer = self.preparer
  1921. index = create.element
  1922. self._verify_index_table(index)
  1923. text = "CREATE "
  1924. if index.unique:
  1925. text += "UNIQUE "
  1926. text += "INDEX "
  1927. if self.dialect._supports_create_index_concurrently:
  1928. concurrently = index.dialect_options["postgresql"]["concurrently"]
  1929. if concurrently:
  1930. text += "CONCURRENTLY "
  1931. if create.if_not_exists:
  1932. text += "IF NOT EXISTS "
  1933. text += "%s ON %s " % (
  1934. self._prepared_index_name(index, include_schema=False),
  1935. preparer.format_table(index.table),
  1936. )
  1937. using = index.dialect_options["postgresql"]["using"]
  1938. if using:
  1939. text += (
  1940. "USING %s "
  1941. % self.preparer.validate_sql_phrase(using, IDX_USING).lower()
  1942. )
  1943. ops = index.dialect_options["postgresql"]["ops"]
  1944. text += "(%s)" % (
  1945. ", ".join(
  1946. [
  1947. self.sql_compiler.process(
  1948. (
  1949. expr.self_group()
  1950. if not isinstance(expr, expression.ColumnClause)
  1951. else expr
  1952. ),
  1953. include_table=False,
  1954. literal_binds=True,
  1955. )
  1956. + (
  1957. (" " + ops[expr.key])
  1958. if hasattr(expr, "key") and expr.key in ops
  1959. else ""
  1960. )
  1961. for expr in index.expressions
  1962. ]
  1963. )
  1964. )
  1965. text += self._define_include(index)
  1966. nulls_not_distinct = index.dialect_options["postgresql"][
  1967. "nulls_not_distinct"
  1968. ]
  1969. if nulls_not_distinct is True:
  1970. text += " NULLS NOT DISTINCT"
  1971. elif nulls_not_distinct is False:
  1972. text += " NULLS DISTINCT"
  1973. withclause = index.dialect_options["postgresql"]["with"]
  1974. if withclause:
  1975. text += " WITH (%s)" % (
  1976. ", ".join(
  1977. [
  1978. "%s = %s" % storage_parameter
  1979. for storage_parameter in withclause.items()
  1980. ]
  1981. )
  1982. )
  1983. tablespace_name = index.dialect_options["postgresql"]["tablespace"]
  1984. if tablespace_name:
  1985. text += " TABLESPACE %s" % preparer.quote(tablespace_name)
  1986. whereclause = index.dialect_options["postgresql"]["where"]
  1987. if whereclause is not None:
  1988. whereclause = coercions.expect(
  1989. roles.DDLExpressionRole, whereclause
  1990. )
  1991. where_compiled = self.sql_compiler.process(
  1992. whereclause, include_table=False, literal_binds=True
  1993. )
  1994. text += " WHERE " + where_compiled
  1995. return text
  1996. def define_unique_constraint_distinct(self, constraint, **kw):
  1997. nulls_not_distinct = constraint.dialect_options["postgresql"][
  1998. "nulls_not_distinct"
  1999. ]
  2000. if nulls_not_distinct is True:
  2001. nulls_not_distinct_param = "NULLS NOT DISTINCT "
  2002. elif nulls_not_distinct is False:
  2003. nulls_not_distinct_param = "NULLS DISTINCT "
  2004. else:
  2005. nulls_not_distinct_param = ""
  2006. return nulls_not_distinct_param
  2007. def visit_drop_index(self, drop, **kw):
  2008. index = drop.element
  2009. text = "\nDROP INDEX "
  2010. if self.dialect._supports_drop_index_concurrently:
  2011. concurrently = index.dialect_options["postgresql"]["concurrently"]
  2012. if concurrently:
  2013. text += "CONCURRENTLY "
  2014. if drop.if_exists:
  2015. text += "IF EXISTS "
  2016. text += self._prepared_index_name(index, include_schema=True)
  2017. return text
  2018. def visit_exclude_constraint(self, constraint, **kw):
  2019. text = ""
  2020. if constraint.name is not None:
  2021. text += "CONSTRAINT %s " % self.preparer.format_constraint(
  2022. constraint
  2023. )
  2024. elements = []
  2025. kw["include_table"] = False
  2026. kw["literal_binds"] = True
  2027. for expr, name, op in constraint._render_exprs:
  2028. exclude_element = self.sql_compiler.process(expr, **kw) + (
  2029. (" " + constraint.ops[expr.key])
  2030. if hasattr(expr, "key") and expr.key in constraint.ops
  2031. else ""
  2032. )
  2033. elements.append("%s WITH %s" % (exclude_element, op))
  2034. text += "EXCLUDE USING %s (%s)" % (
  2035. self.preparer.validate_sql_phrase(
  2036. constraint.using, IDX_USING
  2037. ).lower(),
  2038. ", ".join(elements),
  2039. )
  2040. if constraint.where is not None:
  2041. text += " WHERE (%s)" % self.sql_compiler.process(
  2042. constraint.where, literal_binds=True
  2043. )
  2044. text += self.define_constraint_deferrability(constraint)
  2045. return text
  2046. def post_create_table(self, table):
  2047. table_opts = []
  2048. pg_opts = table.dialect_options["postgresql"]
  2049. inherits = pg_opts.get("inherits")
  2050. if inherits is not None:
  2051. if not isinstance(inherits, (list, tuple)):
  2052. inherits = (inherits,)
  2053. table_opts.append(
  2054. "\n INHERITS ( "
  2055. + ", ".join(self.preparer.quote(name) for name in inherits)
  2056. + " )"
  2057. )
  2058. if pg_opts["partition_by"]:
  2059. table_opts.append("\n PARTITION BY %s" % pg_opts["partition_by"])
  2060. if pg_opts["using"]:
  2061. table_opts.append("\n USING %s" % pg_opts["using"])
  2062. if pg_opts["with_oids"] is True:
  2063. table_opts.append("\n WITH OIDS")
  2064. elif pg_opts["with_oids"] is False:
  2065. table_opts.append("\n WITHOUT OIDS")
  2066. if pg_opts["on_commit"]:
  2067. on_commit_options = pg_opts["on_commit"].replace("_", " ").upper()
  2068. table_opts.append("\n ON COMMIT %s" % on_commit_options)
  2069. if pg_opts["tablespace"]:
  2070. tablespace_name = pg_opts["tablespace"]
  2071. table_opts.append(
  2072. "\n TABLESPACE %s" % self.preparer.quote(tablespace_name)
  2073. )
  2074. return "".join(table_opts)
  2075. def visit_computed_column(self, generated, **kw):
  2076. if generated.persisted is False:
  2077. raise exc.CompileError(
  2078. "PostrgreSQL computed columns do not support 'virtual' "
  2079. "persistence; set the 'persisted' flag to None or True for "
  2080. "PostgreSQL support."
  2081. )
  2082. return "GENERATED ALWAYS AS (%s) STORED" % self.sql_compiler.process(
  2083. generated.sqltext, include_table=False, literal_binds=True
  2084. )
  2085. def visit_create_sequence(self, create, **kw):
  2086. prefix = None
  2087. if create.element.data_type is not None:
  2088. prefix = " AS %s" % self.type_compiler.process(
  2089. create.element.data_type
  2090. )
  2091. return super().visit_create_sequence(create, prefix=prefix, **kw)
  2092. def _can_comment_on_constraint(self, ddl_instance):
  2093. constraint = ddl_instance.element
  2094. if constraint.name is None:
  2095. raise exc.CompileError(
  2096. f"Can't emit COMMENT ON for constraint {constraint!r}: "
  2097. "it has no name"
  2098. )
  2099. if constraint.table is None:
  2100. raise exc.CompileError(
  2101. f"Can't emit COMMENT ON for constraint {constraint!r}: "
  2102. "it has no associated table"
  2103. )
  2104. def visit_set_constraint_comment(self, create, **kw):
  2105. self._can_comment_on_constraint(create)
  2106. return "COMMENT ON CONSTRAINT %s ON %s IS %s" % (
  2107. self.preparer.format_constraint(create.element),
  2108. self.preparer.format_table(create.element.table),
  2109. self.sql_compiler.render_literal_value(
  2110. create.element.comment, sqltypes.String()
  2111. ),
  2112. )
  2113. def visit_drop_constraint_comment(self, drop, **kw):
  2114. self._can_comment_on_constraint(drop)
  2115. return "COMMENT ON CONSTRAINT %s ON %s IS NULL" % (
  2116. self.preparer.format_constraint(drop.element),
  2117. self.preparer.format_table(drop.element.table),
  2118. )
  2119. class PGTypeCompiler(compiler.GenericTypeCompiler):
  2120. def visit_TSVECTOR(self, type_, **kw):
  2121. return "TSVECTOR"
  2122. def visit_TSQUERY(self, type_, **kw):
  2123. return "TSQUERY"
  2124. def visit_INET(self, type_, **kw):
  2125. return "INET"
  2126. def visit_CIDR(self, type_, **kw):
  2127. return "CIDR"
  2128. def visit_CITEXT(self, type_, **kw):
  2129. return "CITEXT"
  2130. def visit_MACADDR(self, type_, **kw):
  2131. return "MACADDR"
  2132. def visit_MACADDR8(self, type_, **kw):
  2133. return "MACADDR8"
  2134. def visit_MONEY(self, type_, **kw):
  2135. return "MONEY"
  2136. def visit_OID(self, type_, **kw):
  2137. return "OID"
  2138. def visit_REGCONFIG(self, type_, **kw):
  2139. return "REGCONFIG"
  2140. def visit_REGCLASS(self, type_, **kw):
  2141. return "REGCLASS"
  2142. def visit_FLOAT(self, type_, **kw):
  2143. if not type_.precision:
  2144. return "FLOAT"
  2145. else:
  2146. return "FLOAT(%(precision)s)" % {"precision": type_.precision}
  2147. def visit_double(self, type_, **kw):
  2148. return self.visit_DOUBLE_PRECISION(type, **kw)
  2149. def visit_BIGINT(self, type_, **kw):
  2150. return "BIGINT"
  2151. def visit_HSTORE(self, type_, **kw):
  2152. return "HSTORE"
  2153. def visit_JSON(self, type_, **kw):
  2154. return "JSON"
  2155. def visit_JSONB(self, type_, **kw):
  2156. return "JSONB"
  2157. def visit_INT4MULTIRANGE(self, type_, **kw):
  2158. return "INT4MULTIRANGE"
  2159. def visit_INT8MULTIRANGE(self, type_, **kw):
  2160. return "INT8MULTIRANGE"
  2161. def visit_NUMMULTIRANGE(self, type_, **kw):
  2162. return "NUMMULTIRANGE"
  2163. def visit_DATEMULTIRANGE(self, type_, **kw):
  2164. return "DATEMULTIRANGE"
  2165. def visit_TSMULTIRANGE(self, type_, **kw):
  2166. return "TSMULTIRANGE"
  2167. def visit_TSTZMULTIRANGE(self, type_, **kw):
  2168. return "TSTZMULTIRANGE"
  2169. def visit_INT4RANGE(self, type_, **kw):
  2170. return "INT4RANGE"
  2171. def visit_INT8RANGE(self, type_, **kw):
  2172. return "INT8RANGE"
  2173. def visit_NUMRANGE(self, type_, **kw):
  2174. return "NUMRANGE"
  2175. def visit_DATERANGE(self, type_, **kw):
  2176. return "DATERANGE"
  2177. def visit_TSRANGE(self, type_, **kw):
  2178. return "TSRANGE"
  2179. def visit_TSTZRANGE(self, type_, **kw):
  2180. return "TSTZRANGE"
  2181. def visit_json_int_index(self, type_, **kw):
  2182. return "INT"
  2183. def visit_json_str_index(self, type_, **kw):
  2184. return "TEXT"
  2185. def visit_datetime(self, type_, **kw):
  2186. return self.visit_TIMESTAMP(type_, **kw)
  2187. def visit_enum(self, type_, **kw):
  2188. if not type_.native_enum or not self.dialect.supports_native_enum:
  2189. return super().visit_enum(type_, **kw)
  2190. else:
  2191. return self.visit_ENUM(type_, **kw)
  2192. def visit_ENUM(self, type_, identifier_preparer=None, **kw):
  2193. if identifier_preparer is None:
  2194. identifier_preparer = self.dialect.identifier_preparer
  2195. return identifier_preparer.format_type(type_)
  2196. def visit_DOMAIN(self, type_, identifier_preparer=None, **kw):
  2197. if identifier_preparer is None:
  2198. identifier_preparer = self.dialect.identifier_preparer
  2199. return identifier_preparer.format_type(type_)
  2200. def visit_TIMESTAMP(self, type_, **kw):
  2201. return "TIMESTAMP%s %s" % (
  2202. (
  2203. "(%d)" % type_.precision
  2204. if getattr(type_, "precision", None) is not None
  2205. else ""
  2206. ),
  2207. (type_.timezone and "WITH" or "WITHOUT") + " TIME ZONE",
  2208. )
  2209. def visit_TIME(self, type_, **kw):
  2210. return "TIME%s %s" % (
  2211. (
  2212. "(%d)" % type_.precision
  2213. if getattr(type_, "precision", None) is not None
  2214. else ""
  2215. ),
  2216. (type_.timezone and "WITH" or "WITHOUT") + " TIME ZONE",
  2217. )
  2218. def visit_INTERVAL(self, type_, **kw):
  2219. text = "INTERVAL"
  2220. if type_.fields is not None:
  2221. text += " " + type_.fields
  2222. if type_.precision is not None:
  2223. text += " (%d)" % type_.precision
  2224. return text
  2225. def visit_BIT(self, type_, **kw):
  2226. if type_.varying:
  2227. compiled = "BIT VARYING"
  2228. if type_.length is not None:
  2229. compiled += "(%d)" % type_.length
  2230. else:
  2231. compiled = "BIT(%d)" % type_.length
  2232. return compiled
  2233. def visit_uuid(self, type_, **kw):
  2234. if type_.native_uuid:
  2235. return self.visit_UUID(type_, **kw)
  2236. else:
  2237. return super().visit_uuid(type_, **kw)
  2238. def visit_UUID(self, type_, **kw):
  2239. return "UUID"
  2240. def visit_large_binary(self, type_, **kw):
  2241. return self.visit_BYTEA(type_, **kw)
  2242. def visit_BYTEA(self, type_, **kw):
  2243. return "BYTEA"
  2244. def visit_ARRAY(self, type_, **kw):
  2245. inner = self.process(type_.item_type, **kw)
  2246. return re.sub(
  2247. r"((?: COLLATE.*)?)$",
  2248. (
  2249. r"%s\1"
  2250. % (
  2251. "[]"
  2252. * (type_.dimensions if type_.dimensions is not None else 1)
  2253. )
  2254. ),
  2255. inner,
  2256. count=1,
  2257. )
  2258. def visit_json_path(self, type_, **kw):
  2259. return self.visit_JSONPATH(type_, **kw)
  2260. def visit_JSONPATH(self, type_, **kw):
  2261. return "JSONPATH"
  2262. class PGIdentifierPreparer(compiler.IdentifierPreparer):
  2263. reserved_words = RESERVED_WORDS
  2264. def _unquote_identifier(self, value):
  2265. if value[0] == self.initial_quote:
  2266. value = value[1:-1].replace(
  2267. self.escape_to_quote, self.escape_quote
  2268. )
  2269. return value
  2270. def format_type(self, type_, use_schema=True):
  2271. if not type_.name:
  2272. raise exc.CompileError(
  2273. f"PostgreSQL {type_.__class__.__name__} type requires a name."
  2274. )
  2275. name = self.quote(type_.name)
  2276. effective_schema = self.schema_for_object(type_)
  2277. if (
  2278. not self.omit_schema
  2279. and use_schema
  2280. and effective_schema is not None
  2281. ):
  2282. name = f"{self.quote_schema(effective_schema)}.{name}"
  2283. return name
  2284. class ReflectedNamedType(TypedDict):
  2285. """Represents a reflected named type."""
  2286. name: str
  2287. """Name of the type."""
  2288. schema: str
  2289. """The schema of the type."""
  2290. visible: bool
  2291. """Indicates if this type is in the current search path."""
  2292. class ReflectedDomainConstraint(TypedDict):
  2293. """Represents a reflect check constraint of a domain."""
  2294. name: str
  2295. """Name of the constraint."""
  2296. check: str
  2297. """The check constraint text."""
  2298. class ReflectedDomain(ReflectedNamedType):
  2299. """Represents a reflected enum."""
  2300. type: str
  2301. """The string name of the underlying data type of the domain."""
  2302. nullable: bool
  2303. """Indicates if the domain allows null or not."""
  2304. default: Optional[str]
  2305. """The string representation of the default value of this domain
  2306. or ``None`` if none present.
  2307. """
  2308. constraints: List[ReflectedDomainConstraint]
  2309. """The constraints defined in the domain, if any.
  2310. The constraint are in order of evaluation by postgresql.
  2311. """
  2312. collation: Optional[str]
  2313. """The collation for the domain."""
  2314. class ReflectedEnum(ReflectedNamedType):
  2315. """Represents a reflected enum."""
  2316. labels: List[str]
  2317. """The labels that compose the enum."""
  2318. class PGInspector(reflection.Inspector):
  2319. dialect: PGDialect
  2320. def get_table_oid(
  2321. self, table_name: str, schema: Optional[str] = None
  2322. ) -> int:
  2323. """Return the OID for the given table name.
  2324. :param table_name: string name of the table. For special quoting,
  2325. use :class:`.quoted_name`.
  2326. :param schema: string schema name; if omitted, uses the default schema
  2327. of the database connection. For special quoting,
  2328. use :class:`.quoted_name`.
  2329. """
  2330. with self._operation_context() as conn:
  2331. return self.dialect.get_table_oid(
  2332. conn, table_name, schema, info_cache=self.info_cache
  2333. )
  2334. def get_domains(
  2335. self, schema: Optional[str] = None
  2336. ) -> List[ReflectedDomain]:
  2337. """Return a list of DOMAIN objects.
  2338. Each member is a dictionary containing these fields:
  2339. * name - name of the domain
  2340. * schema - the schema name for the domain.
  2341. * visible - boolean, whether or not this domain is visible
  2342. in the default search path.
  2343. * type - the type defined by this domain.
  2344. * nullable - Indicates if this domain can be ``NULL``.
  2345. * default - The default value of the domain or ``None`` if the
  2346. domain has no default.
  2347. * constraints - A list of dict wit the constraint defined by this
  2348. domain. Each element constaints two keys: ``name`` of the
  2349. constraint and ``check`` with the constraint text.
  2350. :param schema: schema name. If None, the default schema
  2351. (typically 'public') is used. May also be set to ``'*'`` to
  2352. indicate load domains for all schemas.
  2353. .. versionadded:: 2.0
  2354. """
  2355. with self._operation_context() as conn:
  2356. return self.dialect._load_domains(
  2357. conn, schema, info_cache=self.info_cache
  2358. )
  2359. def get_enums(self, schema: Optional[str] = None) -> List[ReflectedEnum]:
  2360. """Return a list of ENUM objects.
  2361. Each member is a dictionary containing these fields:
  2362. * name - name of the enum
  2363. * schema - the schema name for the enum.
  2364. * visible - boolean, whether or not this enum is visible
  2365. in the default search path.
  2366. * labels - a list of string labels that apply to the enum.
  2367. :param schema: schema name. If None, the default schema
  2368. (typically 'public') is used. May also be set to ``'*'`` to
  2369. indicate load enums for all schemas.
  2370. """
  2371. with self._operation_context() as conn:
  2372. return self.dialect._load_enums(
  2373. conn, schema, info_cache=self.info_cache
  2374. )
  2375. def get_foreign_table_names(
  2376. self, schema: Optional[str] = None
  2377. ) -> List[str]:
  2378. """Return a list of FOREIGN TABLE names.
  2379. Behavior is similar to that of
  2380. :meth:`_reflection.Inspector.get_table_names`,
  2381. except that the list is limited to those tables that report a
  2382. ``relkind`` value of ``f``.
  2383. """
  2384. with self._operation_context() as conn:
  2385. return self.dialect._get_foreign_table_names(
  2386. conn, schema, info_cache=self.info_cache
  2387. )
  2388. def has_type(
  2389. self, type_name: str, schema: Optional[str] = None, **kw: Any
  2390. ) -> bool:
  2391. """Return if the database has the specified type in the provided
  2392. schema.
  2393. :param type_name: the type to check.
  2394. :param schema: schema name. If None, the default schema
  2395. (typically 'public') is used. May also be set to ``'*'`` to
  2396. check in all schemas.
  2397. .. versionadded:: 2.0
  2398. """
  2399. with self._operation_context() as conn:
  2400. return self.dialect.has_type(
  2401. conn, type_name, schema, info_cache=self.info_cache
  2402. )
  2403. class PGExecutionContext(default.DefaultExecutionContext):
  2404. def fire_sequence(self, seq, type_):
  2405. return self._execute_scalar(
  2406. (
  2407. "select nextval('%s')"
  2408. % self.identifier_preparer.format_sequence(seq)
  2409. ),
  2410. type_,
  2411. )
  2412. def get_insert_default(self, column):
  2413. if column.primary_key and column is column.table._autoincrement_column:
  2414. if column.server_default and column.server_default.has_argument:
  2415. # pre-execute passive defaults on primary key columns
  2416. return self._execute_scalar(
  2417. "select %s" % column.server_default.arg, column.type
  2418. )
  2419. elif column.default is None or (
  2420. column.default.is_sequence and column.default.optional
  2421. ):
  2422. # execute the sequence associated with a SERIAL primary
  2423. # key column. for non-primary-key SERIAL, the ID just
  2424. # generates server side.
  2425. try:
  2426. seq_name = column._postgresql_seq_name
  2427. except AttributeError:
  2428. tab = column.table.name
  2429. col = column.name
  2430. tab = tab[0 : 29 + max(0, (29 - len(col)))]
  2431. col = col[0 : 29 + max(0, (29 - len(tab)))]
  2432. name = "%s_%s_seq" % (tab, col)
  2433. column._postgresql_seq_name = seq_name = name
  2434. if column.table is not None:
  2435. effective_schema = self.connection.schema_for_object(
  2436. column.table
  2437. )
  2438. else:
  2439. effective_schema = None
  2440. if effective_schema is not None:
  2441. exc = 'select nextval(\'"%s"."%s"\')' % (
  2442. effective_schema,
  2443. seq_name,
  2444. )
  2445. else:
  2446. exc = "select nextval('\"%s\"')" % (seq_name,)
  2447. return self._execute_scalar(exc, column.type)
  2448. return super().get_insert_default(column)
  2449. class PGReadOnlyConnectionCharacteristic(
  2450. characteristics.ConnectionCharacteristic
  2451. ):
  2452. transactional = True
  2453. def reset_characteristic(self, dialect, dbapi_conn):
  2454. dialect.set_readonly(dbapi_conn, False)
  2455. def set_characteristic(self, dialect, dbapi_conn, value):
  2456. dialect.set_readonly(dbapi_conn, value)
  2457. def get_characteristic(self, dialect, dbapi_conn):
  2458. return dialect.get_readonly(dbapi_conn)
  2459. class PGDeferrableConnectionCharacteristic(
  2460. characteristics.ConnectionCharacteristic
  2461. ):
  2462. transactional = True
  2463. def reset_characteristic(self, dialect, dbapi_conn):
  2464. dialect.set_deferrable(dbapi_conn, False)
  2465. def set_characteristic(self, dialect, dbapi_conn, value):
  2466. dialect.set_deferrable(dbapi_conn, value)
  2467. def get_characteristic(self, dialect, dbapi_conn):
  2468. return dialect.get_deferrable(dbapi_conn)
  2469. class PGDialect(default.DefaultDialect):
  2470. name = "postgresql"
  2471. supports_statement_cache = True
  2472. supports_alter = True
  2473. max_identifier_length = 63
  2474. supports_sane_rowcount = True
  2475. bind_typing = interfaces.BindTyping.RENDER_CASTS
  2476. supports_native_enum = True
  2477. supports_native_boolean = True
  2478. supports_native_uuid = True
  2479. supports_smallserial = True
  2480. supports_sequences = True
  2481. sequences_optional = True
  2482. preexecute_autoincrement_sequences = True
  2483. postfetch_lastrowid = False
  2484. use_insertmanyvalues = True
  2485. returns_native_bytes = True
  2486. insertmanyvalues_implicit_sentinel = (
  2487. InsertmanyvaluesSentinelOpts.ANY_AUTOINCREMENT
  2488. | InsertmanyvaluesSentinelOpts.USE_INSERT_FROM_SELECT
  2489. | InsertmanyvaluesSentinelOpts.RENDER_SELECT_COL_CASTS
  2490. )
  2491. supports_comments = True
  2492. supports_constraint_comments = True
  2493. supports_default_values = True
  2494. supports_default_metavalue = True
  2495. supports_empty_insert = False
  2496. supports_multivalues_insert = True
  2497. supports_identity_columns = True
  2498. default_paramstyle = "pyformat"
  2499. ischema_names = ischema_names
  2500. colspecs = colspecs
  2501. statement_compiler = PGCompiler
  2502. ddl_compiler = PGDDLCompiler
  2503. type_compiler_cls = PGTypeCompiler
  2504. preparer = PGIdentifierPreparer
  2505. execution_ctx_cls = PGExecutionContext
  2506. inspector = PGInspector
  2507. update_returning = True
  2508. delete_returning = True
  2509. insert_returning = True
  2510. update_returning_multifrom = True
  2511. delete_returning_multifrom = True
  2512. connection_characteristics = (
  2513. default.DefaultDialect.connection_characteristics
  2514. )
  2515. connection_characteristics = connection_characteristics.union(
  2516. {
  2517. "postgresql_readonly": PGReadOnlyConnectionCharacteristic(),
  2518. "postgresql_deferrable": PGDeferrableConnectionCharacteristic(),
  2519. }
  2520. )
  2521. construct_arguments = [
  2522. (
  2523. schema.Index,
  2524. {
  2525. "using": False,
  2526. "include": None,
  2527. "where": None,
  2528. "ops": {},
  2529. "concurrently": False,
  2530. "with": {},
  2531. "tablespace": None,
  2532. "nulls_not_distinct": None,
  2533. },
  2534. ),
  2535. (
  2536. schema.Table,
  2537. {
  2538. "ignore_search_path": False,
  2539. "tablespace": None,
  2540. "partition_by": None,
  2541. "with_oids": None,
  2542. "on_commit": None,
  2543. "inherits": None,
  2544. "using": None,
  2545. },
  2546. ),
  2547. (
  2548. schema.CheckConstraint,
  2549. {
  2550. "not_valid": False,
  2551. },
  2552. ),
  2553. (
  2554. schema.ForeignKeyConstraint,
  2555. {
  2556. "not_valid": False,
  2557. },
  2558. ),
  2559. (
  2560. schema.PrimaryKeyConstraint,
  2561. {"include": None},
  2562. ),
  2563. (
  2564. schema.UniqueConstraint,
  2565. {
  2566. "include": None,
  2567. "nulls_not_distinct": None,
  2568. },
  2569. ),
  2570. ]
  2571. reflection_options = ("postgresql_ignore_search_path",)
  2572. _backslash_escapes = True
  2573. _supports_create_index_concurrently = True
  2574. _supports_drop_index_concurrently = True
  2575. def __init__(
  2576. self,
  2577. native_inet_types=None,
  2578. json_serializer=None,
  2579. json_deserializer=None,
  2580. **kwargs,
  2581. ):
  2582. default.DefaultDialect.__init__(self, **kwargs)
  2583. self._native_inet_types = native_inet_types
  2584. self._json_deserializer = json_deserializer
  2585. self._json_serializer = json_serializer
  2586. def initialize(self, connection):
  2587. super().initialize(connection)
  2588. # https://www.postgresql.org/docs/9.3/static/release-9-2.html#AEN116689
  2589. self.supports_smallserial = self.server_version_info >= (9, 2)
  2590. self._set_backslash_escapes(connection)
  2591. self._supports_drop_index_concurrently = self.server_version_info >= (
  2592. 9,
  2593. 2,
  2594. )
  2595. self.supports_identity_columns = self.server_version_info >= (10,)
  2596. def get_isolation_level_values(self, dbapi_conn):
  2597. # note the generic dialect doesn't have AUTOCOMMIT, however
  2598. # all postgresql dialects should include AUTOCOMMIT.
  2599. return (
  2600. "SERIALIZABLE",
  2601. "READ UNCOMMITTED",
  2602. "READ COMMITTED",
  2603. "REPEATABLE READ",
  2604. )
  2605. def set_isolation_level(self, dbapi_connection, level):
  2606. cursor = dbapi_connection.cursor()
  2607. cursor.execute(
  2608. "SET SESSION CHARACTERISTICS AS TRANSACTION "
  2609. f"ISOLATION LEVEL {level}"
  2610. )
  2611. cursor.execute("COMMIT")
  2612. cursor.close()
  2613. def get_isolation_level(self, dbapi_connection):
  2614. cursor = dbapi_connection.cursor()
  2615. cursor.execute("show transaction isolation level")
  2616. val = cursor.fetchone()[0]
  2617. cursor.close()
  2618. return val.upper()
  2619. def set_readonly(self, connection, value):
  2620. raise NotImplementedError()
  2621. def get_readonly(self, connection):
  2622. raise NotImplementedError()
  2623. def set_deferrable(self, connection, value):
  2624. raise NotImplementedError()
  2625. def get_deferrable(self, connection):
  2626. raise NotImplementedError()
  2627. def _split_multihost_from_url(self, url: URL) -> Union[
  2628. Tuple[None, None],
  2629. Tuple[Tuple[Optional[str], ...], Tuple[Optional[int], ...]],
  2630. ]:
  2631. hosts: Optional[Tuple[Optional[str], ...]] = None
  2632. ports_str: Union[str, Tuple[Optional[str], ...], None] = None
  2633. integrated_multihost = False
  2634. if "host" in url.query:
  2635. if isinstance(url.query["host"], (list, tuple)):
  2636. integrated_multihost = True
  2637. hosts, ports_str = zip(
  2638. *[
  2639. token.split(":") if ":" in token else (token, None)
  2640. for token in url.query["host"]
  2641. ]
  2642. )
  2643. elif isinstance(url.query["host"], str):
  2644. hosts = tuple(url.query["host"].split(","))
  2645. if (
  2646. "port" not in url.query
  2647. and len(hosts) == 1
  2648. and ":" in hosts[0]
  2649. ):
  2650. # internet host is alphanumeric plus dots or hyphens.
  2651. # this is essentially rfc1123, which refers to rfc952.
  2652. # https://stackoverflow.com/questions/3523028/
  2653. # valid-characters-of-a-hostname
  2654. host_port_match = re.match(
  2655. r"^([a-zA-Z0-9\-\.]*)(?:\:(\d*))?$", hosts[0]
  2656. )
  2657. if host_port_match:
  2658. integrated_multihost = True
  2659. h, p = host_port_match.group(1, 2)
  2660. if TYPE_CHECKING:
  2661. assert isinstance(h, str)
  2662. assert isinstance(p, str)
  2663. hosts = (h,)
  2664. ports_str = cast(
  2665. "Tuple[Optional[str], ...]", (p,) if p else (None,)
  2666. )
  2667. if "port" in url.query:
  2668. if integrated_multihost:
  2669. raise exc.ArgumentError(
  2670. "Can't mix 'multihost' formats together; use "
  2671. '"host=h1,h2,h3&port=p1,p2,p3" or '
  2672. '"host=h1:p1&host=h2:p2&host=h3:p3" separately'
  2673. )
  2674. if isinstance(url.query["port"], (list, tuple)):
  2675. ports_str = url.query["port"]
  2676. elif isinstance(url.query["port"], str):
  2677. ports_str = tuple(url.query["port"].split(","))
  2678. ports: Optional[Tuple[Optional[int], ...]] = None
  2679. if ports_str:
  2680. try:
  2681. ports = tuple(int(x) if x else None for x in ports_str)
  2682. except ValueError:
  2683. raise exc.ArgumentError(
  2684. f"Received non-integer port arguments: {ports_str}"
  2685. ) from None
  2686. if ports and (
  2687. (not hosts and len(ports) > 1)
  2688. or (
  2689. hosts
  2690. and ports
  2691. and len(hosts) != len(ports)
  2692. and (len(hosts) > 1 or len(ports) > 1)
  2693. )
  2694. ):
  2695. raise exc.ArgumentError("number of hosts and ports don't match")
  2696. if hosts is not None:
  2697. if ports is None:
  2698. ports = tuple(None for _ in hosts)
  2699. return hosts, ports # type: ignore
  2700. def do_begin_twophase(self, connection, xid):
  2701. self.do_begin(connection.connection)
  2702. def do_prepare_twophase(self, connection, xid):
  2703. connection.exec_driver_sql("PREPARE TRANSACTION '%s'" % xid)
  2704. def do_rollback_twophase(
  2705. self, connection, xid, is_prepared=True, recover=False
  2706. ):
  2707. if is_prepared:
  2708. if recover:
  2709. # FIXME: ugly hack to get out of transaction
  2710. # context when committing recoverable transactions
  2711. # Must find out a way how to make the dbapi not
  2712. # open a transaction.
  2713. connection.exec_driver_sql("ROLLBACK")
  2714. connection.exec_driver_sql("ROLLBACK PREPARED '%s'" % xid)
  2715. connection.exec_driver_sql("BEGIN")
  2716. self.do_rollback(connection.connection)
  2717. else:
  2718. self.do_rollback(connection.connection)
  2719. def do_commit_twophase(
  2720. self, connection, xid, is_prepared=True, recover=False
  2721. ):
  2722. if is_prepared:
  2723. if recover:
  2724. connection.exec_driver_sql("ROLLBACK")
  2725. connection.exec_driver_sql("COMMIT PREPARED '%s'" % xid)
  2726. connection.exec_driver_sql("BEGIN")
  2727. self.do_rollback(connection.connection)
  2728. else:
  2729. self.do_commit(connection.connection)
  2730. def do_recover_twophase(self, connection):
  2731. return connection.scalars(
  2732. sql.text("SELECT gid FROM pg_prepared_xacts")
  2733. ).all()
  2734. def _get_default_schema_name(self, connection):
  2735. return connection.exec_driver_sql("select current_schema()").scalar()
  2736. @reflection.cache
  2737. def has_schema(self, connection, schema, **kw):
  2738. query = select(pg_catalog.pg_namespace.c.nspname).where(
  2739. pg_catalog.pg_namespace.c.nspname == schema
  2740. )
  2741. return bool(connection.scalar(query))
  2742. def _pg_class_filter_scope_schema(
  2743. self, query, schema, scope, pg_class_table=None
  2744. ):
  2745. if pg_class_table is None:
  2746. pg_class_table = pg_catalog.pg_class
  2747. query = query.join(
  2748. pg_catalog.pg_namespace,
  2749. pg_catalog.pg_namespace.c.oid == pg_class_table.c.relnamespace,
  2750. )
  2751. if scope is ObjectScope.DEFAULT:
  2752. query = query.where(pg_class_table.c.relpersistence != "t")
  2753. elif scope is ObjectScope.TEMPORARY:
  2754. query = query.where(pg_class_table.c.relpersistence == "t")
  2755. if schema is None:
  2756. query = query.where(
  2757. pg_catalog.pg_table_is_visible(pg_class_table.c.oid),
  2758. # ignore pg_catalog schema
  2759. pg_catalog.pg_namespace.c.nspname != "pg_catalog",
  2760. )
  2761. else:
  2762. query = query.where(pg_catalog.pg_namespace.c.nspname == schema)
  2763. return query
  2764. def _pg_class_relkind_condition(self, relkinds, pg_class_table=None):
  2765. if pg_class_table is None:
  2766. pg_class_table = pg_catalog.pg_class
  2767. # uses the any form instead of in otherwise postgresql complaings
  2768. # that 'IN could not convert type character to "char"'
  2769. return pg_class_table.c.relkind == sql.any_(_array.array(relkinds))
  2770. @lru_cache()
  2771. def _has_table_query(self, schema):
  2772. query = select(pg_catalog.pg_class.c.relname).where(
  2773. pg_catalog.pg_class.c.relname == bindparam("table_name"),
  2774. self._pg_class_relkind_condition(
  2775. pg_catalog.RELKINDS_ALL_TABLE_LIKE
  2776. ),
  2777. )
  2778. return self._pg_class_filter_scope_schema(
  2779. query, schema, scope=ObjectScope.ANY
  2780. )
  2781. @reflection.cache
  2782. def has_table(self, connection, table_name, schema=None, **kw):
  2783. self._ensure_has_table_connection(connection)
  2784. query = self._has_table_query(schema)
  2785. return bool(connection.scalar(query, {"table_name": table_name}))
  2786. @reflection.cache
  2787. def has_sequence(self, connection, sequence_name, schema=None, **kw):
  2788. query = select(pg_catalog.pg_class.c.relname).where(
  2789. pg_catalog.pg_class.c.relkind == "S",
  2790. pg_catalog.pg_class.c.relname == sequence_name,
  2791. )
  2792. query = self._pg_class_filter_scope_schema(
  2793. query, schema, scope=ObjectScope.ANY
  2794. )
  2795. return bool(connection.scalar(query))
  2796. @reflection.cache
  2797. def has_type(self, connection, type_name, schema=None, **kw):
  2798. query = (
  2799. select(pg_catalog.pg_type.c.typname)
  2800. .join(
  2801. pg_catalog.pg_namespace,
  2802. pg_catalog.pg_namespace.c.oid
  2803. == pg_catalog.pg_type.c.typnamespace,
  2804. )
  2805. .where(pg_catalog.pg_type.c.typname == type_name)
  2806. )
  2807. if schema is None:
  2808. query = query.where(
  2809. pg_catalog.pg_type_is_visible(pg_catalog.pg_type.c.oid),
  2810. # ignore pg_catalog schema
  2811. pg_catalog.pg_namespace.c.nspname != "pg_catalog",
  2812. )
  2813. elif schema != "*":
  2814. query = query.where(pg_catalog.pg_namespace.c.nspname == schema)
  2815. return bool(connection.scalar(query))
  2816. def _get_server_version_info(self, connection):
  2817. v = connection.exec_driver_sql("select pg_catalog.version()").scalar()
  2818. m = re.match(
  2819. r".*(?:PostgreSQL|EnterpriseDB) "
  2820. r"(\d+)\.?(\d+)?(?:\.(\d+))?(?:\.\d+)?(?:devel|beta)?",
  2821. v,
  2822. )
  2823. if not m:
  2824. raise AssertionError(
  2825. "Could not determine version from string '%s'" % v
  2826. )
  2827. return tuple([int(x) for x in m.group(1, 2, 3) if x is not None])
  2828. @reflection.cache
  2829. def get_table_oid(self, connection, table_name, schema=None, **kw):
  2830. """Fetch the oid for schema.table_name."""
  2831. query = select(pg_catalog.pg_class.c.oid).where(
  2832. pg_catalog.pg_class.c.relname == table_name,
  2833. self._pg_class_relkind_condition(
  2834. pg_catalog.RELKINDS_ALL_TABLE_LIKE
  2835. ),
  2836. )
  2837. query = self._pg_class_filter_scope_schema(
  2838. query, schema, scope=ObjectScope.ANY
  2839. )
  2840. table_oid = connection.scalar(query)
  2841. if table_oid is None:
  2842. raise exc.NoSuchTableError(
  2843. f"{schema}.{table_name}" if schema else table_name
  2844. )
  2845. return table_oid
  2846. @reflection.cache
  2847. def get_schema_names(self, connection, **kw):
  2848. query = (
  2849. select(pg_catalog.pg_namespace.c.nspname)
  2850. .where(pg_catalog.pg_namespace.c.nspname.not_like("pg_%"))
  2851. .order_by(pg_catalog.pg_namespace.c.nspname)
  2852. )
  2853. return connection.scalars(query).all()
  2854. def _get_relnames_for_relkinds(self, connection, schema, relkinds, scope):
  2855. query = select(pg_catalog.pg_class.c.relname).where(
  2856. self._pg_class_relkind_condition(relkinds)
  2857. )
  2858. query = self._pg_class_filter_scope_schema(query, schema, scope=scope)
  2859. return connection.scalars(query).all()
  2860. @reflection.cache
  2861. def get_table_names(self, connection, schema=None, **kw):
  2862. return self._get_relnames_for_relkinds(
  2863. connection,
  2864. schema,
  2865. pg_catalog.RELKINDS_TABLE_NO_FOREIGN,
  2866. scope=ObjectScope.DEFAULT,
  2867. )
  2868. @reflection.cache
  2869. def get_temp_table_names(self, connection, **kw):
  2870. return self._get_relnames_for_relkinds(
  2871. connection,
  2872. schema=None,
  2873. relkinds=pg_catalog.RELKINDS_TABLE_NO_FOREIGN,
  2874. scope=ObjectScope.TEMPORARY,
  2875. )
  2876. @reflection.cache
  2877. def _get_foreign_table_names(self, connection, schema=None, **kw):
  2878. return self._get_relnames_for_relkinds(
  2879. connection, schema, relkinds=("f",), scope=ObjectScope.ANY
  2880. )
  2881. @reflection.cache
  2882. def get_view_names(self, connection, schema=None, **kw):
  2883. return self._get_relnames_for_relkinds(
  2884. connection,
  2885. schema,
  2886. pg_catalog.RELKINDS_VIEW,
  2887. scope=ObjectScope.DEFAULT,
  2888. )
  2889. @reflection.cache
  2890. def get_materialized_view_names(self, connection, schema=None, **kw):
  2891. return self._get_relnames_for_relkinds(
  2892. connection,
  2893. schema,
  2894. pg_catalog.RELKINDS_MAT_VIEW,
  2895. scope=ObjectScope.DEFAULT,
  2896. )
  2897. @reflection.cache
  2898. def get_temp_view_names(self, connection, schema=None, **kw):
  2899. return self._get_relnames_for_relkinds(
  2900. connection,
  2901. schema,
  2902. # NOTE: do not include temp materialzied views (that do not
  2903. # seem to be a thing at least up to version 14)
  2904. pg_catalog.RELKINDS_VIEW,
  2905. scope=ObjectScope.TEMPORARY,
  2906. )
  2907. @reflection.cache
  2908. def get_sequence_names(self, connection, schema=None, **kw):
  2909. return self._get_relnames_for_relkinds(
  2910. connection, schema, relkinds=("S",), scope=ObjectScope.ANY
  2911. )
  2912. @reflection.cache
  2913. def get_view_definition(self, connection, view_name, schema=None, **kw):
  2914. query = (
  2915. select(pg_catalog.pg_get_viewdef(pg_catalog.pg_class.c.oid))
  2916. .select_from(pg_catalog.pg_class)
  2917. .where(
  2918. pg_catalog.pg_class.c.relname == view_name,
  2919. self._pg_class_relkind_condition(
  2920. pg_catalog.RELKINDS_VIEW + pg_catalog.RELKINDS_MAT_VIEW
  2921. ),
  2922. )
  2923. )
  2924. query = self._pg_class_filter_scope_schema(
  2925. query, schema, scope=ObjectScope.ANY
  2926. )
  2927. res = connection.scalar(query)
  2928. if res is None:
  2929. raise exc.NoSuchTableError(
  2930. f"{schema}.{view_name}" if schema else view_name
  2931. )
  2932. else:
  2933. return res
  2934. def _value_or_raise(self, data, table, schema):
  2935. try:
  2936. return dict(data)[(schema, table)]
  2937. except KeyError:
  2938. raise exc.NoSuchTableError(
  2939. f"{schema}.{table}" if schema else table
  2940. ) from None
  2941. def _prepare_filter_names(self, filter_names):
  2942. if filter_names:
  2943. return True, {"filter_names": filter_names}
  2944. else:
  2945. return False, {}
  2946. def _kind_to_relkinds(self, kind: ObjectKind) -> Tuple[str, ...]:
  2947. if kind is ObjectKind.ANY:
  2948. return pg_catalog.RELKINDS_ALL_TABLE_LIKE
  2949. relkinds = ()
  2950. if ObjectKind.TABLE in kind:
  2951. relkinds += pg_catalog.RELKINDS_TABLE
  2952. if ObjectKind.VIEW in kind:
  2953. relkinds += pg_catalog.RELKINDS_VIEW
  2954. if ObjectKind.MATERIALIZED_VIEW in kind:
  2955. relkinds += pg_catalog.RELKINDS_MAT_VIEW
  2956. return relkinds
  2957. @reflection.cache
  2958. def get_columns(self, connection, table_name, schema=None, **kw):
  2959. data = self.get_multi_columns(
  2960. connection,
  2961. schema=schema,
  2962. filter_names=[table_name],
  2963. scope=ObjectScope.ANY,
  2964. kind=ObjectKind.ANY,
  2965. **kw,
  2966. )
  2967. return self._value_or_raise(data, table_name, schema)
  2968. @lru_cache()
  2969. def _columns_query(self, schema, has_filter_names, scope, kind):
  2970. # NOTE: the query with the default and identity options scalar
  2971. # subquery is faster than trying to use outer joins for them
  2972. generated = (
  2973. pg_catalog.pg_attribute.c.attgenerated.label("generated")
  2974. if self.server_version_info >= (12,)
  2975. else sql.null().label("generated")
  2976. )
  2977. if self.server_version_info >= (10,):
  2978. # join lateral performs worse (~2x slower) than a scalar_subquery
  2979. identity = (
  2980. select(
  2981. sql.func.json_build_object(
  2982. "always",
  2983. pg_catalog.pg_attribute.c.attidentity == "a",
  2984. "start",
  2985. pg_catalog.pg_sequence.c.seqstart,
  2986. "increment",
  2987. pg_catalog.pg_sequence.c.seqincrement,
  2988. "minvalue",
  2989. pg_catalog.pg_sequence.c.seqmin,
  2990. "maxvalue",
  2991. pg_catalog.pg_sequence.c.seqmax,
  2992. "cache",
  2993. pg_catalog.pg_sequence.c.seqcache,
  2994. "cycle",
  2995. pg_catalog.pg_sequence.c.seqcycle,
  2996. type_=sqltypes.JSON(),
  2997. )
  2998. )
  2999. .select_from(pg_catalog.pg_sequence)
  3000. .where(
  3001. # attidentity != '' is required or it will reflect also
  3002. # serial columns as identity.
  3003. pg_catalog.pg_attribute.c.attidentity != "",
  3004. pg_catalog.pg_sequence.c.seqrelid
  3005. == sql.cast(
  3006. sql.cast(
  3007. pg_catalog.pg_get_serial_sequence(
  3008. sql.cast(
  3009. sql.cast(
  3010. pg_catalog.pg_attribute.c.attrelid,
  3011. REGCLASS,
  3012. ),
  3013. TEXT,
  3014. ),
  3015. pg_catalog.pg_attribute.c.attname,
  3016. ),
  3017. REGCLASS,
  3018. ),
  3019. OID,
  3020. ),
  3021. )
  3022. .correlate(pg_catalog.pg_attribute)
  3023. .scalar_subquery()
  3024. .label("identity_options")
  3025. )
  3026. else:
  3027. identity = sql.null().label("identity_options")
  3028. # join lateral performs the same as scalar_subquery here
  3029. default = (
  3030. select(
  3031. pg_catalog.pg_get_expr(
  3032. pg_catalog.pg_attrdef.c.adbin,
  3033. pg_catalog.pg_attrdef.c.adrelid,
  3034. )
  3035. )
  3036. .select_from(pg_catalog.pg_attrdef)
  3037. .where(
  3038. pg_catalog.pg_attrdef.c.adrelid
  3039. == pg_catalog.pg_attribute.c.attrelid,
  3040. pg_catalog.pg_attrdef.c.adnum
  3041. == pg_catalog.pg_attribute.c.attnum,
  3042. pg_catalog.pg_attribute.c.atthasdef,
  3043. )
  3044. .correlate(pg_catalog.pg_attribute)
  3045. .scalar_subquery()
  3046. .label("default")
  3047. )
  3048. relkinds = self._kind_to_relkinds(kind)
  3049. query = (
  3050. select(
  3051. pg_catalog.pg_attribute.c.attname.label("name"),
  3052. pg_catalog.format_type(
  3053. pg_catalog.pg_attribute.c.atttypid,
  3054. pg_catalog.pg_attribute.c.atttypmod,
  3055. ).label("format_type"),
  3056. default,
  3057. pg_catalog.pg_attribute.c.attnotnull.label("not_null"),
  3058. pg_catalog.pg_class.c.relname.label("table_name"),
  3059. pg_catalog.pg_description.c.description.label("comment"),
  3060. generated,
  3061. identity,
  3062. )
  3063. .select_from(pg_catalog.pg_class)
  3064. # NOTE: postgresql support table with no user column, meaning
  3065. # there is no row with pg_attribute.attnum > 0. use a left outer
  3066. # join to avoid filtering these tables.
  3067. .outerjoin(
  3068. pg_catalog.pg_attribute,
  3069. sql.and_(
  3070. pg_catalog.pg_class.c.oid
  3071. == pg_catalog.pg_attribute.c.attrelid,
  3072. pg_catalog.pg_attribute.c.attnum > 0,
  3073. ~pg_catalog.pg_attribute.c.attisdropped,
  3074. ),
  3075. )
  3076. .outerjoin(
  3077. pg_catalog.pg_description,
  3078. sql.and_(
  3079. pg_catalog.pg_description.c.objoid
  3080. == pg_catalog.pg_attribute.c.attrelid,
  3081. pg_catalog.pg_description.c.objsubid
  3082. == pg_catalog.pg_attribute.c.attnum,
  3083. ),
  3084. )
  3085. .where(self._pg_class_relkind_condition(relkinds))
  3086. .order_by(
  3087. pg_catalog.pg_class.c.relname, pg_catalog.pg_attribute.c.attnum
  3088. )
  3089. )
  3090. query = self._pg_class_filter_scope_schema(query, schema, scope=scope)
  3091. if has_filter_names:
  3092. query = query.where(
  3093. pg_catalog.pg_class.c.relname.in_(bindparam("filter_names"))
  3094. )
  3095. return query
  3096. def get_multi_columns(
  3097. self, connection, schema, filter_names, scope, kind, **kw
  3098. ):
  3099. has_filter_names, params = self._prepare_filter_names(filter_names)
  3100. query = self._columns_query(schema, has_filter_names, scope, kind)
  3101. rows = connection.execute(query, params).mappings()
  3102. # dictionary with (name, ) if default search path or (schema, name)
  3103. # as keys
  3104. domains = {
  3105. ((d["schema"], d["name"]) if not d["visible"] else (d["name"],)): d
  3106. for d in self._load_domains(
  3107. connection, schema="*", info_cache=kw.get("info_cache")
  3108. )
  3109. }
  3110. # dictionary with (name, ) if default search path or (schema, name)
  3111. # as keys
  3112. enums = dict(
  3113. (
  3114. ((rec["name"],), rec)
  3115. if rec["visible"]
  3116. else ((rec["schema"], rec["name"]), rec)
  3117. )
  3118. for rec in self._load_enums(
  3119. connection, schema="*", info_cache=kw.get("info_cache")
  3120. )
  3121. )
  3122. columns = self._get_columns_info(rows, domains, enums, schema)
  3123. return columns.items()
  3124. _format_type_args_pattern = re.compile(r"\((.*)\)")
  3125. _format_type_args_delim = re.compile(r"\s*,\s*")
  3126. _format_array_spec_pattern = re.compile(r"((?:\[\])*)$")
  3127. def _reflect_type(
  3128. self,
  3129. format_type: Optional[str],
  3130. domains: Dict[str, ReflectedDomain],
  3131. enums: Dict[str, ReflectedEnum],
  3132. type_description: str,
  3133. ) -> sqltypes.TypeEngine[Any]:
  3134. """
  3135. Attempts to reconstruct a column type defined in ischema_names based
  3136. on the information available in the format_type.
  3137. If the `format_type` cannot be associated with a known `ischema_names`,
  3138. it is treated as a reference to a known PostgreSQL named `ENUM` or
  3139. `DOMAIN` type.
  3140. """
  3141. type_description = type_description or "unknown type"
  3142. if format_type is None:
  3143. util.warn(
  3144. "PostgreSQL format_type() returned NULL for %s"
  3145. % type_description
  3146. )
  3147. return sqltypes.NULLTYPE
  3148. attype_args_match = self._format_type_args_pattern.search(format_type)
  3149. if attype_args_match and attype_args_match.group(1):
  3150. attype_args = self._format_type_args_delim.split(
  3151. attype_args_match.group(1)
  3152. )
  3153. else:
  3154. attype_args = ()
  3155. match_array_dim = self._format_array_spec_pattern.search(format_type)
  3156. # Each "[]" in array specs corresponds to an array dimension
  3157. array_dim = len(match_array_dim.group(1) or "") // 2
  3158. # Remove all parameters and array specs from format_type to obtain an
  3159. # ischema_name candidate
  3160. attype = self._format_type_args_pattern.sub("", format_type)
  3161. attype = self._format_array_spec_pattern.sub("", attype)
  3162. schema_type = self.ischema_names.get(attype.lower(), None)
  3163. args, kwargs = (), {}
  3164. if attype == "numeric":
  3165. if len(attype_args) == 2:
  3166. precision, scale = map(int, attype_args)
  3167. args = (precision, scale)
  3168. elif attype == "double precision":
  3169. args = (53,)
  3170. elif attype == "integer":
  3171. args = ()
  3172. elif attype in ("timestamp with time zone", "time with time zone"):
  3173. kwargs["timezone"] = True
  3174. if len(attype_args) == 1:
  3175. kwargs["precision"] = int(attype_args[0])
  3176. elif attype in (
  3177. "timestamp without time zone",
  3178. "time without time zone",
  3179. "time",
  3180. ):
  3181. kwargs["timezone"] = False
  3182. if len(attype_args) == 1:
  3183. kwargs["precision"] = int(attype_args[0])
  3184. elif attype == "bit varying":
  3185. kwargs["varying"] = True
  3186. if len(attype_args) == 1:
  3187. charlen = int(attype_args[0])
  3188. args = (charlen,)
  3189. elif attype.startswith("interval"):
  3190. schema_type = INTERVAL
  3191. field_match = re.match(r"interval (.+)", attype)
  3192. if field_match:
  3193. kwargs["fields"] = field_match.group(1)
  3194. if len(attype_args) == 1:
  3195. kwargs["precision"] = int(attype_args[0])
  3196. else:
  3197. enum_or_domain_key = tuple(util.quoted_token_parser(attype))
  3198. if enum_or_domain_key in enums:
  3199. schema_type = ENUM
  3200. enum = enums[enum_or_domain_key]
  3201. kwargs["name"] = enum["name"]
  3202. if not enum["visible"]:
  3203. kwargs["schema"] = enum["schema"]
  3204. args = tuple(enum["labels"])
  3205. elif enum_or_domain_key in domains:
  3206. schema_type = DOMAIN
  3207. domain = domains[enum_or_domain_key]
  3208. data_type = self._reflect_type(
  3209. domain["type"],
  3210. domains,
  3211. enums,
  3212. type_description="DOMAIN '%s'" % domain["name"],
  3213. )
  3214. args = (domain["name"], data_type)
  3215. kwargs["collation"] = domain["collation"]
  3216. kwargs["default"] = domain["default"]
  3217. kwargs["not_null"] = not domain["nullable"]
  3218. kwargs["create_type"] = False
  3219. if domain["constraints"]:
  3220. # We only support a single constraint
  3221. check_constraint = domain["constraints"][0]
  3222. kwargs["constraint_name"] = check_constraint["name"]
  3223. kwargs["check"] = check_constraint["check"]
  3224. if not domain["visible"]:
  3225. kwargs["schema"] = domain["schema"]
  3226. else:
  3227. try:
  3228. charlen = int(attype_args[0])
  3229. args = (charlen, *attype_args[1:])
  3230. except (ValueError, IndexError):
  3231. args = attype_args
  3232. if not schema_type:
  3233. util.warn(
  3234. "Did not recognize type '%s' of %s"
  3235. % (attype, type_description)
  3236. )
  3237. return sqltypes.NULLTYPE
  3238. data_type = schema_type(*args, **kwargs)
  3239. if array_dim >= 1:
  3240. # postgres does not preserve dimensionality or size of array types.
  3241. data_type = _array.ARRAY(data_type)
  3242. return data_type
  3243. def _get_columns_info(self, rows, domains, enums, schema):
  3244. columns = defaultdict(list)
  3245. for row_dict in rows:
  3246. # ensure that each table has an entry, even if it has no columns
  3247. if row_dict["name"] is None:
  3248. columns[(schema, row_dict["table_name"])] = (
  3249. ReflectionDefaults.columns()
  3250. )
  3251. continue
  3252. table_cols = columns[(schema, row_dict["table_name"])]
  3253. coltype = self._reflect_type(
  3254. row_dict["format_type"],
  3255. domains,
  3256. enums,
  3257. type_description="column '%s'" % row_dict["name"],
  3258. )
  3259. default = row_dict["default"]
  3260. name = row_dict["name"]
  3261. generated = row_dict["generated"]
  3262. nullable = not row_dict["not_null"]
  3263. if isinstance(coltype, DOMAIN):
  3264. if not default:
  3265. # domain can override the default value but
  3266. # cant set it to None
  3267. if coltype.default is not None:
  3268. default = coltype.default
  3269. nullable = nullable and not coltype.not_null
  3270. identity = row_dict["identity_options"]
  3271. # If a zero byte or blank string depending on driver (is also
  3272. # absent for older PG versions), then not a generated column.
  3273. # Otherwise, s = stored. (Other values might be added in the
  3274. # future.)
  3275. if generated not in (None, "", b"\x00"):
  3276. computed = dict(
  3277. sqltext=default, persisted=generated in ("s", b"s")
  3278. )
  3279. default = None
  3280. else:
  3281. computed = None
  3282. # adjust the default value
  3283. autoincrement = False
  3284. if default is not None:
  3285. match = re.search(r"""(nextval\(')([^']+)('.*$)""", default)
  3286. if match is not None:
  3287. if issubclass(coltype._type_affinity, sqltypes.Integer):
  3288. autoincrement = True
  3289. # the default is related to a Sequence
  3290. if "." not in match.group(2) and schema is not None:
  3291. # unconditionally quote the schema name. this could
  3292. # later be enhanced to obey quoting rules /
  3293. # "quote schema"
  3294. default = (
  3295. match.group(1)
  3296. + ('"%s"' % schema)
  3297. + "."
  3298. + match.group(2)
  3299. + match.group(3)
  3300. )
  3301. column_info = {
  3302. "name": name,
  3303. "type": coltype,
  3304. "nullable": nullable,
  3305. "default": default,
  3306. "autoincrement": autoincrement or identity is not None,
  3307. "comment": row_dict["comment"],
  3308. }
  3309. if computed is not None:
  3310. column_info["computed"] = computed
  3311. if identity is not None:
  3312. column_info["identity"] = identity
  3313. table_cols.append(column_info)
  3314. return columns
  3315. @lru_cache()
  3316. def _table_oids_query(self, schema, has_filter_names, scope, kind):
  3317. relkinds = self._kind_to_relkinds(kind)
  3318. oid_q = select(
  3319. pg_catalog.pg_class.c.oid, pg_catalog.pg_class.c.relname
  3320. ).where(self._pg_class_relkind_condition(relkinds))
  3321. oid_q = self._pg_class_filter_scope_schema(oid_q, schema, scope=scope)
  3322. if has_filter_names:
  3323. oid_q = oid_q.where(
  3324. pg_catalog.pg_class.c.relname.in_(bindparam("filter_names"))
  3325. )
  3326. return oid_q
  3327. @reflection.flexi_cache(
  3328. ("schema", InternalTraversal.dp_string),
  3329. ("filter_names", InternalTraversal.dp_string_list),
  3330. ("kind", InternalTraversal.dp_plain_obj),
  3331. ("scope", InternalTraversal.dp_plain_obj),
  3332. )
  3333. def _get_table_oids(
  3334. self, connection, schema, filter_names, scope, kind, **kw
  3335. ):
  3336. has_filter_names, params = self._prepare_filter_names(filter_names)
  3337. oid_q = self._table_oids_query(schema, has_filter_names, scope, kind)
  3338. result = connection.execute(oid_q, params)
  3339. return result.all()
  3340. @util.memoized_property
  3341. def _constraint_query(self):
  3342. if self.server_version_info >= (11, 0):
  3343. indnkeyatts = pg_catalog.pg_index.c.indnkeyatts
  3344. else:
  3345. indnkeyatts = sql.null().label("indnkeyatts")
  3346. if self.server_version_info >= (15,):
  3347. indnullsnotdistinct = pg_catalog.pg_index.c.indnullsnotdistinct
  3348. else:
  3349. indnullsnotdistinct = sql.false().label("indnullsnotdistinct")
  3350. con_sq = (
  3351. select(
  3352. pg_catalog.pg_constraint.c.conrelid,
  3353. pg_catalog.pg_constraint.c.conname,
  3354. sql.func.unnest(pg_catalog.pg_index.c.indkey).label("attnum"),
  3355. sql.func.generate_subscripts(
  3356. pg_catalog.pg_index.c.indkey, 1
  3357. ).label("ord"),
  3358. indnkeyatts,
  3359. indnullsnotdistinct,
  3360. pg_catalog.pg_description.c.description,
  3361. )
  3362. .join(
  3363. pg_catalog.pg_index,
  3364. pg_catalog.pg_constraint.c.conindid
  3365. == pg_catalog.pg_index.c.indexrelid,
  3366. )
  3367. .outerjoin(
  3368. pg_catalog.pg_description,
  3369. pg_catalog.pg_description.c.objoid
  3370. == pg_catalog.pg_constraint.c.oid,
  3371. )
  3372. .where(
  3373. pg_catalog.pg_constraint.c.contype == bindparam("contype"),
  3374. pg_catalog.pg_constraint.c.conrelid.in_(bindparam("oids")),
  3375. # NOTE: filtering also on pg_index.indrelid for oids does
  3376. # not seem to have a performance effect, but it may be an
  3377. # option if perf problems are reported
  3378. )
  3379. .subquery("con")
  3380. )
  3381. attr_sq = (
  3382. select(
  3383. con_sq.c.conrelid,
  3384. con_sq.c.conname,
  3385. con_sq.c.description,
  3386. con_sq.c.ord,
  3387. con_sq.c.indnkeyatts,
  3388. con_sq.c.indnullsnotdistinct,
  3389. pg_catalog.pg_attribute.c.attname,
  3390. )
  3391. .select_from(pg_catalog.pg_attribute)
  3392. .join(
  3393. con_sq,
  3394. sql.and_(
  3395. pg_catalog.pg_attribute.c.attnum == con_sq.c.attnum,
  3396. pg_catalog.pg_attribute.c.attrelid == con_sq.c.conrelid,
  3397. ),
  3398. )
  3399. .where(
  3400. # NOTE: restate the condition here, since pg15 otherwise
  3401. # seems to get confused on pscopg2 sometimes, doing
  3402. # a sequential scan of pg_attribute.
  3403. # The condition in the con_sq subquery is not actually needed
  3404. # in pg15, but it may be needed in older versions. Keeping it
  3405. # does not seems to have any inpact in any case.
  3406. con_sq.c.conrelid.in_(bindparam("oids"))
  3407. )
  3408. .subquery("attr")
  3409. )
  3410. return (
  3411. select(
  3412. attr_sq.c.conrelid,
  3413. sql.func.array_agg(
  3414. # NOTE: cast since some postgresql derivatives may
  3415. # not support array_agg on the name type
  3416. aggregate_order_by(
  3417. attr_sq.c.attname.cast(TEXT), attr_sq.c.ord
  3418. )
  3419. ).label("cols"),
  3420. attr_sq.c.conname,
  3421. sql.func.min(attr_sq.c.description).label("description"),
  3422. sql.func.min(attr_sq.c.indnkeyatts).label("indnkeyatts"),
  3423. sql.func.bool_and(attr_sq.c.indnullsnotdistinct).label(
  3424. "indnullsnotdistinct"
  3425. ),
  3426. )
  3427. .group_by(attr_sq.c.conrelid, attr_sq.c.conname)
  3428. .order_by(attr_sq.c.conrelid, attr_sq.c.conname)
  3429. )
  3430. def _reflect_constraint(
  3431. self, connection, contype, schema, filter_names, scope, kind, **kw
  3432. ):
  3433. # used to reflect primary and unique constraint
  3434. table_oids = self._get_table_oids(
  3435. connection, schema, filter_names, scope, kind, **kw
  3436. )
  3437. batches = list(table_oids)
  3438. is_unique = contype == "u"
  3439. while batches:
  3440. batch = batches[0:3000]
  3441. batches[0:3000] = []
  3442. result = connection.execute(
  3443. self._constraint_query,
  3444. {"oids": [r[0] for r in batch], "contype": contype},
  3445. ).mappings()
  3446. result_by_oid = defaultdict(list)
  3447. for row_dict in result:
  3448. result_by_oid[row_dict["conrelid"]].append(row_dict)
  3449. for oid, tablename in batch:
  3450. for_oid = result_by_oid.get(oid, ())
  3451. if for_oid:
  3452. for row in for_oid:
  3453. # See note in get_multi_indexes
  3454. all_cols = row["cols"]
  3455. indnkeyatts = row["indnkeyatts"]
  3456. if (
  3457. indnkeyatts is not None
  3458. and len(all_cols) > indnkeyatts
  3459. ):
  3460. inc_cols = all_cols[indnkeyatts:]
  3461. cst_cols = all_cols[:indnkeyatts]
  3462. else:
  3463. inc_cols = []
  3464. cst_cols = all_cols
  3465. opts = {}
  3466. if self.server_version_info >= (11,):
  3467. opts["postgresql_include"] = inc_cols
  3468. if is_unique:
  3469. opts["postgresql_nulls_not_distinct"] = row[
  3470. "indnullsnotdistinct"
  3471. ]
  3472. yield (
  3473. tablename,
  3474. cst_cols,
  3475. row["conname"],
  3476. row["description"],
  3477. opts,
  3478. )
  3479. else:
  3480. yield tablename, None, None, None, None
  3481. @reflection.cache
  3482. def get_pk_constraint(self, connection, table_name, schema=None, **kw):
  3483. data = self.get_multi_pk_constraint(
  3484. connection,
  3485. schema=schema,
  3486. filter_names=[table_name],
  3487. scope=ObjectScope.ANY,
  3488. kind=ObjectKind.ANY,
  3489. **kw,
  3490. )
  3491. return self._value_or_raise(data, table_name, schema)
  3492. def get_multi_pk_constraint(
  3493. self, connection, schema, filter_names, scope, kind, **kw
  3494. ):
  3495. result = self._reflect_constraint(
  3496. connection, "p", schema, filter_names, scope, kind, **kw
  3497. )
  3498. # only a single pk can be present for each table. Return an entry
  3499. # even if a table has no primary key
  3500. default = ReflectionDefaults.pk_constraint
  3501. def pk_constraint(pk_name, cols, comment, opts):
  3502. info = {
  3503. "constrained_columns": cols,
  3504. "name": pk_name,
  3505. "comment": comment,
  3506. }
  3507. if opts:
  3508. info["dialect_options"] = opts
  3509. return info
  3510. return (
  3511. (
  3512. (schema, table_name),
  3513. (
  3514. pk_constraint(pk_name, cols, comment, opts)
  3515. if pk_name is not None
  3516. else default()
  3517. ),
  3518. )
  3519. for table_name, cols, pk_name, comment, opts in result
  3520. )
  3521. @reflection.cache
  3522. def get_foreign_keys(
  3523. self,
  3524. connection,
  3525. table_name,
  3526. schema=None,
  3527. postgresql_ignore_search_path=False,
  3528. **kw,
  3529. ):
  3530. data = self.get_multi_foreign_keys(
  3531. connection,
  3532. schema=schema,
  3533. filter_names=[table_name],
  3534. postgresql_ignore_search_path=postgresql_ignore_search_path,
  3535. scope=ObjectScope.ANY,
  3536. kind=ObjectKind.ANY,
  3537. **kw,
  3538. )
  3539. return self._value_or_raise(data, table_name, schema)
  3540. @lru_cache()
  3541. def _foreing_key_query(self, schema, has_filter_names, scope, kind):
  3542. pg_class_ref = pg_catalog.pg_class.alias("cls_ref")
  3543. pg_namespace_ref = pg_catalog.pg_namespace.alias("nsp_ref")
  3544. relkinds = self._kind_to_relkinds(kind)
  3545. query = (
  3546. select(
  3547. pg_catalog.pg_class.c.relname,
  3548. pg_catalog.pg_constraint.c.conname,
  3549. # NOTE: avoid calling pg_get_constraintdef when not needed
  3550. # to speed up the query
  3551. sql.case(
  3552. (
  3553. pg_catalog.pg_constraint.c.oid.is_not(None),
  3554. pg_catalog.pg_get_constraintdef(
  3555. pg_catalog.pg_constraint.c.oid, True
  3556. ),
  3557. ),
  3558. else_=None,
  3559. ),
  3560. pg_namespace_ref.c.nspname,
  3561. pg_catalog.pg_description.c.description,
  3562. )
  3563. .select_from(pg_catalog.pg_class)
  3564. .outerjoin(
  3565. pg_catalog.pg_constraint,
  3566. sql.and_(
  3567. pg_catalog.pg_class.c.oid
  3568. == pg_catalog.pg_constraint.c.conrelid,
  3569. pg_catalog.pg_constraint.c.contype == "f",
  3570. ),
  3571. )
  3572. .outerjoin(
  3573. pg_class_ref,
  3574. pg_class_ref.c.oid == pg_catalog.pg_constraint.c.confrelid,
  3575. )
  3576. .outerjoin(
  3577. pg_namespace_ref,
  3578. pg_class_ref.c.relnamespace == pg_namespace_ref.c.oid,
  3579. )
  3580. .outerjoin(
  3581. pg_catalog.pg_description,
  3582. pg_catalog.pg_description.c.objoid
  3583. == pg_catalog.pg_constraint.c.oid,
  3584. )
  3585. .order_by(
  3586. pg_catalog.pg_class.c.relname,
  3587. pg_catalog.pg_constraint.c.conname,
  3588. )
  3589. .where(self._pg_class_relkind_condition(relkinds))
  3590. )
  3591. query = self._pg_class_filter_scope_schema(query, schema, scope)
  3592. if has_filter_names:
  3593. query = query.where(
  3594. pg_catalog.pg_class.c.relname.in_(bindparam("filter_names"))
  3595. )
  3596. return query
  3597. @util.memoized_property
  3598. def _fk_regex_pattern(self):
  3599. # optionally quoted token
  3600. qtoken = '(?:"[^"]+"|[A-Za-z0-9_]+?)'
  3601. # https://www.postgresql.org/docs/current/static/sql-createtable.html
  3602. return re.compile(
  3603. r"FOREIGN KEY \((.*?)\) "
  3604. rf"REFERENCES (?:({qtoken})\.)?({qtoken})\(((?:{qtoken}(?: *, *)?)+)\)" # noqa: E501
  3605. r"[\s]?(MATCH (FULL|PARTIAL|SIMPLE)+)?"
  3606. r"[\s]?(ON UPDATE "
  3607. r"(CASCADE|RESTRICT|NO ACTION|SET NULL|SET DEFAULT)+)?"
  3608. r"[\s]?(ON DELETE "
  3609. r"(CASCADE|RESTRICT|NO ACTION|"
  3610. r"SET (?:NULL|DEFAULT)(?:\s\(.+\))?)+)?"
  3611. r"[\s]?(DEFERRABLE|NOT DEFERRABLE)?"
  3612. r"[\s]?(INITIALLY (DEFERRED|IMMEDIATE)+)?"
  3613. )
  3614. def get_multi_foreign_keys(
  3615. self,
  3616. connection,
  3617. schema,
  3618. filter_names,
  3619. scope,
  3620. kind,
  3621. postgresql_ignore_search_path=False,
  3622. **kw,
  3623. ):
  3624. preparer = self.identifier_preparer
  3625. has_filter_names, params = self._prepare_filter_names(filter_names)
  3626. query = self._foreing_key_query(schema, has_filter_names, scope, kind)
  3627. result = connection.execute(query, params)
  3628. FK_REGEX = self._fk_regex_pattern
  3629. fkeys = defaultdict(list)
  3630. default = ReflectionDefaults.foreign_keys
  3631. for table_name, conname, condef, conschema, comment in result:
  3632. # ensure that each table has an entry, even if it has
  3633. # no foreign keys
  3634. if conname is None:
  3635. fkeys[(schema, table_name)] = default()
  3636. continue
  3637. table_fks = fkeys[(schema, table_name)]
  3638. m = re.search(FK_REGEX, condef).groups()
  3639. (
  3640. constrained_columns,
  3641. referred_schema,
  3642. referred_table,
  3643. referred_columns,
  3644. _,
  3645. match,
  3646. _,
  3647. onupdate,
  3648. _,
  3649. ondelete,
  3650. deferrable,
  3651. _,
  3652. initially,
  3653. ) = m
  3654. if deferrable is not None:
  3655. deferrable = True if deferrable == "DEFERRABLE" else False
  3656. constrained_columns = [
  3657. preparer._unquote_identifier(x)
  3658. for x in re.split(r"\s*,\s*", constrained_columns)
  3659. ]
  3660. if postgresql_ignore_search_path:
  3661. # when ignoring search path, we use the actual schema
  3662. # provided it isn't the "default" schema
  3663. if conschema != self.default_schema_name:
  3664. referred_schema = conschema
  3665. else:
  3666. referred_schema = schema
  3667. elif referred_schema:
  3668. # referred_schema is the schema that we regexp'ed from
  3669. # pg_get_constraintdef(). If the schema is in the search
  3670. # path, pg_get_constraintdef() will give us None.
  3671. referred_schema = preparer._unquote_identifier(referred_schema)
  3672. elif schema is not None and schema == conschema:
  3673. # If the actual schema matches the schema of the table
  3674. # we're reflecting, then we will use that.
  3675. referred_schema = schema
  3676. referred_table = preparer._unquote_identifier(referred_table)
  3677. referred_columns = [
  3678. preparer._unquote_identifier(x)
  3679. for x in re.split(r"\s*,\s", referred_columns)
  3680. ]
  3681. options = {
  3682. k: v
  3683. for k, v in [
  3684. ("onupdate", onupdate),
  3685. ("ondelete", ondelete),
  3686. ("initially", initially),
  3687. ("deferrable", deferrable),
  3688. ("match", match),
  3689. ]
  3690. if v is not None and v != "NO ACTION"
  3691. }
  3692. fkey_d = {
  3693. "name": conname,
  3694. "constrained_columns": constrained_columns,
  3695. "referred_schema": referred_schema,
  3696. "referred_table": referred_table,
  3697. "referred_columns": referred_columns,
  3698. "options": options,
  3699. "comment": comment,
  3700. }
  3701. table_fks.append(fkey_d)
  3702. return fkeys.items()
  3703. @reflection.cache
  3704. def get_indexes(self, connection, table_name, schema=None, **kw):
  3705. data = self.get_multi_indexes(
  3706. connection,
  3707. schema=schema,
  3708. filter_names=[table_name],
  3709. scope=ObjectScope.ANY,
  3710. kind=ObjectKind.ANY,
  3711. **kw,
  3712. )
  3713. return self._value_or_raise(data, table_name, schema)
  3714. @util.memoized_property
  3715. def _index_query(self):
  3716. # NOTE: pg_index is used as from two times to improve performance,
  3717. # since extraing all the index information from `idx_sq` to avoid
  3718. # the second pg_index use leads to a worse performing query in
  3719. # particular when querying for a single table (as of pg 17)
  3720. # NOTE: repeating oids clause improve query performance
  3721. # subquery to get the columns
  3722. idx_sq = (
  3723. select(
  3724. pg_catalog.pg_index.c.indexrelid,
  3725. pg_catalog.pg_index.c.indrelid,
  3726. sql.func.unnest(pg_catalog.pg_index.c.indkey).label("attnum"),
  3727. sql.func.generate_subscripts(
  3728. pg_catalog.pg_index.c.indkey, 1
  3729. ).label("ord"),
  3730. )
  3731. .where(
  3732. ~pg_catalog.pg_index.c.indisprimary,
  3733. pg_catalog.pg_index.c.indrelid.in_(bindparam("oids")),
  3734. )
  3735. .subquery("idx")
  3736. )
  3737. attr_sq = (
  3738. select(
  3739. idx_sq.c.indexrelid,
  3740. idx_sq.c.indrelid,
  3741. idx_sq.c.ord,
  3742. # NOTE: always using pg_get_indexdef is too slow so just
  3743. # invoke when the element is an expression
  3744. sql.case(
  3745. (
  3746. idx_sq.c.attnum == 0,
  3747. pg_catalog.pg_get_indexdef(
  3748. idx_sq.c.indexrelid, idx_sq.c.ord + 1, True
  3749. ),
  3750. ),
  3751. # NOTE: need to cast this since attname is of type "name"
  3752. # that's limited to 63 bytes, while pg_get_indexdef
  3753. # returns "text" so its output may get cut
  3754. else_=pg_catalog.pg_attribute.c.attname.cast(TEXT),
  3755. ).label("element"),
  3756. (idx_sq.c.attnum == 0).label("is_expr"),
  3757. )
  3758. .select_from(idx_sq)
  3759. .outerjoin(
  3760. # do not remove rows where idx_sq.c.attnum is 0
  3761. pg_catalog.pg_attribute,
  3762. sql.and_(
  3763. pg_catalog.pg_attribute.c.attnum == idx_sq.c.attnum,
  3764. pg_catalog.pg_attribute.c.attrelid == idx_sq.c.indrelid,
  3765. ),
  3766. )
  3767. .where(idx_sq.c.indrelid.in_(bindparam("oids")))
  3768. .subquery("idx_attr")
  3769. )
  3770. cols_sq = (
  3771. select(
  3772. attr_sq.c.indexrelid,
  3773. sql.func.min(attr_sq.c.indrelid),
  3774. sql.func.array_agg(
  3775. aggregate_order_by(attr_sq.c.element, attr_sq.c.ord)
  3776. ).label("elements"),
  3777. sql.func.array_agg(
  3778. aggregate_order_by(attr_sq.c.is_expr, attr_sq.c.ord)
  3779. ).label("elements_is_expr"),
  3780. )
  3781. .group_by(attr_sq.c.indexrelid)
  3782. .subquery("idx_cols")
  3783. )
  3784. if self.server_version_info >= (11, 0):
  3785. indnkeyatts = pg_catalog.pg_index.c.indnkeyatts
  3786. else:
  3787. indnkeyatts = sql.null().label("indnkeyatts")
  3788. if self.server_version_info >= (15,):
  3789. nulls_not_distinct = pg_catalog.pg_index.c.indnullsnotdistinct
  3790. else:
  3791. nulls_not_distinct = sql.false().label("indnullsnotdistinct")
  3792. return (
  3793. select(
  3794. pg_catalog.pg_index.c.indrelid,
  3795. pg_catalog.pg_class.c.relname,
  3796. pg_catalog.pg_index.c.indisunique,
  3797. pg_catalog.pg_constraint.c.conrelid.is_not(None).label(
  3798. "has_constraint"
  3799. ),
  3800. pg_catalog.pg_index.c.indoption,
  3801. pg_catalog.pg_class.c.reloptions,
  3802. pg_catalog.pg_am.c.amname,
  3803. # NOTE: pg_get_expr is very fast so this case has almost no
  3804. # performance impact
  3805. sql.case(
  3806. (
  3807. pg_catalog.pg_index.c.indpred.is_not(None),
  3808. pg_catalog.pg_get_expr(
  3809. pg_catalog.pg_index.c.indpred,
  3810. pg_catalog.pg_index.c.indrelid,
  3811. ),
  3812. ),
  3813. else_=None,
  3814. ).label("filter_definition"),
  3815. indnkeyatts,
  3816. nulls_not_distinct,
  3817. cols_sq.c.elements,
  3818. cols_sq.c.elements_is_expr,
  3819. )
  3820. .select_from(pg_catalog.pg_index)
  3821. .where(
  3822. pg_catalog.pg_index.c.indrelid.in_(bindparam("oids")),
  3823. ~pg_catalog.pg_index.c.indisprimary,
  3824. )
  3825. .join(
  3826. pg_catalog.pg_class,
  3827. pg_catalog.pg_index.c.indexrelid == pg_catalog.pg_class.c.oid,
  3828. )
  3829. .join(
  3830. pg_catalog.pg_am,
  3831. pg_catalog.pg_class.c.relam == pg_catalog.pg_am.c.oid,
  3832. )
  3833. .outerjoin(
  3834. cols_sq,
  3835. pg_catalog.pg_index.c.indexrelid == cols_sq.c.indexrelid,
  3836. )
  3837. .outerjoin(
  3838. pg_catalog.pg_constraint,
  3839. sql.and_(
  3840. pg_catalog.pg_index.c.indrelid
  3841. == pg_catalog.pg_constraint.c.conrelid,
  3842. pg_catalog.pg_index.c.indexrelid
  3843. == pg_catalog.pg_constraint.c.conindid,
  3844. pg_catalog.pg_constraint.c.contype
  3845. == sql.any_(_array.array(("p", "u", "x"))),
  3846. ),
  3847. )
  3848. .order_by(
  3849. pg_catalog.pg_index.c.indrelid, pg_catalog.pg_class.c.relname
  3850. )
  3851. )
  3852. def get_multi_indexes(
  3853. self, connection, schema, filter_names, scope, kind, **kw
  3854. ):
  3855. table_oids = self._get_table_oids(
  3856. connection, schema, filter_names, scope, kind, **kw
  3857. )
  3858. indexes = defaultdict(list)
  3859. default = ReflectionDefaults.indexes
  3860. batches = list(table_oids)
  3861. while batches:
  3862. batch = batches[0:3000]
  3863. batches[0:3000] = []
  3864. result = connection.execute(
  3865. self._index_query, {"oids": [r[0] for r in batch]}
  3866. ).mappings()
  3867. result_by_oid = defaultdict(list)
  3868. for row_dict in result:
  3869. result_by_oid[row_dict["indrelid"]].append(row_dict)
  3870. for oid, table_name in batch:
  3871. if oid not in result_by_oid:
  3872. # ensure that each table has an entry, even if reflection
  3873. # is skipped because not supported
  3874. indexes[(schema, table_name)] = default()
  3875. continue
  3876. for row in result_by_oid[oid]:
  3877. index_name = row["relname"]
  3878. table_indexes = indexes[(schema, table_name)]
  3879. all_elements = row["elements"]
  3880. all_elements_is_expr = row["elements_is_expr"]
  3881. indnkeyatts = row["indnkeyatts"]
  3882. # "The number of key columns in the index, not counting any
  3883. # included columns, which are merely stored and do not
  3884. # participate in the index semantics"
  3885. if (
  3886. indnkeyatts is not None
  3887. and len(all_elements) > indnkeyatts
  3888. ):
  3889. # this is a "covering index" which has INCLUDE columns
  3890. # as well as regular index columns
  3891. inc_cols = all_elements[indnkeyatts:]
  3892. idx_elements = all_elements[:indnkeyatts]
  3893. idx_elements_is_expr = all_elements_is_expr[
  3894. :indnkeyatts
  3895. ]
  3896. # postgresql does not support expression on included
  3897. # columns as of v14: "ERROR: expressions are not
  3898. # supported in included columns".
  3899. assert all(
  3900. not is_expr
  3901. for is_expr in all_elements_is_expr[indnkeyatts:]
  3902. )
  3903. else:
  3904. idx_elements = all_elements
  3905. idx_elements_is_expr = all_elements_is_expr
  3906. inc_cols = []
  3907. index = {"name": index_name, "unique": row["indisunique"]}
  3908. if any(idx_elements_is_expr):
  3909. index["column_names"] = [
  3910. None if is_expr else expr
  3911. for expr, is_expr in zip(
  3912. idx_elements, idx_elements_is_expr
  3913. )
  3914. ]
  3915. index["expressions"] = idx_elements
  3916. else:
  3917. index["column_names"] = idx_elements
  3918. sorting = {}
  3919. for col_index, col_flags in enumerate(row["indoption"]):
  3920. col_sorting = ()
  3921. # try to set flags only if they differ from PG
  3922. # defaults...
  3923. if col_flags & 0x01:
  3924. col_sorting += ("desc",)
  3925. if not (col_flags & 0x02):
  3926. col_sorting += ("nulls_last",)
  3927. else:
  3928. if col_flags & 0x02:
  3929. col_sorting += ("nulls_first",)
  3930. if col_sorting:
  3931. sorting[idx_elements[col_index]] = col_sorting
  3932. if sorting:
  3933. index["column_sorting"] = sorting
  3934. if row["has_constraint"]:
  3935. index["duplicates_constraint"] = index_name
  3936. dialect_options = {}
  3937. if row["reloptions"]:
  3938. dialect_options["postgresql_with"] = dict(
  3939. [
  3940. option.split("=", 1)
  3941. for option in row["reloptions"]
  3942. ]
  3943. )
  3944. # it *might* be nice to include that this is 'btree' in the
  3945. # reflection info. But we don't want an Index object
  3946. # to have a ``postgresql_using`` in it that is just the
  3947. # default, so for the moment leaving this out.
  3948. amname = row["amname"]
  3949. if amname != "btree":
  3950. dialect_options["postgresql_using"] = row["amname"]
  3951. if row["filter_definition"]:
  3952. dialect_options["postgresql_where"] = row[
  3953. "filter_definition"
  3954. ]
  3955. if self.server_version_info >= (11,):
  3956. # NOTE: this is legacy, this is part of
  3957. # dialect_options now as of #7382
  3958. index["include_columns"] = inc_cols
  3959. dialect_options["postgresql_include"] = inc_cols
  3960. if row["indnullsnotdistinct"]:
  3961. # the default is False, so ignore it.
  3962. dialect_options["postgresql_nulls_not_distinct"] = row[
  3963. "indnullsnotdistinct"
  3964. ]
  3965. if dialect_options:
  3966. index["dialect_options"] = dialect_options
  3967. table_indexes.append(index)
  3968. return indexes.items()
  3969. @reflection.cache
  3970. def get_unique_constraints(
  3971. self, connection, table_name, schema=None, **kw
  3972. ):
  3973. data = self.get_multi_unique_constraints(
  3974. connection,
  3975. schema=schema,
  3976. filter_names=[table_name],
  3977. scope=ObjectScope.ANY,
  3978. kind=ObjectKind.ANY,
  3979. **kw,
  3980. )
  3981. return self._value_or_raise(data, table_name, schema)
  3982. def get_multi_unique_constraints(
  3983. self,
  3984. connection,
  3985. schema,
  3986. filter_names,
  3987. scope,
  3988. kind,
  3989. **kw,
  3990. ):
  3991. result = self._reflect_constraint(
  3992. connection, "u", schema, filter_names, scope, kind, **kw
  3993. )
  3994. # each table can have multiple unique constraints
  3995. uniques = defaultdict(list)
  3996. default = ReflectionDefaults.unique_constraints
  3997. for table_name, cols, con_name, comment, options in result:
  3998. # ensure a list is created for each table. leave it empty if
  3999. # the table has no unique cosntraint
  4000. if con_name is None:
  4001. uniques[(schema, table_name)] = default()
  4002. continue
  4003. uc_dict = {
  4004. "column_names": cols,
  4005. "name": con_name,
  4006. "comment": comment,
  4007. }
  4008. if options:
  4009. uc_dict["dialect_options"] = options
  4010. uniques[(schema, table_name)].append(uc_dict)
  4011. return uniques.items()
  4012. @reflection.cache
  4013. def get_table_comment(self, connection, table_name, schema=None, **kw):
  4014. data = self.get_multi_table_comment(
  4015. connection,
  4016. schema,
  4017. [table_name],
  4018. scope=ObjectScope.ANY,
  4019. kind=ObjectKind.ANY,
  4020. **kw,
  4021. )
  4022. return self._value_or_raise(data, table_name, schema)
  4023. @lru_cache()
  4024. def _comment_query(self, schema, has_filter_names, scope, kind):
  4025. relkinds = self._kind_to_relkinds(kind)
  4026. query = (
  4027. select(
  4028. pg_catalog.pg_class.c.relname,
  4029. pg_catalog.pg_description.c.description,
  4030. )
  4031. .select_from(pg_catalog.pg_class)
  4032. .outerjoin(
  4033. pg_catalog.pg_description,
  4034. sql.and_(
  4035. pg_catalog.pg_class.c.oid
  4036. == pg_catalog.pg_description.c.objoid,
  4037. pg_catalog.pg_description.c.objsubid == 0,
  4038. pg_catalog.pg_description.c.classoid
  4039. == sql.func.cast("pg_catalog.pg_class", REGCLASS),
  4040. ),
  4041. )
  4042. .where(self._pg_class_relkind_condition(relkinds))
  4043. )
  4044. query = self._pg_class_filter_scope_schema(query, schema, scope)
  4045. if has_filter_names:
  4046. query = query.where(
  4047. pg_catalog.pg_class.c.relname.in_(bindparam("filter_names"))
  4048. )
  4049. return query
  4050. def get_multi_table_comment(
  4051. self, connection, schema, filter_names, scope, kind, **kw
  4052. ):
  4053. has_filter_names, params = self._prepare_filter_names(filter_names)
  4054. query = self._comment_query(schema, has_filter_names, scope, kind)
  4055. result = connection.execute(query, params)
  4056. default = ReflectionDefaults.table_comment
  4057. return (
  4058. (
  4059. (schema, table),
  4060. {"text": comment} if comment is not None else default(),
  4061. )
  4062. for table, comment in result
  4063. )
  4064. @reflection.cache
  4065. def get_check_constraints(self, connection, table_name, schema=None, **kw):
  4066. data = self.get_multi_check_constraints(
  4067. connection,
  4068. schema,
  4069. [table_name],
  4070. scope=ObjectScope.ANY,
  4071. kind=ObjectKind.ANY,
  4072. **kw,
  4073. )
  4074. return self._value_or_raise(data, table_name, schema)
  4075. @lru_cache()
  4076. def _check_constraint_query(self, schema, has_filter_names, scope, kind):
  4077. relkinds = self._kind_to_relkinds(kind)
  4078. query = (
  4079. select(
  4080. pg_catalog.pg_class.c.relname,
  4081. pg_catalog.pg_constraint.c.conname,
  4082. # NOTE: avoid calling pg_get_constraintdef when not needed
  4083. # to speed up the query
  4084. sql.case(
  4085. (
  4086. pg_catalog.pg_constraint.c.oid.is_not(None),
  4087. pg_catalog.pg_get_constraintdef(
  4088. pg_catalog.pg_constraint.c.oid, True
  4089. ),
  4090. ),
  4091. else_=None,
  4092. ),
  4093. pg_catalog.pg_description.c.description,
  4094. )
  4095. .select_from(pg_catalog.pg_class)
  4096. .outerjoin(
  4097. pg_catalog.pg_constraint,
  4098. sql.and_(
  4099. pg_catalog.pg_class.c.oid
  4100. == pg_catalog.pg_constraint.c.conrelid,
  4101. pg_catalog.pg_constraint.c.contype == "c",
  4102. ),
  4103. )
  4104. .outerjoin(
  4105. pg_catalog.pg_description,
  4106. pg_catalog.pg_description.c.objoid
  4107. == pg_catalog.pg_constraint.c.oid,
  4108. )
  4109. .order_by(
  4110. pg_catalog.pg_class.c.relname,
  4111. pg_catalog.pg_constraint.c.conname,
  4112. )
  4113. .where(self._pg_class_relkind_condition(relkinds))
  4114. )
  4115. query = self._pg_class_filter_scope_schema(query, schema, scope)
  4116. if has_filter_names:
  4117. query = query.where(
  4118. pg_catalog.pg_class.c.relname.in_(bindparam("filter_names"))
  4119. )
  4120. return query
  4121. def get_multi_check_constraints(
  4122. self, connection, schema, filter_names, scope, kind, **kw
  4123. ):
  4124. has_filter_names, params = self._prepare_filter_names(filter_names)
  4125. query = self._check_constraint_query(
  4126. schema, has_filter_names, scope, kind
  4127. )
  4128. result = connection.execute(query, params)
  4129. check_constraints = defaultdict(list)
  4130. default = ReflectionDefaults.check_constraints
  4131. for table_name, check_name, src, comment in result:
  4132. # only two cases for check_name and src: both null or both defined
  4133. if check_name is None and src is None:
  4134. check_constraints[(schema, table_name)] = default()
  4135. continue
  4136. # samples:
  4137. # "CHECK (((a > 1) AND (a < 5)))"
  4138. # "CHECK (((a = 1) OR ((a > 2) AND (a < 5))))"
  4139. # "CHECK (((a > 1) AND (a < 5))) NOT VALID"
  4140. # "CHECK (some_boolean_function(a))"
  4141. # "CHECK (((a\n < 1)\n OR\n (a\n >= 5))\n)"
  4142. # "CHECK (a NOT NULL) NO INHERIT"
  4143. # "CHECK (a NOT NULL) NO INHERIT NOT VALID"
  4144. m = re.match(
  4145. r"^CHECK *\((.+)\)( NO INHERIT)?( NOT VALID)?$",
  4146. src,
  4147. flags=re.DOTALL,
  4148. )
  4149. if not m:
  4150. util.warn("Could not parse CHECK constraint text: %r" % src)
  4151. sqltext = ""
  4152. else:
  4153. sqltext = re.compile(
  4154. r"^[\s\n]*\((.+)\)[\s\n]*$", flags=re.DOTALL
  4155. ).sub(r"\1", m.group(1))
  4156. entry = {
  4157. "name": check_name,
  4158. "sqltext": sqltext,
  4159. "comment": comment,
  4160. }
  4161. if m:
  4162. do = {}
  4163. if " NOT VALID" in m.groups():
  4164. do["not_valid"] = True
  4165. if " NO INHERIT" in m.groups():
  4166. do["no_inherit"] = True
  4167. if do:
  4168. entry["dialect_options"] = do
  4169. check_constraints[(schema, table_name)].append(entry)
  4170. return check_constraints.items()
  4171. def _pg_type_filter_schema(self, query, schema):
  4172. if schema is None:
  4173. query = query.where(
  4174. pg_catalog.pg_type_is_visible(pg_catalog.pg_type.c.oid),
  4175. # ignore pg_catalog schema
  4176. pg_catalog.pg_namespace.c.nspname != "pg_catalog",
  4177. )
  4178. elif schema != "*":
  4179. query = query.where(pg_catalog.pg_namespace.c.nspname == schema)
  4180. return query
  4181. @lru_cache()
  4182. def _enum_query(self, schema):
  4183. lbl_agg_sq = (
  4184. select(
  4185. pg_catalog.pg_enum.c.enumtypid,
  4186. sql.func.array_agg(
  4187. aggregate_order_by(
  4188. # NOTE: cast since some postgresql derivatives may
  4189. # not support array_agg on the name type
  4190. pg_catalog.pg_enum.c.enumlabel.cast(TEXT),
  4191. pg_catalog.pg_enum.c.enumsortorder,
  4192. )
  4193. ).label("labels"),
  4194. )
  4195. .group_by(pg_catalog.pg_enum.c.enumtypid)
  4196. .subquery("lbl_agg")
  4197. )
  4198. query = (
  4199. select(
  4200. pg_catalog.pg_type.c.typname.label("name"),
  4201. pg_catalog.pg_type_is_visible(pg_catalog.pg_type.c.oid).label(
  4202. "visible"
  4203. ),
  4204. pg_catalog.pg_namespace.c.nspname.label("schema"),
  4205. lbl_agg_sq.c.labels.label("labels"),
  4206. )
  4207. .join(
  4208. pg_catalog.pg_namespace,
  4209. pg_catalog.pg_namespace.c.oid
  4210. == pg_catalog.pg_type.c.typnamespace,
  4211. )
  4212. .outerjoin(
  4213. lbl_agg_sq, pg_catalog.pg_type.c.oid == lbl_agg_sq.c.enumtypid
  4214. )
  4215. .where(pg_catalog.pg_type.c.typtype == "e")
  4216. .order_by(
  4217. pg_catalog.pg_namespace.c.nspname, pg_catalog.pg_type.c.typname
  4218. )
  4219. )
  4220. return self._pg_type_filter_schema(query, schema)
  4221. @reflection.cache
  4222. def _load_enums(self, connection, schema=None, **kw):
  4223. if not self.supports_native_enum:
  4224. return []
  4225. result = connection.execute(self._enum_query(schema))
  4226. enums = []
  4227. for name, visible, schema, labels in result:
  4228. enums.append(
  4229. {
  4230. "name": name,
  4231. "schema": schema,
  4232. "visible": visible,
  4233. "labels": [] if labels is None else labels,
  4234. }
  4235. )
  4236. return enums
  4237. @lru_cache()
  4238. def _domain_query(self, schema):
  4239. con_sq = (
  4240. select(
  4241. pg_catalog.pg_constraint.c.contypid,
  4242. sql.func.array_agg(
  4243. pg_catalog.pg_get_constraintdef(
  4244. pg_catalog.pg_constraint.c.oid, True
  4245. )
  4246. ).label("condefs"),
  4247. sql.func.array_agg(
  4248. # NOTE: cast since some postgresql derivatives may
  4249. # not support array_agg on the name type
  4250. pg_catalog.pg_constraint.c.conname.cast(TEXT)
  4251. ).label("connames"),
  4252. )
  4253. # The domain this constraint is on; zero if not a domain constraint
  4254. .where(pg_catalog.pg_constraint.c.contypid != 0)
  4255. .group_by(pg_catalog.pg_constraint.c.contypid)
  4256. .subquery("domain_constraints")
  4257. )
  4258. query = (
  4259. select(
  4260. pg_catalog.pg_type.c.typname.label("name"),
  4261. pg_catalog.format_type(
  4262. pg_catalog.pg_type.c.typbasetype,
  4263. pg_catalog.pg_type.c.typtypmod,
  4264. ).label("attype"),
  4265. (~pg_catalog.pg_type.c.typnotnull).label("nullable"),
  4266. pg_catalog.pg_type.c.typdefault.label("default"),
  4267. pg_catalog.pg_type_is_visible(pg_catalog.pg_type.c.oid).label(
  4268. "visible"
  4269. ),
  4270. pg_catalog.pg_namespace.c.nspname.label("schema"),
  4271. con_sq.c.condefs,
  4272. con_sq.c.connames,
  4273. pg_catalog.pg_collation.c.collname,
  4274. )
  4275. .join(
  4276. pg_catalog.pg_namespace,
  4277. pg_catalog.pg_namespace.c.oid
  4278. == pg_catalog.pg_type.c.typnamespace,
  4279. )
  4280. .outerjoin(
  4281. pg_catalog.pg_collation,
  4282. pg_catalog.pg_type.c.typcollation
  4283. == pg_catalog.pg_collation.c.oid,
  4284. )
  4285. .outerjoin(
  4286. con_sq,
  4287. pg_catalog.pg_type.c.oid == con_sq.c.contypid,
  4288. )
  4289. .where(pg_catalog.pg_type.c.typtype == "d")
  4290. .order_by(
  4291. pg_catalog.pg_namespace.c.nspname, pg_catalog.pg_type.c.typname
  4292. )
  4293. )
  4294. return self._pg_type_filter_schema(query, schema)
  4295. @reflection.cache
  4296. def _load_domains(self, connection, schema=None, **kw):
  4297. result = connection.execute(self._domain_query(schema))
  4298. domains: List[ReflectedDomain] = []
  4299. for domain in result.mappings():
  4300. # strip (30) from character varying(30)
  4301. attype = re.search(r"([^\(]+)", domain["attype"]).group(1)
  4302. constraints: List[ReflectedDomainConstraint] = []
  4303. if domain["connames"]:
  4304. # When a domain has multiple CHECK constraints, they will
  4305. # be tested in alphabetical order by name.
  4306. sorted_constraints = sorted(
  4307. zip(domain["connames"], domain["condefs"]),
  4308. key=lambda t: t[0],
  4309. )
  4310. for name, def_ in sorted_constraints:
  4311. # constraint is in the form "CHECK (expression)"
  4312. # or "NOT NULL". Ignore the "NOT NULL" and
  4313. # remove "CHECK (" and the tailing ")".
  4314. if def_.casefold().startswith("check"):
  4315. check = def_[7:-1]
  4316. constraints.append({"name": name, "check": check})
  4317. domain_rec: ReflectedDomain = {
  4318. "name": domain["name"],
  4319. "schema": domain["schema"],
  4320. "visible": domain["visible"],
  4321. "type": attype,
  4322. "nullable": domain["nullable"],
  4323. "default": domain["default"],
  4324. "constraints": constraints,
  4325. "collation": domain["collname"],
  4326. }
  4327. domains.append(domain_rec)
  4328. return domains
  4329. def _set_backslash_escapes(self, connection):
  4330. # this method is provided as an override hook for descendant
  4331. # dialects (e.g. Redshift), so removing it may break them
  4332. std_string = connection.exec_driver_sql(
  4333. "show standard_conforming_strings"
  4334. ).scalar()
  4335. self._backslash_escapes = std_string == "off"