base.py 155 KB

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