base.py 160 KB

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