base.py 109 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000
  1. # postgresql/base.py
  2. # Copyright (C) 2005-2017 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: http://www.opensource.org/licenses/mit-license.php
  7. r"""
  8. .. dialect:: postgresql
  9. :name: PostgreSQL
  10. .. _postgresql_sequences:
  11. Sequences/SERIAL
  12. ----------------
  13. PostgreSQL supports sequences, and SQLAlchemy uses these as the default means
  14. of creating new primary key values for integer-based primary key columns. When
  15. creating tables, SQLAlchemy will issue the ``SERIAL`` datatype for
  16. integer-based primary key columns, which generates a sequence and server side
  17. default corresponding to the column.
  18. To specify a specific named sequence to be used for primary key generation,
  19. use the :func:`~sqlalchemy.schema.Sequence` construct::
  20. Table('sometable', metadata,
  21. Column('id', Integer, Sequence('some_id_seq'), primary_key=True)
  22. )
  23. When SQLAlchemy issues a single INSERT statement, to fulfill the contract of
  24. having the "last insert identifier" available, a RETURNING clause is added to
  25. the INSERT statement which specifies the primary key columns should be
  26. returned after the statement completes. The RETURNING functionality only takes
  27. place if PostgreSQL 8.2 or later is in use. As a fallback approach, the
  28. sequence, whether specified explicitly or implicitly via ``SERIAL``, is
  29. executed independently beforehand, the returned value to be used in the
  30. subsequent insert. Note that when an
  31. :func:`~sqlalchemy.sql.expression.insert()` construct is executed using
  32. "executemany" semantics, the "last inserted identifier" functionality does not
  33. apply; no RETURNING clause is emitted nor is the sequence pre-executed in this
  34. case.
  35. To force the usage of RETURNING by default off, specify the flag
  36. ``implicit_returning=False`` to :func:`.create_engine`.
  37. .. _postgresql_isolation_level:
  38. Transaction Isolation Level
  39. ---------------------------
  40. All PostgreSQL dialects support setting of transaction isolation level
  41. both via a dialect-specific parameter
  42. :paramref:`.create_engine.isolation_level` accepted by :func:`.create_engine`,
  43. as well as the :paramref:`.Connection.execution_options.isolation_level`
  44. argument as passed to :meth:`.Connection.execution_options`.
  45. When using a non-psycopg2 dialect, this feature works by issuing the command
  46. ``SET SESSION CHARACTERISTICS AS TRANSACTION ISOLATION LEVEL <level>`` for
  47. each new connection. For the special AUTOCOMMIT isolation level,
  48. DBAPI-specific techniques are used.
  49. To set isolation level using :func:`.create_engine`::
  50. engine = create_engine(
  51. "postgresql+pg8000://scott:tiger@localhost/test",
  52. isolation_level="READ UNCOMMITTED"
  53. )
  54. To set using per-connection execution options::
  55. connection = engine.connect()
  56. connection = connection.execution_options(
  57. isolation_level="READ COMMITTED"
  58. )
  59. Valid values for ``isolation_level`` include:
  60. * ``READ COMMITTED``
  61. * ``READ UNCOMMITTED``
  62. * ``REPEATABLE READ``
  63. * ``SERIALIZABLE``
  64. * ``AUTOCOMMIT`` - on psycopg2 / pg8000 only
  65. .. seealso::
  66. :ref:`psycopg2_isolation_level`
  67. :ref:`pg8000_isolation_level`
  68. .. _postgresql_schema_reflection:
  69. Remote-Schema Table Introspection and PostgreSQL search_path
  70. ------------------------------------------------------------
  71. The PostgreSQL dialect can reflect tables from any schema. The
  72. :paramref:`.Table.schema` argument, or alternatively the
  73. :paramref:`.MetaData.reflect.schema` argument determines which schema will
  74. be searched for the table or tables. The reflected :class:`.Table` objects
  75. will in all cases retain this ``.schema`` attribute as was specified.
  76. However, with regards to tables which these :class:`.Table` objects refer to
  77. via foreign key constraint, a decision must be made as to how the ``.schema``
  78. is represented in those remote tables, in the case where that remote
  79. schema name is also a member of the current
  80. `PostgreSQL search path
  81. <http://www.postgresql.org/docs/current/static/ddl-schemas.html#DDL-SCHEMAS-PATH>`_.
  82. By default, the PostgreSQL dialect mimics the behavior encouraged by
  83. PostgreSQL's own ``pg_get_constraintdef()`` builtin procedure. This function
  84. returns a sample definition for a particular foreign key constraint,
  85. omitting the referenced schema name from that definition when the name is
  86. also in the PostgreSQL schema search path. The interaction below
  87. illustrates this behavior::
  88. test=> CREATE TABLE test_schema.referred(id INTEGER PRIMARY KEY);
  89. CREATE TABLE
  90. test=> CREATE TABLE referring(
  91. test(> id INTEGER PRIMARY KEY,
  92. test(> referred_id INTEGER REFERENCES test_schema.referred(id));
  93. CREATE TABLE
  94. test=> SET search_path TO public, test_schema;
  95. test=> SELECT pg_catalog.pg_get_constraintdef(r.oid, true) FROM
  96. test-> pg_catalog.pg_class c JOIN pg_catalog.pg_namespace n
  97. test-> ON n.oid = c.relnamespace
  98. test-> JOIN pg_catalog.pg_constraint r ON c.oid = r.conrelid
  99. test-> WHERE c.relname='referring' AND r.contype = 'f'
  100. test-> ;
  101. pg_get_constraintdef
  102. ---------------------------------------------------
  103. FOREIGN KEY (referred_id) REFERENCES referred(id)
  104. (1 row)
  105. Above, we created a table ``referred`` as a member of the remote schema
  106. ``test_schema``, however when we added ``test_schema`` to the
  107. PG ``search_path`` and then asked ``pg_get_constraintdef()`` for the
  108. ``FOREIGN KEY`` syntax, ``test_schema`` was not included in the output of
  109. the function.
  110. On the other hand, if we set the search path back to the typical default
  111. of ``public``::
  112. test=> SET search_path TO public;
  113. SET
  114. The same query against ``pg_get_constraintdef()`` now returns the fully
  115. schema-qualified name for us::
  116. test=> SELECT pg_catalog.pg_get_constraintdef(r.oid, true) FROM
  117. test-> pg_catalog.pg_class c JOIN pg_catalog.pg_namespace n
  118. test-> ON n.oid = c.relnamespace
  119. test-> JOIN pg_catalog.pg_constraint r ON c.oid = r.conrelid
  120. test-> WHERE c.relname='referring' AND r.contype = 'f';
  121. pg_get_constraintdef
  122. ---------------------------------------------------------------
  123. FOREIGN KEY (referred_id) REFERENCES test_schema.referred(id)
  124. (1 row)
  125. SQLAlchemy will by default use the return value of ``pg_get_constraintdef()``
  126. in order to determine the remote schema name. That is, if our ``search_path``
  127. were set to include ``test_schema``, and we invoked a table
  128. reflection process as follows::
  129. >>> from sqlalchemy import Table, MetaData, create_engine
  130. >>> engine = create_engine("postgresql://scott:tiger@localhost/test")
  131. >>> with engine.connect() as conn:
  132. ... conn.execute("SET search_path TO test_schema, public")
  133. ... meta = MetaData()
  134. ... referring = Table('referring', meta,
  135. ... autoload=True, autoload_with=conn)
  136. ...
  137. <sqlalchemy.engine.result.ResultProxy object at 0x101612ed0>
  138. The above process would deliver to the :attr:`.MetaData.tables` collection
  139. ``referred`` table named **without** the schema::
  140. >>> meta.tables['referred'].schema is None
  141. True
  142. To alter the behavior of reflection such that the referred schema is
  143. maintained regardless of the ``search_path`` setting, use the
  144. ``postgresql_ignore_search_path`` option, which can be specified as a
  145. dialect-specific argument to both :class:`.Table` as well as
  146. :meth:`.MetaData.reflect`::
  147. >>> with engine.connect() as conn:
  148. ... conn.execute("SET search_path TO test_schema, public")
  149. ... meta = MetaData()
  150. ... referring = Table('referring', meta, autoload=True,
  151. ... autoload_with=conn,
  152. ... postgresql_ignore_search_path=True)
  153. ...
  154. <sqlalchemy.engine.result.ResultProxy object at 0x1016126d0>
  155. We will now have ``test_schema.referred`` stored as schema-qualified::
  156. >>> meta.tables['test_schema.referred'].schema
  157. 'test_schema'
  158. .. sidebar:: Best Practices for PostgreSQL Schema reflection
  159. The description of PostgreSQL schema reflection behavior is complex, and
  160. is the product of many years of dealing with widely varied use cases and
  161. user preferences. But in fact, there's no need to understand any of it if
  162. you just stick to the simplest use pattern: leave the ``search_path`` set
  163. to its default of ``public`` only, never refer to the name ``public`` as
  164. an explicit schema name otherwise, and refer to all other schema names
  165. explicitly when building up a :class:`.Table` object. The options
  166. described here are only for those users who can't, or prefer not to, stay
  167. within these guidelines.
  168. Note that **in all cases**, the "default" schema is always reflected as
  169. ``None``. The "default" schema on PostgreSQL is that which is returned by the
  170. PostgreSQL ``current_schema()`` function. On a typical PostgreSQL
  171. installation, this is the name ``public``. So a table that refers to another
  172. which is in the ``public`` (i.e. default) schema will always have the
  173. ``.schema`` attribute set to ``None``.
  174. .. versionadded:: 0.9.2 Added the ``postgresql_ignore_search_path``
  175. dialect-level option accepted by :class:`.Table` and
  176. :meth:`.MetaData.reflect`.
  177. .. seealso::
  178. `The Schema Search Path
  179. <http://www.postgresql.org/docs/9.0/static/ddl-schemas.html#DDL-SCHEMAS-PATH>`_
  180. - on the PostgreSQL website.
  181. INSERT/UPDATE...RETURNING
  182. -------------------------
  183. The dialect supports PG 8.2's ``INSERT..RETURNING``, ``UPDATE..RETURNING`` and
  184. ``DELETE..RETURNING`` syntaxes. ``INSERT..RETURNING`` is used by default
  185. for single-row INSERT statements in order to fetch newly generated
  186. primary key identifiers. To specify an explicit ``RETURNING`` clause,
  187. use the :meth:`._UpdateBase.returning` method on a per-statement basis::
  188. # INSERT..RETURNING
  189. result = table.insert().returning(table.c.col1, table.c.col2).\
  190. values(name='foo')
  191. print result.fetchall()
  192. # UPDATE..RETURNING
  193. result = table.update().returning(table.c.col1, table.c.col2).\
  194. where(table.c.name=='foo').values(name='bar')
  195. print result.fetchall()
  196. # DELETE..RETURNING
  197. result = table.delete().returning(table.c.col1, table.c.col2).\
  198. where(table.c.name=='foo')
  199. print result.fetchall()
  200. .. _postgresql_insert_on_conflict:
  201. INSERT...ON CONFLICT (Upsert)
  202. ------------------------------
  203. Starting with version 9.5, PostgreSQL allows "upserts" (update or insert)
  204. of rows into a table via the ``ON CONFLICT`` clause of the ``INSERT`` statement.
  205. A candidate row will only be inserted if that row does not violate
  206. any unique constraints. In the case of a unique constraint violation,
  207. a secondary action can occur which can be either "DO UPDATE", indicating
  208. that the data in the target row should be updated, or "DO NOTHING",
  209. which indicates to silently skip this row.
  210. Conflicts are determined using existing unique constraints and indexes. These
  211. constraints may be identified either using their name as stated in DDL,
  212. or they may be *inferred* by stating the columns and conditions that comprise
  213. the indexes.
  214. SQLAlchemy provides ``ON CONFLICT`` support via the PostgreSQL-specific
  215. :func:`.postgresql.dml.insert()` function, which provides
  216. the generative methods :meth:`~.postgresql.dml.Insert.on_conflict_do_update`
  217. and :meth:`~.postgresql.dml.Insert.on_conflict_do_nothing`::
  218. from sqlalchemy.dialects.postgresql import insert
  219. insert_stmt = insert(my_table).values(
  220. id='some_existing_id',
  221. data='inserted value')
  222. do_nothing_stmt = insert_stmt.on_conflict_do_nothing(
  223. index_elements=['id']
  224. )
  225. conn.execute(do_nothing_stmt)
  226. do_update_stmt = insert_stmt.on_conflict_do_update(
  227. constraint='pk_my_table',
  228. set_=dict(data='updated value')
  229. )
  230. conn.execute(do_update_stmt)
  231. Both methods supply the "target" of the conflict using either the
  232. named constraint or by column inference:
  233. * The :paramref:`.Insert.on_conflict_do_update.index_elements` argument
  234. specifies a sequence containing string column names, :class:`.Column` objects,
  235. and/or SQL expression elements, which would identify a unique index::
  236. do_update_stmt = insert_stmt.on_conflict_do_update(
  237. index_elements=['id'],
  238. set_=dict(data='updated value')
  239. )
  240. do_update_stmt = insert_stmt.on_conflict_do_update(
  241. index_elements=[my_table.c.id],
  242. set_=dict(data='updated value')
  243. )
  244. * When using :paramref:`.Insert.on_conflict_do_update.index_elements` to
  245. infer an index, a partial index can be inferred by also specifying the
  246. use the :paramref:`.Insert.on_conflict_do_update.index_where` parameter::
  247. from sqlalchemy.dialects.postgresql import insert
  248. stmt = insert(my_table).values(user_email='a@b.com', data='inserted data')
  249. stmt = stmt.on_conflict_do_update(
  250. index_elements=[my_table.c.user_email],
  251. index_where=my_table.c.user_email.like('%@gmail.com'),
  252. set_=dict(data=stmt.excluded.data)
  253. )
  254. conn.execute(stmt)
  255. * The :paramref:`.Insert.on_conflict_do_update.constraint` argument is
  256. used to specify an index directly rather than inferring it. This can be
  257. the name of a UNIQUE constraint, a PRIMARY KEY constraint, or an INDEX::
  258. do_update_stmt = insert_stmt.on_conflict_do_update(
  259. constraint='my_table_idx_1',
  260. set_=dict(data='updated value')
  261. )
  262. do_update_stmt = insert_stmt.on_conflict_do_update(
  263. constraint='my_table_pk',
  264. set_=dict(data='updated value')
  265. )
  266. * The :paramref:`.Insert.on_conflict_do_update.constraint` argument may
  267. also refer to a SQLAlchemy construct representing a constraint,
  268. e.g. :class:`.UniqueConstraint`, :class:`.PrimaryKeyConstraint`,
  269. :class:`.Index`, or :class:`.ExcludeConstraint`. In this use,
  270. if the constraint has a name, it is used directly. Otherwise, if the
  271. constraint is unnamed, then inference will be used, where the expressions
  272. and optional WHERE clause of the constraint will be spelled out in the
  273. construct. This use is especially convenient
  274. to refer to the named or unnamed primary key of a :class:`.Table` using the
  275. :attr:`.Table.primary_key` attribute::
  276. do_update_stmt = insert_stmt.on_conflict_do_update(
  277. constraint=my_table.primary_key,
  278. set_=dict(data='updated value')
  279. )
  280. ``ON CONFLICT...DO UPDATE`` is used to perform an update of the already
  281. existing row, using any combination of new values as well as values
  282. from the proposed insertion. These values are specified using the
  283. :paramref:`.Insert.on_conflict_do_update.set_` parameter. This
  284. parameter accepts a dictionary which consists of direct values
  285. for UPDATE::
  286. from sqlalchemy.dialects.postgresql import insert
  287. stmt = insert(my_table).values(id='some_id', data='inserted value')
  288. do_update_stmt = stmt.on_conflict_do_update(
  289. index_elements=['id'],
  290. set_=dict(data='updated value')
  291. )
  292. conn.execute(do_update_stmt)
  293. .. warning::
  294. The :meth:`.Insert.on_conflict_do_update` method does **not** take into
  295. account Python-side default UPDATE values or generation functions, e.g.
  296. e.g. those specified using :paramref:`.Column.onupdate`.
  297. These values will not be exercised for an ON CONFLICT style of UPDATE,
  298. unless they are manually specified in the
  299. :paramref:`.Insert.on_conflict_do_update.set_` dictionary.
  300. In order to refer to the proposed insertion row, the special alias
  301. :attr:`~.postgresql.dml.Insert.excluded` is available as an attribute on
  302. the :class:`.postgresql.dml.Insert` object; this object is a
  303. :class:`.ColumnCollection` which alias contains all columns of the target
  304. table::
  305. from sqlalchemy.dialects.postgresql import insert
  306. stmt = insert(my_table).values(
  307. id='some_id',
  308. data='inserted value',
  309. author='jlh')
  310. do_update_stmt = stmt.on_conflict_do_update(
  311. index_elements=['id'],
  312. set_=dict(data='updated value', author=stmt.excluded.author)
  313. )
  314. conn.execute(do_update_stmt)
  315. The :meth:`.Insert.on_conflict_do_update` method also accepts
  316. a WHERE clause using the :paramref:`.Insert.on_conflict_do_update.where`
  317. parameter, which will limit those rows which receive an UPDATE::
  318. from sqlalchemy.dialects.postgresql import insert
  319. stmt = insert(my_table).values(
  320. id='some_id',
  321. data='inserted value',
  322. author='jlh')
  323. on_update_stmt = stmt.on_conflict_do_update(
  324. index_elements=['id'],
  325. set_=dict(data='updated value', author=stmt.excluded.author)
  326. where=(my_table.c.status == 2)
  327. )
  328. conn.execute(on_update_stmt)
  329. ``ON CONFLICT`` may also be used to skip inserting a row entirely
  330. if any conflict with a unique or exclusion constraint occurs; below
  331. this is illustrated using the
  332. :meth:`~.postgresql.dml.Insert.on_conflict_do_nothing` method::
  333. from sqlalchemy.dialects.postgresql import insert
  334. stmt = insert(my_table).values(id='some_id', data='inserted value')
  335. stmt = stmt.on_conflict_do_nothing(index_elements=['id'])
  336. conn.execute(stmt)
  337. If ``DO NOTHING`` is used without specifying any columns or constraint,
  338. it has the effect of skipping the INSERT for any unique or exclusion
  339. constraint violation which occurs::
  340. from sqlalchemy.dialects.postgresql import insert
  341. stmt = insert(my_table).values(id='some_id', data='inserted value')
  342. stmt = stmt.on_conflict_do_nothing()
  343. conn.execute(stmt)
  344. .. versionadded:: 1.1 Added support for PostgreSQL ON CONFLICT clauses
  345. .. seealso::
  346. `INSERT .. ON CONFLICT <http://www.postgresql.org/docs/current/static/sql-insert.html#SQL-ON-CONFLICT>`_ - in the PostgreSQL documentation.
  347. .. _postgresql_match:
  348. Full Text Search
  349. ----------------
  350. SQLAlchemy makes available the PostgreSQL ``@@`` operator via the
  351. :meth:`.ColumnElement.match` method on any textual column expression.
  352. On a PostgreSQL dialect, an expression like the following::
  353. select([sometable.c.text.match("search string")])
  354. will emit to the database::
  355. SELECT text @@ to_tsquery('search string') FROM table
  356. The PostgreSQL text search functions such as ``to_tsquery()``
  357. and ``to_tsvector()`` are available
  358. explicitly using the standard :data:`.func` construct. For example::
  359. select([
  360. func.to_tsvector('fat cats ate rats').match('cat & rat')
  361. ])
  362. Emits the equivalent of::
  363. SELECT to_tsvector('fat cats ate rats') @@ to_tsquery('cat & rat')
  364. The :class:`.postgresql.TSVECTOR` type can provide for explicit CAST::
  365. from sqlalchemy.dialects.postgresql import TSVECTOR
  366. from sqlalchemy import select, cast
  367. select([cast("some text", TSVECTOR)])
  368. produces a statement equivalent to::
  369. SELECT CAST('some text' AS TSVECTOR) AS anon_1
  370. Full Text Searches in PostgreSQL are influenced by a combination of: the
  371. PostgresSQL setting of ``default_text_search_config``, the ``regconfig`` used
  372. to build the GIN/GiST indexes, and the ``regconfig`` optionally passed in
  373. during a query.
  374. When performing a Full Text Search against a column that has a GIN or
  375. GiST index that is already pre-computed (which is common on full text
  376. searches) one may need to explicitly pass in a particular PostgresSQL
  377. ``regconfig`` value to ensure the query-planner utilizes the index and does
  378. not re-compute the column on demand.
  379. In order to provide for this explicit query planning, or to use different
  380. search strategies, the ``match`` method accepts a ``postgresql_regconfig``
  381. keyword argument::
  382. select([mytable.c.id]).where(
  383. mytable.c.title.match('somestring', postgresql_regconfig='english')
  384. )
  385. Emits the equivalent of::
  386. SELECT mytable.id FROM mytable
  387. WHERE mytable.title @@ to_tsquery('english', 'somestring')
  388. One can also specifically pass in a `'regconfig'` value to the
  389. ``to_tsvector()`` command as the initial argument::
  390. select([mytable.c.id]).where(
  391. func.to_tsvector('english', mytable.c.title )\
  392. .match('somestring', postgresql_regconfig='english')
  393. )
  394. produces a statement equivalent to::
  395. SELECT mytable.id FROM mytable
  396. WHERE to_tsvector('english', mytable.title) @@
  397. to_tsquery('english', 'somestring')
  398. It is recommended that you use the ``EXPLAIN ANALYZE...`` tool from
  399. PostgresSQL to ensure that you are generating queries with SQLAlchemy that
  400. take full advantage of any indexes you may have created for full text search.
  401. FROM ONLY ...
  402. ------------------------
  403. The dialect supports PostgreSQL's ONLY keyword for targeting only a particular
  404. table in an inheritance hierarchy. This can be used to produce the
  405. ``SELECT ... FROM ONLY``, ``UPDATE ONLY ...``, and ``DELETE FROM ONLY ...``
  406. syntaxes. It uses SQLAlchemy's hints mechanism::
  407. # SELECT ... FROM ONLY ...
  408. result = table.select().with_hint(table, 'ONLY', 'postgresql')
  409. print result.fetchall()
  410. # UPDATE ONLY ...
  411. table.update(values=dict(foo='bar')).with_hint('ONLY',
  412. dialect_name='postgresql')
  413. # DELETE FROM ONLY ...
  414. table.delete().with_hint('ONLY', dialect_name='postgresql')
  415. .. _postgresql_indexes:
  416. PostgreSQL-Specific Index Options
  417. ---------------------------------
  418. Several extensions to the :class:`.Index` construct are available, specific
  419. to the PostgreSQL dialect.
  420. .. _postgresql_partial_indexes:
  421. Partial Indexes
  422. ^^^^^^^^^^^^^^^^
  423. Partial indexes add criterion to the index definition so that the index is
  424. applied to a subset of rows. These can be specified on :class:`.Index`
  425. using the ``postgresql_where`` keyword argument::
  426. Index('my_index', my_table.c.id, postgresql_where=my_table.c.value > 10)
  427. Operator Classes
  428. ^^^^^^^^^^^^^^^^^
  429. PostgreSQL allows the specification of an *operator class* for each column of
  430. an index (see
  431. http://www.postgresql.org/docs/8.3/interactive/indexes-opclass.html).
  432. The :class:`.Index` construct allows these to be specified via the
  433. ``postgresql_ops`` keyword argument::
  434. Index(
  435. 'my_index', my_table.c.id, my_table.c.data,
  436. postgresql_ops={
  437. 'data': 'text_pattern_ops',
  438. 'id': 'int4_ops'
  439. })
  440. Note that the keys in the ``postgresql_ops`` dictionary are the "key" name of
  441. the :class:`.Column`, i.e. the name used to access it from the ``.c``
  442. collection of :class:`.Table`, which can be configured to be different than
  443. the actual name of the column as expressed in the database.
  444. If ``postgresql_ops`` is to be used against a complex SQL expression such
  445. as a function call, then to apply to the column it must be given a label
  446. that is identified in the dictionary by name, e.g.::
  447. Index(
  448. 'my_index', my_table.c.id,
  449. func.lower(my_table.c.data).label('data_lower'),
  450. postgresql_ops={
  451. 'data_lower': 'text_pattern_ops',
  452. 'id': 'int4_ops'
  453. })
  454. Index Types
  455. ^^^^^^^^^^^^
  456. PostgreSQL provides several index types: B-Tree, Hash, GiST, and GIN, as well
  457. as the ability for users to create their own (see
  458. http://www.postgresql.org/docs/8.3/static/indexes-types.html). These can be
  459. specified on :class:`.Index` using the ``postgresql_using`` keyword argument::
  460. Index('my_index', my_table.c.data, postgresql_using='gin')
  461. The value passed to the keyword argument will be simply passed through to the
  462. underlying CREATE INDEX command, so it *must* be a valid index type for your
  463. version of PostgreSQL.
  464. .. _postgresql_index_storage:
  465. Index Storage Parameters
  466. ^^^^^^^^^^^^^^^^^^^^^^^^
  467. PostgreSQL allows storage parameters to be set on indexes. The storage
  468. parameters available depend on the index method used by the index. Storage
  469. parameters can be specified on :class:`.Index` using the ``postgresql_with``
  470. keyword argument::
  471. Index('my_index', my_table.c.data, postgresql_with={"fillfactor": 50})
  472. .. versionadded:: 1.0.6
  473. PostgreSQL allows to define the tablespace in which to create the index.
  474. The tablespace can be specified on :class:`.Index` using the
  475. ``postgresql_tablespace`` keyword argument::
  476. Index('my_index', my_table.c.data, postgresql_tablespace='my_tablespace')
  477. .. versionadded:: 1.1
  478. Note that the same option is available on :class:`.Table` as well.
  479. .. _postgresql_index_concurrently:
  480. Indexes with CONCURRENTLY
  481. ^^^^^^^^^^^^^^^^^^^^^^^^^
  482. The PostgreSQL index option CONCURRENTLY is supported by passing the
  483. flag ``postgresql_concurrently`` to the :class:`.Index` construct::
  484. tbl = Table('testtbl', m, Column('data', Integer))
  485. idx1 = Index('test_idx1', tbl.c.data, postgresql_concurrently=True)
  486. The above index construct will render DDL for CREATE INDEX, assuming
  487. PostgreSQL 8.2 or higher is detected or for a connection-less dialect, as::
  488. CREATE INDEX CONCURRENTLY test_idx1 ON testtbl (data)
  489. For DROP INDEX, assuming PostgreSQL 9.2 or higher is detected or for
  490. a connection-less dialect, it will emit::
  491. DROP INDEX CONCURRENTLY test_idx1
  492. .. versionadded:: 1.1 support for CONCURRENTLY on DROP INDEX. The
  493. CONCURRENTLY keyword is now only emitted if a high enough version
  494. of PostgreSQL is detected on the connection (or for a connection-less
  495. dialect).
  496. When using CONCURRENTLY, the Postgresql database requires that the statement
  497. be invoked outside of a transaction block. The Python DBAPI enforces that
  498. even for a single statement, a transaction is present, so to use this
  499. construct, the DBAPI's "autocommit" mode must be used::
  500. metadata = MetaData()
  501. table = Table(
  502. "foo", metadata,
  503. Column("id", String))
  504. index = Index(
  505. "foo_idx", table.c.id, postgresql_concurrently=True)
  506. with engine.connect() as conn:
  507. with conn.execution_options(isolation_level='AUTOCOMMIT'):
  508. table.create(conn)
  509. .. seealso::
  510. :ref:`postgresql_isolation_level`
  511. .. _postgresql_index_reflection:
  512. PostgreSQL Index Reflection
  513. ---------------------------
  514. The PostgreSQL database creates a UNIQUE INDEX implicitly whenever the
  515. UNIQUE CONSTRAINT construct is used. When inspecting a table using
  516. :class:`.Inspector`, the :meth:`.Inspector.get_indexes`
  517. and the :meth:`.Inspector.get_unique_constraints` will report on these
  518. two constructs distinctly; in the case of the index, the key
  519. ``duplicates_constraint`` will be present in the index entry if it is
  520. detected as mirroring a constraint. When performing reflection using
  521. ``Table(..., autoload=True)``, the UNIQUE INDEX is **not** returned
  522. in :attr:`.Table.indexes` when it is detected as mirroring a
  523. :class:`.UniqueConstraint` in the :attr:`.Table.constraints` collection.
  524. .. versionchanged:: 1.0.0 - :class:`.Table` reflection now includes
  525. :class:`.UniqueConstraint` objects present in the :attr:`.Table.constraints`
  526. collection; the PostgreSQL backend will no longer include a "mirrored"
  527. :class:`.Index` construct in :attr:`.Table.indexes` if it is detected
  528. as corresponding to a unique constraint.
  529. Special Reflection Options
  530. --------------------------
  531. The :class:`.Inspector` used for the PostgreSQL backend is an instance
  532. of :class:`.PGInspector`, which offers additional methods::
  533. from sqlalchemy import create_engine, inspect
  534. engine = create_engine("postgresql+psycopg2://localhost/test")
  535. insp = inspect(engine) # will be a PGInspector
  536. print(insp.get_enums())
  537. .. autoclass:: PGInspector
  538. :members:
  539. .. _postgresql_table_options:
  540. PostgreSQL Table Options
  541. -------------------------
  542. Several options for CREATE TABLE are supported directly by the PostgreSQL
  543. dialect in conjunction with the :class:`.Table` construct:
  544. * ``TABLESPACE``::
  545. Table("some_table", metadata, ..., postgresql_tablespace='some_tablespace')
  546. The above option is also available on the :class:`.Index` construct.
  547. * ``ON COMMIT``::
  548. Table("some_table", metadata, ..., postgresql_on_commit='PRESERVE ROWS')
  549. * ``WITH OIDS``::
  550. Table("some_table", metadata, ..., postgresql_with_oids=True)
  551. * ``WITHOUT OIDS``::
  552. Table("some_table", metadata, ..., postgresql_with_oids=False)
  553. * ``INHERITS``::
  554. Table("some_table", metadata, ..., postgresql_inherits="some_supertable")
  555. Table("some_table", metadata, ..., postgresql_inherits=("t1", "t2", ...))
  556. .. versionadded:: 1.0.0
  557. .. seealso::
  558. `PostgreSQL CREATE TABLE options
  559. <http://www.postgresql.org/docs/current/static/sql-createtable.html>`_
  560. ARRAY Types
  561. -----------
  562. The PostgreSQL dialect supports arrays, both as multidimensional column types
  563. as well as array literals:
  564. * :class:`.postgresql.ARRAY` - ARRAY datatype
  565. * :class:`.postgresql.array` - array literal
  566. * :func:`.postgresql.array_agg` - ARRAY_AGG SQL function
  567. * :class:`.postgresql.aggregate_order_by` - helper for PG's ORDER BY aggregate
  568. function syntax.
  569. JSON Types
  570. ----------
  571. The PostgreSQL dialect supports both JSON and JSONB datatypes, including
  572. psycopg2's native support and support for all of PostgreSQL's special
  573. operators:
  574. * :class:`.postgresql.JSON`
  575. * :class:`.postgresql.JSONB`
  576. HSTORE Type
  577. -----------
  578. The PostgreSQL HSTORE type as well as hstore literals are supported:
  579. * :class:`.postgresql.HSTORE` - HSTORE datatype
  580. * :class:`.postgresql.hstore` - hstore literal
  581. ENUM Types
  582. ----------
  583. PostgreSQL has an independently creatable TYPE structure which is used
  584. to implement an enumerated type. This approach introduces significant
  585. complexity on the SQLAlchemy side in terms of when this type should be
  586. CREATED and DROPPED. The type object is also an independently reflectable
  587. entity. The following sections should be consulted:
  588. * :class:`.postgresql.ENUM` - DDL and typing support for ENUM.
  589. * :meth:`.PGInspector.get_enums` - retrieve a listing of current ENUM types
  590. * :meth:`.postgresql.ENUM.create` , :meth:`.postgresql.ENUM.drop` - individual
  591. CREATE and DROP commands for ENUM.
  592. .. _postgresql_array_of_enum:
  593. Using ENUM with ARRAY
  594. ^^^^^^^^^^^^^^^^^^^^^
  595. The combination of ENUM and ARRAY is not directly supported by backend
  596. DBAPIs at this time. In order to send and receive an ARRAY of ENUM,
  597. use the following workaround type::
  598. class ArrayOfEnum(ARRAY):
  599. def bind_expression(self, bindvalue):
  600. return sa.cast(bindvalue, self)
  601. def result_processor(self, dialect, coltype):
  602. super_rp = super(ArrayOfEnum, self).result_processor(
  603. dialect, coltype)
  604. def handle_raw_string(value):
  605. inner = re.match(r"^{(.*)}$", value).group(1)
  606. return inner.split(",") if inner else []
  607. def process(value):
  608. if value is None:
  609. return None
  610. return super_rp(handle_raw_string(value))
  611. return process
  612. E.g.::
  613. Table(
  614. 'mydata', metadata,
  615. Column('id', Integer, primary_key=True),
  616. Column('data', ArrayOfEnum(ENUM('a', 'b, 'c', name='myenum')))
  617. )
  618. This type is not included as a built-in type as it would be incompatible
  619. with a DBAPI that suddenly decides to support ARRAY of ENUM directly in
  620. a new version.
  621. .. _postgresql_array_of_json:
  622. Using JSON/JSONB with ARRAY
  623. ^^^^^^^^^^^^^^^^^^^^^^^^^^^
  624. Similar to using ENUM, for an ARRAY of JSON/JSONB we need to render the
  625. appropriate CAST, however current psycopg2 drivers seem to handle the result
  626. for ARRAY of JSON automatically, so the type is simpler::
  627. class CastingArray(ARRAY):
  628. def bind_expression(self, bindvalue):
  629. return sa.cast(bindvalue, self)
  630. E.g.::
  631. Table(
  632. 'mydata', metadata,
  633. Column('id', Integer, primary_key=True),
  634. Column('data', CastingArray(JSONB))
  635. )
  636. """
  637. from collections import defaultdict
  638. import re
  639. import datetime as dt
  640. from sqlalchemy.sql import elements
  641. from ... import sql, schema, exc, util
  642. from ...engine import default, reflection
  643. from ...sql import compiler, expression
  644. from ... import types as sqltypes
  645. try:
  646. from uuid import UUID as _python_UUID
  647. except ImportError:
  648. _python_UUID = None
  649. from sqlalchemy.types import INTEGER, BIGINT, SMALLINT, VARCHAR, \
  650. CHAR, TEXT, FLOAT, NUMERIC, \
  651. DATE, BOOLEAN, REAL
  652. AUTOCOMMIT_REGEXP = re.compile(
  653. r'\s*(?:UPDATE|INSERT|CREATE|DELETE|DROP|ALTER|GRANT|REVOKE|'
  654. 'IMPORT FOREIGN SCHEMA|REFRESH MATERIALIZED VIEW)',
  655. re.I | re.UNICODE)
  656. RESERVED_WORDS = set(
  657. ["all", "analyse", "analyze", "and", "any", "array", "as", "asc",
  658. "asymmetric", "both", "case", "cast", "check", "collate", "column",
  659. "constraint", "create", "current_catalog", "current_date",
  660. "current_role", "current_time", "current_timestamp", "current_user",
  661. "default", "deferrable", "desc", "distinct", "do", "else", "end",
  662. "except", "false", "fetch", "for", "foreign", "from", "grant", "group",
  663. "having", "in", "initially", "intersect", "into", "leading", "limit",
  664. "localtime", "localtimestamp", "new", "not", "null", "of", "off",
  665. "offset", "old", "on", "only", "or", "order", "placing", "primary",
  666. "references", "returning", "select", "session_user", "some", "symmetric",
  667. "table", "then", "to", "trailing", "true", "union", "unique", "user",
  668. "using", "variadic", "when", "where", "window", "with", "authorization",
  669. "between", "binary", "cross", "current_schema", "freeze", "full",
  670. "ilike", "inner", "is", "isnull", "join", "left", "like", "natural",
  671. "notnull", "outer", "over", "overlaps", "right", "similar", "verbose"
  672. ])
  673. _DECIMAL_TYPES = (1231, 1700)
  674. _FLOAT_TYPES = (700, 701, 1021, 1022)
  675. _INT_TYPES = (20, 21, 23, 26, 1005, 1007, 1016)
  676. class BYTEA(sqltypes.LargeBinary):
  677. __visit_name__ = 'BYTEA'
  678. class DOUBLE_PRECISION(sqltypes.Float):
  679. __visit_name__ = 'DOUBLE_PRECISION'
  680. class INET(sqltypes.TypeEngine):
  681. __visit_name__ = "INET"
  682. PGInet = INET
  683. class CIDR(sqltypes.TypeEngine):
  684. __visit_name__ = "CIDR"
  685. PGCidr = CIDR
  686. class MACADDR(sqltypes.TypeEngine):
  687. __visit_name__ = "MACADDR"
  688. PGMacAddr = MACADDR
  689. class OID(sqltypes.TypeEngine):
  690. """Provide the PostgreSQL OID type.
  691. .. versionadded:: 0.9.5
  692. """
  693. __visit_name__ = "OID"
  694. class TIMESTAMP(sqltypes.TIMESTAMP):
  695. def __init__(self, timezone=False, precision=None):
  696. super(TIMESTAMP, self).__init__(timezone=timezone)
  697. self.precision = precision
  698. class TIME(sqltypes.TIME):
  699. def __init__(self, timezone=False, precision=None):
  700. super(TIME, self).__init__(timezone=timezone)
  701. self.precision = precision
  702. class INTERVAL(sqltypes.TypeEngine):
  703. """PostgreSQL INTERVAL type.
  704. The INTERVAL type may not be supported on all DBAPIs.
  705. It is known to work on psycopg2 and not pg8000 or zxjdbc.
  706. """
  707. __visit_name__ = 'INTERVAL'
  708. def __init__(self, precision=None):
  709. self.precision = precision
  710. @classmethod
  711. def _adapt_from_generic_interval(cls, interval):
  712. return INTERVAL(precision=interval.second_precision)
  713. @property
  714. def _type_affinity(self):
  715. return sqltypes.Interval
  716. @property
  717. def python_type(self):
  718. return dt.timedelta
  719. PGInterval = INTERVAL
  720. class BIT(sqltypes.TypeEngine):
  721. __visit_name__ = 'BIT'
  722. def __init__(self, length=None, varying=False):
  723. if not varying:
  724. # BIT without VARYING defaults to length 1
  725. self.length = length or 1
  726. else:
  727. # but BIT VARYING can be unlimited-length, so no default
  728. self.length = length
  729. self.varying = varying
  730. PGBit = BIT
  731. class UUID(sqltypes.TypeEngine):
  732. """PostgreSQL UUID type.
  733. Represents the UUID column type, interpreting
  734. data either as natively returned by the DBAPI
  735. or as Python uuid objects.
  736. The UUID type may not be supported on all DBAPIs.
  737. It is known to work on psycopg2 and not pg8000.
  738. """
  739. __visit_name__ = 'UUID'
  740. def __init__(self, as_uuid=False):
  741. """Construct a UUID type.
  742. :param as_uuid=False: if True, values will be interpreted
  743. as Python uuid objects, converting to/from string via the
  744. DBAPI.
  745. """
  746. if as_uuid and _python_UUID is None:
  747. raise NotImplementedError(
  748. "This version of Python does not support "
  749. "the native UUID type."
  750. )
  751. self.as_uuid = as_uuid
  752. def bind_processor(self, dialect):
  753. if self.as_uuid:
  754. def process(value):
  755. if value is not None:
  756. value = util.text_type(value)
  757. return value
  758. return process
  759. else:
  760. return None
  761. def result_processor(self, dialect, coltype):
  762. if self.as_uuid:
  763. def process(value):
  764. if value is not None:
  765. value = _python_UUID(value)
  766. return value
  767. return process
  768. else:
  769. return None
  770. PGUuid = UUID
  771. class TSVECTOR(sqltypes.TypeEngine):
  772. """The :class:`.postgresql.TSVECTOR` type implements the PostgreSQL
  773. text search type TSVECTOR.
  774. It can be used to do full text queries on natural language
  775. documents.
  776. .. versionadded:: 0.9.0
  777. .. seealso::
  778. :ref:`postgresql_match`
  779. """
  780. __visit_name__ = 'TSVECTOR'
  781. class ENUM(sqltypes.Enum):
  782. """PostgreSQL ENUM type.
  783. This is a subclass of :class:`.types.Enum` which includes
  784. support for PG's ``CREATE TYPE`` and ``DROP TYPE``.
  785. When the builtin type :class:`.types.Enum` is used and the
  786. :paramref:`.Enum.native_enum` flag is left at its default of
  787. True, the PostgreSQL backend will use a :class:`.postgresql.ENUM`
  788. type as the implementation, so the special create/drop rules
  789. will be used.
  790. The create/drop behavior of ENUM is necessarily intricate, due to the
  791. awkward relationship the ENUM type has in relationship to the
  792. parent table, in that it may be "owned" by just a single table, or
  793. may be shared among many tables.
  794. When using :class:`.types.Enum` or :class:`.postgresql.ENUM`
  795. in an "inline" fashion, the ``CREATE TYPE`` and ``DROP TYPE`` is emitted
  796. corresponding to when the :meth:`.Table.create` and :meth:`.Table.drop`
  797. methods are called::
  798. table = Table('sometable', metadata,
  799. Column('some_enum', ENUM('a', 'b', 'c', name='myenum'))
  800. )
  801. table.create(engine) # will emit CREATE ENUM and CREATE TABLE
  802. table.drop(engine) # will emit DROP TABLE and DROP ENUM
  803. To use a common enumerated type between multiple tables, the best
  804. practice is to declare the :class:`.types.Enum` or
  805. :class:`.postgresql.ENUM` independently, and associate it with the
  806. :class:`.MetaData` object itself::
  807. my_enum = ENUM('a', 'b', 'c', name='myenum', metadata=metadata)
  808. t1 = Table('sometable_one', metadata,
  809. Column('some_enum', myenum)
  810. )
  811. t2 = Table('sometable_two', metadata,
  812. Column('some_enum', myenum)
  813. )
  814. When this pattern is used, care must still be taken at the level
  815. of individual table creates. Emitting CREATE TABLE without also
  816. specifying ``checkfirst=True`` will still cause issues::
  817. t1.create(engine) # will fail: no such type 'myenum'
  818. If we specify ``checkfirst=True``, the individual table-level create
  819. operation will check for the ``ENUM`` and create if not exists::
  820. # will check if enum exists, and emit CREATE TYPE if not
  821. t1.create(engine, checkfirst=True)
  822. When using a metadata-level ENUM type, the type will always be created
  823. and dropped if either the metadata-wide create/drop is called::
  824. metadata.create_all(engine) # will emit CREATE TYPE
  825. metadata.drop_all(engine) # will emit DROP TYPE
  826. The type can also be created and dropped directly::
  827. my_enum.create(engine)
  828. my_enum.drop(engine)
  829. .. versionchanged:: 1.0.0 The PostgreSQL :class:`.postgresql.ENUM` type
  830. now behaves more strictly with regards to CREATE/DROP. A metadata-level
  831. ENUM type will only be created and dropped at the metadata level,
  832. not the table level, with the exception of
  833. ``table.create(checkfirst=True)``.
  834. The ``table.drop()`` call will now emit a DROP TYPE for a table-level
  835. enumerated type.
  836. """
  837. def __init__(self, *enums, **kw):
  838. """Construct an :class:`~.postgresql.ENUM`.
  839. Arguments are the same as that of
  840. :class:`.types.Enum`, but also including
  841. the following parameters.
  842. :param create_type: Defaults to True.
  843. Indicates that ``CREATE TYPE`` should be
  844. emitted, after optionally checking for the
  845. presence of the type, when the parent
  846. table is being created; and additionally
  847. that ``DROP TYPE`` is called when the table
  848. is dropped. When ``False``, no check
  849. will be performed and no ``CREATE TYPE``
  850. or ``DROP TYPE`` is emitted, unless
  851. :meth:`~.postgresql.ENUM.create`
  852. or :meth:`~.postgresql.ENUM.drop`
  853. are called directly.
  854. Setting to ``False`` is helpful
  855. when invoking a creation scheme to a SQL file
  856. without access to the actual database -
  857. the :meth:`~.postgresql.ENUM.create` and
  858. :meth:`~.postgresql.ENUM.drop` methods can
  859. be used to emit SQL to a target bind.
  860. .. versionadded:: 0.7.4
  861. """
  862. self.create_type = kw.pop("create_type", True)
  863. super(ENUM, self).__init__(*enums, **kw)
  864. def create(self, bind=None, checkfirst=True):
  865. """Emit ``CREATE TYPE`` for this
  866. :class:`~.postgresql.ENUM`.
  867. If the underlying dialect does not support
  868. PostgreSQL CREATE TYPE, no action is taken.
  869. :param bind: a connectable :class:`.Engine`,
  870. :class:`.Connection`, or similar object to emit
  871. SQL.
  872. :param checkfirst: if ``True``, a query against
  873. the PG catalog will be first performed to see
  874. if the type does not exist already before
  875. creating.
  876. """
  877. if not bind.dialect.supports_native_enum:
  878. return
  879. if not checkfirst or \
  880. not bind.dialect.has_type(
  881. bind, self.name, schema=self.schema):
  882. bind.execute(CreateEnumType(self))
  883. def drop(self, bind=None, checkfirst=True):
  884. """Emit ``DROP TYPE`` for this
  885. :class:`~.postgresql.ENUM`.
  886. If the underlying dialect does not support
  887. PostgreSQL DROP TYPE, no action is taken.
  888. :param bind: a connectable :class:`.Engine`,
  889. :class:`.Connection`, or similar object to emit
  890. SQL.
  891. :param checkfirst: if ``True``, a query against
  892. the PG catalog will be first performed to see
  893. if the type actually exists before dropping.
  894. """
  895. if not bind.dialect.supports_native_enum:
  896. return
  897. if not checkfirst or \
  898. bind.dialect.has_type(bind, self.name, schema=self.schema):
  899. bind.execute(DropEnumType(self))
  900. def _check_for_name_in_memos(self, checkfirst, kw):
  901. """Look in the 'ddl runner' for 'memos', then
  902. note our name in that collection.
  903. This to ensure a particular named enum is operated
  904. upon only once within any kind of create/drop
  905. sequence without relying upon "checkfirst".
  906. """
  907. if not self.create_type:
  908. return True
  909. if '_ddl_runner' in kw:
  910. ddl_runner = kw['_ddl_runner']
  911. if '_pg_enums' in ddl_runner.memo:
  912. pg_enums = ddl_runner.memo['_pg_enums']
  913. else:
  914. pg_enums = ddl_runner.memo['_pg_enums'] = set()
  915. present = self.name in pg_enums
  916. pg_enums.add(self.name)
  917. return present
  918. else:
  919. return False
  920. def _on_table_create(self, target, bind, checkfirst=False, **kw):
  921. if checkfirst or (
  922. not self.metadata and
  923. not kw.get('_is_metadata_operation', False)) and \
  924. not self._check_for_name_in_memos(checkfirst, kw):
  925. self.create(bind=bind, checkfirst=checkfirst)
  926. def _on_table_drop(self, target, bind, checkfirst=False, **kw):
  927. if not self.metadata and \
  928. not kw.get('_is_metadata_operation', False) and \
  929. not self._check_for_name_in_memos(checkfirst, kw):
  930. self.drop(bind=bind, checkfirst=checkfirst)
  931. def _on_metadata_create(self, target, bind, checkfirst=False, **kw):
  932. if not self._check_for_name_in_memos(checkfirst, kw):
  933. self.create(bind=bind, checkfirst=checkfirst)
  934. def _on_metadata_drop(self, target, bind, checkfirst=False, **kw):
  935. if not self._check_for_name_in_memos(checkfirst, kw):
  936. self.drop(bind=bind, checkfirst=checkfirst)
  937. colspecs = {
  938. sqltypes.Interval: INTERVAL,
  939. sqltypes.Enum: ENUM,
  940. }
  941. ischema_names = {
  942. 'integer': INTEGER,
  943. 'bigint': BIGINT,
  944. 'smallint': SMALLINT,
  945. 'character varying': VARCHAR,
  946. 'character': CHAR,
  947. '"char"': sqltypes.String,
  948. 'name': sqltypes.String,
  949. 'text': TEXT,
  950. 'numeric': NUMERIC,
  951. 'float': FLOAT,
  952. 'real': REAL,
  953. 'inet': INET,
  954. 'cidr': CIDR,
  955. 'uuid': UUID,
  956. 'bit': BIT,
  957. 'bit varying': BIT,
  958. 'macaddr': MACADDR,
  959. 'oid': OID,
  960. 'double precision': DOUBLE_PRECISION,
  961. 'timestamp': TIMESTAMP,
  962. 'timestamp with time zone': TIMESTAMP,
  963. 'timestamp without time zone': TIMESTAMP,
  964. 'time with time zone': TIME,
  965. 'time without time zone': TIME,
  966. 'date': DATE,
  967. 'time': TIME,
  968. 'bytea': BYTEA,
  969. 'boolean': BOOLEAN,
  970. 'interval': INTERVAL,
  971. 'interval year to month': INTERVAL,
  972. 'interval day to second': INTERVAL,
  973. 'tsvector': TSVECTOR
  974. }
  975. class PGCompiler(compiler.SQLCompiler):
  976. def visit_array(self, element, **kw):
  977. return "ARRAY[%s]" % self.visit_clauselist(element, **kw)
  978. def visit_slice(self, element, **kw):
  979. return "%s:%s" % (
  980. self.process(element.start, **kw),
  981. self.process(element.stop, **kw),
  982. )
  983. def visit_json_getitem_op_binary(self, binary, operator, **kw):
  984. kw['eager_grouping'] = True
  985. return self._generate_generic_binary(
  986. binary, " -> ", **kw
  987. )
  988. def visit_json_path_getitem_op_binary(self, binary, operator, **kw):
  989. kw['eager_grouping'] = True
  990. return self._generate_generic_binary(
  991. binary, " #> ", **kw
  992. )
  993. def visit_getitem_binary(self, binary, operator, **kw):
  994. return "%s[%s]" % (
  995. self.process(binary.left, **kw),
  996. self.process(binary.right, **kw)
  997. )
  998. def visit_aggregate_order_by(self, element, **kw):
  999. return "%s ORDER BY %s" % (
  1000. self.process(element.target, **kw),
  1001. self.process(element.order_by, **kw)
  1002. )
  1003. def visit_match_op_binary(self, binary, operator, **kw):
  1004. if "postgresql_regconfig" in binary.modifiers:
  1005. regconfig = self.render_literal_value(
  1006. binary.modifiers['postgresql_regconfig'],
  1007. sqltypes.STRINGTYPE)
  1008. if regconfig:
  1009. return "%s @@ to_tsquery(%s, %s)" % (
  1010. self.process(binary.left, **kw),
  1011. regconfig,
  1012. self.process(binary.right, **kw)
  1013. )
  1014. return "%s @@ to_tsquery(%s)" % (
  1015. self.process(binary.left, **kw),
  1016. self.process(binary.right, **kw)
  1017. )
  1018. def visit_ilike_op_binary(self, binary, operator, **kw):
  1019. escape = binary.modifiers.get("escape", None)
  1020. return '%s ILIKE %s' % \
  1021. (self.process(binary.left, **kw),
  1022. self.process(binary.right, **kw)) \
  1023. + (
  1024. ' ESCAPE ' +
  1025. self.render_literal_value(escape, sqltypes.STRINGTYPE)
  1026. if escape else ''
  1027. )
  1028. def visit_notilike_op_binary(self, binary, operator, **kw):
  1029. escape = binary.modifiers.get("escape", None)
  1030. return '%s NOT ILIKE %s' % \
  1031. (self.process(binary.left, **kw),
  1032. self.process(binary.right, **kw)) \
  1033. + (
  1034. ' ESCAPE ' +
  1035. self.render_literal_value(escape, sqltypes.STRINGTYPE)
  1036. if escape else ''
  1037. )
  1038. def render_literal_value(self, value, type_):
  1039. value = super(PGCompiler, self).render_literal_value(value, type_)
  1040. if self.dialect._backslash_escapes:
  1041. value = value.replace('\\', '\\\\')
  1042. return value
  1043. def visit_sequence(self, seq):
  1044. return "nextval('%s')" % self.preparer.format_sequence(seq)
  1045. def limit_clause(self, select, **kw):
  1046. text = ""
  1047. if select._limit_clause is not None:
  1048. text += " \n LIMIT " + self.process(select._limit_clause, **kw)
  1049. if select._offset_clause is not None:
  1050. if select._limit_clause is None:
  1051. text += " \n LIMIT ALL"
  1052. text += " OFFSET " + self.process(select._offset_clause, **kw)
  1053. return text
  1054. def format_from_hint_text(self, sqltext, table, hint, iscrud):
  1055. if hint.upper() != 'ONLY':
  1056. raise exc.CompileError("Unrecognized hint: %r" % hint)
  1057. return "ONLY " + sqltext
  1058. def get_select_precolumns(self, select, **kw):
  1059. if select._distinct is not False:
  1060. if select._distinct is True:
  1061. return "DISTINCT "
  1062. elif isinstance(select._distinct, (list, tuple)):
  1063. return "DISTINCT ON (" + ', '.join(
  1064. [self.process(col) for col in select._distinct]
  1065. ) + ") "
  1066. else:
  1067. return "DISTINCT ON (" + \
  1068. self.process(select._distinct, **kw) + ") "
  1069. else:
  1070. return ""
  1071. def for_update_clause(self, select, **kw):
  1072. if select._for_update_arg.read:
  1073. if select._for_update_arg.key_share:
  1074. tmp = " FOR KEY SHARE"
  1075. else:
  1076. tmp = " FOR SHARE"
  1077. elif select._for_update_arg.key_share:
  1078. tmp = " FOR NO KEY UPDATE"
  1079. else:
  1080. tmp = " FOR UPDATE"
  1081. if select._for_update_arg.of:
  1082. tables = util.OrderedSet(
  1083. c.table if isinstance(c, expression.ColumnClause)
  1084. else c for c in select._for_update_arg.of)
  1085. tmp += " OF " + ", ".join(
  1086. self.process(table, ashint=True, use_schema=False, **kw)
  1087. for table in tables
  1088. )
  1089. if select._for_update_arg.nowait:
  1090. tmp += " NOWAIT"
  1091. if select._for_update_arg.skip_locked:
  1092. tmp += " SKIP LOCKED"
  1093. return tmp
  1094. def returning_clause(self, stmt, returning_cols):
  1095. columns = [
  1096. self._label_select_column(None, c, True, False, {})
  1097. for c in expression._select_iterables(returning_cols)
  1098. ]
  1099. return 'RETURNING ' + ', '.join(columns)
  1100. def visit_substring_func(self, func, **kw):
  1101. s = self.process(func.clauses.clauses[0], **kw)
  1102. start = self.process(func.clauses.clauses[1], **kw)
  1103. if len(func.clauses.clauses) > 2:
  1104. length = self.process(func.clauses.clauses[2], **kw)
  1105. return "SUBSTRING(%s FROM %s FOR %s)" % (s, start, length)
  1106. else:
  1107. return "SUBSTRING(%s FROM %s)" % (s, start)
  1108. def _on_conflict_target(self, clause, **kw):
  1109. if clause.constraint_target is not None:
  1110. target_text = 'ON CONSTRAINT %s' % clause.constraint_target
  1111. elif clause.inferred_target_elements is not None:
  1112. target_text = '(%s)' % ', '.join(
  1113. (self.preparer.quote(c)
  1114. if isinstance(c, util.string_types)
  1115. else
  1116. self.process(c, include_table=False, use_schema=False))
  1117. for c in clause.inferred_target_elements
  1118. )
  1119. if clause.inferred_target_whereclause is not None:
  1120. target_text += ' WHERE %s' % \
  1121. self.process(
  1122. clause.inferred_target_whereclause,
  1123. include_table=False,
  1124. use_schema=False
  1125. )
  1126. else:
  1127. target_text = ''
  1128. return target_text
  1129. def visit_on_conflict_do_nothing(self, on_conflict, **kw):
  1130. target_text = self._on_conflict_target(on_conflict, **kw)
  1131. if target_text:
  1132. return "ON CONFLICT %s DO NOTHING" % target_text
  1133. else:
  1134. return "ON CONFLICT DO NOTHING"
  1135. def visit_on_conflict_do_update(self, on_conflict, **kw):
  1136. clause = on_conflict
  1137. target_text = self._on_conflict_target(on_conflict, **kw)
  1138. action_set_ops = []
  1139. set_parameters = dict(clause.update_values_to_set)
  1140. # create a list of column assignment clauses as tuples
  1141. cols = self.statement.table.c
  1142. for c in cols:
  1143. col_key = c.key
  1144. if col_key in set_parameters:
  1145. value = set_parameters.pop(col_key)
  1146. if elements._is_literal(value):
  1147. value = elements.BindParameter(
  1148. None, value, type_=c.type
  1149. )
  1150. else:
  1151. if isinstance(value, elements.BindParameter) and \
  1152. value.type._isnull:
  1153. value = value._clone()
  1154. value.type = c.type
  1155. value_text = self.process(value.self_group(), use_schema=False)
  1156. key_text = (
  1157. self.preparer.quote(col_key)
  1158. )
  1159. action_set_ops.append('%s = %s' % (key_text, value_text))
  1160. # check for names that don't match columns
  1161. if set_parameters:
  1162. util.warn(
  1163. "Additional column names not matching "
  1164. "any column keys in table '%s': %s" % (
  1165. self.statement.table.name,
  1166. (", ".join("'%s'" % c for c in set_parameters))
  1167. )
  1168. )
  1169. for k, v in set_parameters.items():
  1170. key_text = (
  1171. self.preparer.quote(k)
  1172. if isinstance(k, util.string_types)
  1173. else self.process(k, use_schema=False)
  1174. )
  1175. value_text = self.process(
  1176. elements._literal_as_binds(v),
  1177. use_schema=False
  1178. )
  1179. action_set_ops.append('%s = %s' % (key_text, value_text))
  1180. action_text = ', '.join(action_set_ops)
  1181. if clause.update_whereclause is not None:
  1182. action_text += ' WHERE %s' % \
  1183. self.process(
  1184. clause.update_whereclause,
  1185. include_table=True,
  1186. use_schema=False
  1187. )
  1188. return 'ON CONFLICT %s DO UPDATE SET %s' % (target_text, action_text)
  1189. class PGDDLCompiler(compiler.DDLCompiler):
  1190. def get_column_specification(self, column, **kwargs):
  1191. colspec = self.preparer.format_column(column)
  1192. impl_type = column.type.dialect_impl(self.dialect)
  1193. if isinstance(impl_type, sqltypes.TypeDecorator):
  1194. impl_type = impl_type.impl
  1195. if column.primary_key and \
  1196. column is column.table._autoincrement_column and \
  1197. (
  1198. self.dialect.supports_smallserial or
  1199. not isinstance(impl_type, sqltypes.SmallInteger)
  1200. ) and (
  1201. column.default is None or
  1202. (
  1203. isinstance(column.default, schema.Sequence) and
  1204. column.default.optional
  1205. )):
  1206. if isinstance(impl_type, sqltypes.BigInteger):
  1207. colspec += " BIGSERIAL"
  1208. elif isinstance(impl_type, sqltypes.SmallInteger):
  1209. colspec += " SMALLSERIAL"
  1210. else:
  1211. colspec += " SERIAL"
  1212. else:
  1213. colspec += " " + self.dialect.type_compiler.process(
  1214. column.type, type_expression=column)
  1215. default = self.get_column_default_string(column)
  1216. if default is not None:
  1217. colspec += " DEFAULT " + default
  1218. if not column.nullable:
  1219. colspec += " NOT NULL"
  1220. return colspec
  1221. def visit_create_enum_type(self, create):
  1222. type_ = create.element
  1223. return "CREATE TYPE %s AS ENUM (%s)" % (
  1224. self.preparer.format_type(type_),
  1225. ", ".join(
  1226. self.sql_compiler.process(sql.literal(e), literal_binds=True)
  1227. for e in type_.enums)
  1228. )
  1229. def visit_drop_enum_type(self, drop):
  1230. type_ = drop.element
  1231. return "DROP TYPE %s" % (
  1232. self.preparer.format_type(type_)
  1233. )
  1234. def visit_create_index(self, create):
  1235. preparer = self.preparer
  1236. index = create.element
  1237. self._verify_index_table(index)
  1238. text = "CREATE "
  1239. if index.unique:
  1240. text += "UNIQUE "
  1241. text += "INDEX "
  1242. if self.dialect._supports_create_index_concurrently:
  1243. concurrently = index.dialect_options['postgresql']['concurrently']
  1244. if concurrently:
  1245. text += "CONCURRENTLY "
  1246. text += "%s ON %s " % (
  1247. self._prepared_index_name(index,
  1248. include_schema=False),
  1249. preparer.format_table(index.table)
  1250. )
  1251. using = index.dialect_options['postgresql']['using']
  1252. if using:
  1253. text += "USING %s " % preparer.quote(using)
  1254. ops = index.dialect_options["postgresql"]["ops"]
  1255. text += "(%s)" \
  1256. % (
  1257. ', '.join([
  1258. self.sql_compiler.process(
  1259. expr.self_group()
  1260. if not isinstance(expr, expression.ColumnClause)
  1261. else expr,
  1262. include_table=False, literal_binds=True) +
  1263. (
  1264. (' ' + ops[expr.key])
  1265. if hasattr(expr, 'key')
  1266. and expr.key in ops else ''
  1267. )
  1268. for expr in index.expressions
  1269. ])
  1270. )
  1271. withclause = index.dialect_options['postgresql']['with']
  1272. if withclause:
  1273. text += " WITH (%s)" % (', '.join(
  1274. ['%s = %s' % storage_parameter
  1275. for storage_parameter in withclause.items()]))
  1276. tablespace_name = index.dialect_options['postgresql']['tablespace']
  1277. if tablespace_name:
  1278. text += " TABLESPACE %s" % preparer.quote(tablespace_name)
  1279. whereclause = index.dialect_options["postgresql"]["where"]
  1280. if whereclause is not None:
  1281. where_compiled = self.sql_compiler.process(
  1282. whereclause, include_table=False,
  1283. literal_binds=True)
  1284. text += " WHERE " + where_compiled
  1285. return text
  1286. def visit_drop_index(self, drop):
  1287. index = drop.element
  1288. text = "\nDROP INDEX "
  1289. if self.dialect._supports_drop_index_concurrently:
  1290. concurrently = index.dialect_options['postgresql']['concurrently']
  1291. if concurrently:
  1292. text += "CONCURRENTLY "
  1293. text += self._prepared_index_name(index, include_schema=True)
  1294. return text
  1295. def visit_exclude_constraint(self, constraint, **kw):
  1296. text = ""
  1297. if constraint.name is not None:
  1298. text += "CONSTRAINT %s " % \
  1299. self.preparer.format_constraint(constraint)
  1300. elements = []
  1301. for expr, name, op in constraint._render_exprs:
  1302. kw['include_table'] = False
  1303. elements.append(
  1304. "%s WITH %s" % (self.sql_compiler.process(expr, **kw), op)
  1305. )
  1306. text += "EXCLUDE USING %s (%s)" % (constraint.using,
  1307. ', '.join(elements))
  1308. if constraint.where is not None:
  1309. text += ' WHERE (%s)' % self.sql_compiler.process(
  1310. constraint.where,
  1311. literal_binds=True)
  1312. text += self.define_constraint_deferrability(constraint)
  1313. return text
  1314. def post_create_table(self, table):
  1315. table_opts = []
  1316. pg_opts = table.dialect_options['postgresql']
  1317. inherits = pg_opts.get('inherits')
  1318. if inherits is not None:
  1319. if not isinstance(inherits, (list, tuple)):
  1320. inherits = (inherits, )
  1321. table_opts.append(
  1322. '\n INHERITS ( ' +
  1323. ', '.join(self.preparer.quote(name) for name in inherits) +
  1324. ' )')
  1325. if pg_opts['with_oids'] is True:
  1326. table_opts.append('\n WITH OIDS')
  1327. elif pg_opts['with_oids'] is False:
  1328. table_opts.append('\n WITHOUT OIDS')
  1329. if pg_opts['on_commit']:
  1330. on_commit_options = pg_opts['on_commit'].replace("_", " ").upper()
  1331. table_opts.append('\n ON COMMIT %s' % on_commit_options)
  1332. if pg_opts['tablespace']:
  1333. tablespace_name = pg_opts['tablespace']
  1334. table_opts.append(
  1335. '\n TABLESPACE %s' % self.preparer.quote(tablespace_name)
  1336. )
  1337. return ''.join(table_opts)
  1338. class PGTypeCompiler(compiler.GenericTypeCompiler):
  1339. def visit_TSVECTOR(self, type, **kw):
  1340. return "TSVECTOR"
  1341. def visit_INET(self, type_, **kw):
  1342. return "INET"
  1343. def visit_CIDR(self, type_, **kw):
  1344. return "CIDR"
  1345. def visit_MACADDR(self, type_, **kw):
  1346. return "MACADDR"
  1347. def visit_OID(self, type_, **kw):
  1348. return "OID"
  1349. def visit_FLOAT(self, type_, **kw):
  1350. if not type_.precision:
  1351. return "FLOAT"
  1352. else:
  1353. return "FLOAT(%(precision)s)" % {'precision': type_.precision}
  1354. def visit_DOUBLE_PRECISION(self, type_, **kw):
  1355. return "DOUBLE PRECISION"
  1356. def visit_BIGINT(self, type_, **kw):
  1357. return "BIGINT"
  1358. def visit_HSTORE(self, type_, **kw):
  1359. return "HSTORE"
  1360. def visit_JSON(self, type_, **kw):
  1361. return "JSON"
  1362. def visit_JSONB(self, type_, **kw):
  1363. return "JSONB"
  1364. def visit_INT4RANGE(self, type_, **kw):
  1365. return "INT4RANGE"
  1366. def visit_INT8RANGE(self, type_, **kw):
  1367. return "INT8RANGE"
  1368. def visit_NUMRANGE(self, type_, **kw):
  1369. return "NUMRANGE"
  1370. def visit_DATERANGE(self, type_, **kw):
  1371. return "DATERANGE"
  1372. def visit_TSRANGE(self, type_, **kw):
  1373. return "TSRANGE"
  1374. def visit_TSTZRANGE(self, type_, **kw):
  1375. return "TSTZRANGE"
  1376. def visit_datetime(self, type_, **kw):
  1377. return self.visit_TIMESTAMP(type_, **kw)
  1378. def visit_enum(self, type_, **kw):
  1379. if not type_.native_enum or not self.dialect.supports_native_enum:
  1380. return super(PGTypeCompiler, self).visit_enum(type_, **kw)
  1381. else:
  1382. return self.visit_ENUM(type_, **kw)
  1383. def visit_ENUM(self, type_, **kw):
  1384. return self.dialect.identifier_preparer.format_type(type_)
  1385. def visit_TIMESTAMP(self, type_, **kw):
  1386. return "TIMESTAMP%s %s" % (
  1387. "(%d)" % type_.precision
  1388. if getattr(type_, 'precision', None) is not None else "",
  1389. (type_.timezone and "WITH" or "WITHOUT") + " TIME ZONE"
  1390. )
  1391. def visit_TIME(self, type_, **kw):
  1392. return "TIME%s %s" % (
  1393. "(%d)" % type_.precision
  1394. if getattr(type_, 'precision', None) is not None else "",
  1395. (type_.timezone and "WITH" or "WITHOUT") + " TIME ZONE"
  1396. )
  1397. def visit_INTERVAL(self, type_, **kw):
  1398. if type_.precision is not None:
  1399. return "INTERVAL(%d)" % type_.precision
  1400. else:
  1401. return "INTERVAL"
  1402. def visit_BIT(self, type_, **kw):
  1403. if type_.varying:
  1404. compiled = "BIT VARYING"
  1405. if type_.length is not None:
  1406. compiled += "(%d)" % type_.length
  1407. else:
  1408. compiled = "BIT(%d)" % type_.length
  1409. return compiled
  1410. def visit_UUID(self, type_, **kw):
  1411. return "UUID"
  1412. def visit_large_binary(self, type_, **kw):
  1413. return self.visit_BYTEA(type_, **kw)
  1414. def visit_BYTEA(self, type_, **kw):
  1415. return "BYTEA"
  1416. def visit_ARRAY(self, type_, **kw):
  1417. return self.process(type_.item_type) + ('[]' * (type_.dimensions
  1418. if type_.dimensions
  1419. is not None else 1))
  1420. class PGIdentifierPreparer(compiler.IdentifierPreparer):
  1421. reserved_words = RESERVED_WORDS
  1422. def _unquote_identifier(self, value):
  1423. if value[0] == self.initial_quote:
  1424. value = value[1:-1].\
  1425. replace(self.escape_to_quote, self.escape_quote)
  1426. return value
  1427. def format_type(self, type_, use_schema=True):
  1428. if not type_.name:
  1429. raise exc.CompileError("PostgreSQL ENUM type requires a name.")
  1430. name = self.quote(type_.name)
  1431. effective_schema = self.schema_for_object(type_)
  1432. if not self.omit_schema and use_schema and \
  1433. effective_schema is not None:
  1434. name = self.quote_schema(effective_schema) + "." + name
  1435. return name
  1436. class PGInspector(reflection.Inspector):
  1437. def __init__(self, conn):
  1438. reflection.Inspector.__init__(self, conn)
  1439. def get_table_oid(self, table_name, schema=None):
  1440. """Return the OID for the given table name."""
  1441. return self.dialect.get_table_oid(self.bind, table_name, schema,
  1442. info_cache=self.info_cache)
  1443. def get_enums(self, schema=None):
  1444. """Return a list of ENUM objects.
  1445. Each member is a dictionary containing these fields:
  1446. * name - name of the enum
  1447. * schema - the schema name for the enum.
  1448. * visible - boolean, whether or not this enum is visible
  1449. in the default search path.
  1450. * labels - a list of string labels that apply to the enum.
  1451. :param schema: schema name. If None, the default schema
  1452. (typically 'public') is used. May also be set to '*' to
  1453. indicate load enums for all schemas.
  1454. .. versionadded:: 1.0.0
  1455. """
  1456. schema = schema or self.default_schema_name
  1457. return self.dialect._load_enums(self.bind, schema)
  1458. def get_foreign_table_names(self, schema=None):
  1459. """Return a list of FOREIGN TABLE names.
  1460. Behavior is similar to that of :meth:`.Inspector.get_table_names`,
  1461. except that the list is limited to those tables tha report a
  1462. ``relkind`` value of ``f``.
  1463. .. versionadded:: 1.0.0
  1464. """
  1465. schema = schema or self.default_schema_name
  1466. return self.dialect._get_foreign_table_names(self.bind, schema)
  1467. def get_view_names(self, schema=None, include=('plain', 'materialized')):
  1468. """Return all view names in `schema`.
  1469. :param schema: Optional, retrieve names from a non-default schema.
  1470. For special quoting, use :class:`.quoted_name`.
  1471. :param include: specify which types of views to return. Passed
  1472. as a string value (for a single type) or a tuple (for any number
  1473. of types). Defaults to ``('plain', 'materialized')``.
  1474. .. versionadded:: 1.1
  1475. """
  1476. return self.dialect.get_view_names(self.bind, schema,
  1477. info_cache=self.info_cache,
  1478. include=include)
  1479. class CreateEnumType(schema._CreateDropBase):
  1480. __visit_name__ = "create_enum_type"
  1481. class DropEnumType(schema._CreateDropBase):
  1482. __visit_name__ = "drop_enum_type"
  1483. class PGExecutionContext(default.DefaultExecutionContext):
  1484. def fire_sequence(self, seq, type_):
  1485. return self._execute_scalar((
  1486. "select nextval('%s')" %
  1487. self.dialect.identifier_preparer.format_sequence(seq)), type_)
  1488. def get_insert_default(self, column):
  1489. if column.primary_key and \
  1490. column is column.table._autoincrement_column:
  1491. if column.server_default and column.server_default.has_argument:
  1492. # pre-execute passive defaults on primary key columns
  1493. return self._execute_scalar("select %s" %
  1494. column.server_default.arg,
  1495. column.type)
  1496. elif (column.default is None or
  1497. (column.default.is_sequence and
  1498. column.default.optional)):
  1499. # execute the sequence associated with a SERIAL primary
  1500. # key column. for non-primary-key SERIAL, the ID just
  1501. # generates server side.
  1502. try:
  1503. seq_name = column._postgresql_seq_name
  1504. except AttributeError:
  1505. tab = column.table.name
  1506. col = column.name
  1507. tab = tab[0:29 + max(0, (29 - len(col)))]
  1508. col = col[0:29 + max(0, (29 - len(tab)))]
  1509. name = "%s_%s_seq" % (tab, col)
  1510. column._postgresql_seq_name = seq_name = name
  1511. if column.table is not None:
  1512. effective_schema = self.connection.schema_for_object(
  1513. column.table)
  1514. else:
  1515. effective_schema = None
  1516. if effective_schema is not None:
  1517. exc = "select nextval('\"%s\".\"%s\"')" % \
  1518. (effective_schema, seq_name)
  1519. else:
  1520. exc = "select nextval('\"%s\"')" % \
  1521. (seq_name, )
  1522. return self._execute_scalar(exc, column.type)
  1523. return super(PGExecutionContext, self).get_insert_default(column)
  1524. def should_autocommit_text(self, statement):
  1525. return AUTOCOMMIT_REGEXP.match(statement)
  1526. class PGDialect(default.DefaultDialect):
  1527. name = 'postgresql'
  1528. supports_alter = True
  1529. max_identifier_length = 63
  1530. supports_sane_rowcount = True
  1531. supports_native_enum = True
  1532. supports_native_boolean = True
  1533. supports_smallserial = True
  1534. supports_sequences = True
  1535. sequences_optional = True
  1536. preexecute_autoincrement_sequences = True
  1537. postfetch_lastrowid = False
  1538. supports_default_values = True
  1539. supports_empty_insert = False
  1540. supports_multivalues_insert = True
  1541. default_paramstyle = 'pyformat'
  1542. ischema_names = ischema_names
  1543. colspecs = colspecs
  1544. statement_compiler = PGCompiler
  1545. ddl_compiler = PGDDLCompiler
  1546. type_compiler = PGTypeCompiler
  1547. preparer = PGIdentifierPreparer
  1548. execution_ctx_cls = PGExecutionContext
  1549. inspector = PGInspector
  1550. isolation_level = None
  1551. construct_arguments = [
  1552. (schema.Index, {
  1553. "using": False,
  1554. "where": None,
  1555. "ops": {},
  1556. "concurrently": False,
  1557. "with": {},
  1558. "tablespace": None
  1559. }),
  1560. (schema.Table, {
  1561. "ignore_search_path": False,
  1562. "tablespace": None,
  1563. "with_oids": None,
  1564. "on_commit": None,
  1565. "inherits": None
  1566. }),
  1567. ]
  1568. reflection_options = ('postgresql_ignore_search_path', )
  1569. _backslash_escapes = True
  1570. _supports_create_index_concurrently = True
  1571. _supports_drop_index_concurrently = True
  1572. def __init__(self, isolation_level=None, json_serializer=None,
  1573. json_deserializer=None, **kwargs):
  1574. default.DefaultDialect.__init__(self, **kwargs)
  1575. self.isolation_level = isolation_level
  1576. self._json_deserializer = json_deserializer
  1577. self._json_serializer = json_serializer
  1578. def initialize(self, connection):
  1579. super(PGDialect, self).initialize(connection)
  1580. self.implicit_returning = self.server_version_info > (8, 2) and \
  1581. self.__dict__.get('implicit_returning', True)
  1582. self.supports_native_enum = self.server_version_info >= (8, 3)
  1583. if not self.supports_native_enum:
  1584. self.colspecs = self.colspecs.copy()
  1585. # pop base Enum type
  1586. self.colspecs.pop(sqltypes.Enum, None)
  1587. # psycopg2, others may have placed ENUM here as well
  1588. self.colspecs.pop(ENUM, None)
  1589. # http://www.postgresql.org/docs/9.3/static/release-9-2.html#AEN116689
  1590. self.supports_smallserial = self.server_version_info >= (9, 2)
  1591. self._backslash_escapes = self.server_version_info < (8, 2) or \
  1592. connection.scalar(
  1593. "show standard_conforming_strings"
  1594. ) == 'off'
  1595. self._supports_create_index_concurrently = \
  1596. self.server_version_info >= (8, 2)
  1597. self._supports_drop_index_concurrently = \
  1598. self.server_version_info >= (9, 2)
  1599. def on_connect(self):
  1600. if self.isolation_level is not None:
  1601. def connect(conn):
  1602. self.set_isolation_level(conn, self.isolation_level)
  1603. return connect
  1604. else:
  1605. return None
  1606. _isolation_lookup = set(['SERIALIZABLE', 'READ UNCOMMITTED',
  1607. 'READ COMMITTED', 'REPEATABLE READ'])
  1608. def set_isolation_level(self, connection, level):
  1609. level = level.replace('_', ' ')
  1610. if level not in self._isolation_lookup:
  1611. raise exc.ArgumentError(
  1612. "Invalid value '%s' for isolation_level. "
  1613. "Valid isolation levels for %s are %s" %
  1614. (level, self.name, ", ".join(self._isolation_lookup))
  1615. )
  1616. cursor = connection.cursor()
  1617. cursor.execute(
  1618. "SET SESSION CHARACTERISTICS AS TRANSACTION "
  1619. "ISOLATION LEVEL %s" % level)
  1620. cursor.execute("COMMIT")
  1621. cursor.close()
  1622. def get_isolation_level(self, connection):
  1623. cursor = connection.cursor()
  1624. cursor.execute('show transaction isolation level')
  1625. val = cursor.fetchone()[0]
  1626. cursor.close()
  1627. return val.upper()
  1628. def do_begin_twophase(self, connection, xid):
  1629. self.do_begin(connection.connection)
  1630. def do_prepare_twophase(self, connection, xid):
  1631. connection.execute("PREPARE TRANSACTION '%s'" % xid)
  1632. def do_rollback_twophase(self, connection, xid,
  1633. is_prepared=True, recover=False):
  1634. if is_prepared:
  1635. if recover:
  1636. # FIXME: ugly hack to get out of transaction
  1637. # context when committing recoverable transactions
  1638. # Must find out a way how to make the dbapi not
  1639. # open a transaction.
  1640. connection.execute("ROLLBACK")
  1641. connection.execute("ROLLBACK PREPARED '%s'" % xid)
  1642. connection.execute("BEGIN")
  1643. self.do_rollback(connection.connection)
  1644. else:
  1645. self.do_rollback(connection.connection)
  1646. def do_commit_twophase(self, connection, xid,
  1647. is_prepared=True, recover=False):
  1648. if is_prepared:
  1649. if recover:
  1650. connection.execute("ROLLBACK")
  1651. connection.execute("COMMIT PREPARED '%s'" % xid)
  1652. connection.execute("BEGIN")
  1653. self.do_rollback(connection.connection)
  1654. else:
  1655. self.do_commit(connection.connection)
  1656. def do_recover_twophase(self, connection):
  1657. resultset = connection.execute(
  1658. sql.text("SELECT gid FROM pg_prepared_xacts"))
  1659. return [row[0] for row in resultset]
  1660. def _get_default_schema_name(self, connection):
  1661. return connection.scalar("select current_schema()")
  1662. def has_schema(self, connection, schema):
  1663. query = ("select nspname from pg_namespace "
  1664. "where lower(nspname)=:schema")
  1665. cursor = connection.execute(
  1666. sql.text(
  1667. query,
  1668. bindparams=[
  1669. sql.bindparam(
  1670. 'schema', util.text_type(schema.lower()),
  1671. type_=sqltypes.Unicode)]
  1672. )
  1673. )
  1674. return bool(cursor.first())
  1675. def has_table(self, connection, table_name, schema=None):
  1676. # seems like case gets folded in pg_class...
  1677. if schema is None:
  1678. cursor = connection.execute(
  1679. sql.text(
  1680. "select relname from pg_class c join pg_namespace n on "
  1681. "n.oid=c.relnamespace where "
  1682. "pg_catalog.pg_table_is_visible(c.oid) "
  1683. "and relname=:name",
  1684. bindparams=[
  1685. sql.bindparam('name', util.text_type(table_name),
  1686. type_=sqltypes.Unicode)]
  1687. )
  1688. )
  1689. else:
  1690. cursor = connection.execute(
  1691. sql.text(
  1692. "select relname from pg_class c join pg_namespace n on "
  1693. "n.oid=c.relnamespace where n.nspname=:schema and "
  1694. "relname=:name",
  1695. bindparams=[
  1696. sql.bindparam('name',
  1697. util.text_type(table_name),
  1698. type_=sqltypes.Unicode),
  1699. sql.bindparam('schema',
  1700. util.text_type(schema),
  1701. type_=sqltypes.Unicode)]
  1702. )
  1703. )
  1704. return bool(cursor.first())
  1705. def has_sequence(self, connection, sequence_name, schema=None):
  1706. if schema is None:
  1707. cursor = connection.execute(
  1708. sql.text(
  1709. "SELECT relname FROM pg_class c join pg_namespace n on "
  1710. "n.oid=c.relnamespace where relkind='S' and "
  1711. "n.nspname=current_schema() "
  1712. "and relname=:name",
  1713. bindparams=[
  1714. sql.bindparam('name', util.text_type(sequence_name),
  1715. type_=sqltypes.Unicode)
  1716. ]
  1717. )
  1718. )
  1719. else:
  1720. cursor = connection.execute(
  1721. sql.text(
  1722. "SELECT relname FROM pg_class c join pg_namespace n on "
  1723. "n.oid=c.relnamespace where relkind='S' and "
  1724. "n.nspname=:schema and relname=:name",
  1725. bindparams=[
  1726. sql.bindparam('name', util.text_type(sequence_name),
  1727. type_=sqltypes.Unicode),
  1728. sql.bindparam('schema',
  1729. util.text_type(schema),
  1730. type_=sqltypes.Unicode)
  1731. ]
  1732. )
  1733. )
  1734. return bool(cursor.first())
  1735. def has_type(self, connection, type_name, schema=None):
  1736. if schema is not None:
  1737. query = """
  1738. SELECT EXISTS (
  1739. SELECT * FROM pg_catalog.pg_type t, pg_catalog.pg_namespace n
  1740. WHERE t.typnamespace = n.oid
  1741. AND t.typname = :typname
  1742. AND n.nspname = :nspname
  1743. )
  1744. """
  1745. query = sql.text(query)
  1746. else:
  1747. query = """
  1748. SELECT EXISTS (
  1749. SELECT * FROM pg_catalog.pg_type t
  1750. WHERE t.typname = :typname
  1751. AND pg_type_is_visible(t.oid)
  1752. )
  1753. """
  1754. query = sql.text(query)
  1755. query = query.bindparams(
  1756. sql.bindparam('typname',
  1757. util.text_type(type_name), type_=sqltypes.Unicode),
  1758. )
  1759. if schema is not None:
  1760. query = query.bindparams(
  1761. sql.bindparam('nspname',
  1762. util.text_type(schema), type_=sqltypes.Unicode),
  1763. )
  1764. cursor = connection.execute(query)
  1765. return bool(cursor.scalar())
  1766. def _get_server_version_info(self, connection):
  1767. v = connection.execute("select version()").scalar()
  1768. m = re.match(
  1769. r'.*(?:PostgreSQL|EnterpriseDB) '
  1770. r'(\d+)\.?(\d+)?(?:\.(\d+))?(?:\.\d+)?(?:devel)?',
  1771. v)
  1772. if not m:
  1773. raise AssertionError(
  1774. "Could not determine version from string '%s'" % v)
  1775. return tuple([int(x) for x in m.group(1, 2, 3) if x is not None])
  1776. @reflection.cache
  1777. def get_table_oid(self, connection, table_name, schema=None, **kw):
  1778. """Fetch the oid for schema.table_name.
  1779. Several reflection methods require the table oid. The idea for using
  1780. this method is that it can be fetched one time and cached for
  1781. subsequent calls.
  1782. """
  1783. table_oid = None
  1784. if schema is not None:
  1785. schema_where_clause = "n.nspname = :schema"
  1786. else:
  1787. schema_where_clause = "pg_catalog.pg_table_is_visible(c.oid)"
  1788. query = """
  1789. SELECT c.oid
  1790. FROM pg_catalog.pg_class c
  1791. LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
  1792. WHERE (%s)
  1793. AND c.relname = :table_name AND c.relkind in ('r', 'v', 'm', 'f')
  1794. """ % schema_where_clause
  1795. # Since we're binding to unicode, table_name and schema_name must be
  1796. # unicode.
  1797. table_name = util.text_type(table_name)
  1798. if schema is not None:
  1799. schema = util.text_type(schema)
  1800. s = sql.text(query).bindparams(table_name=sqltypes.Unicode)
  1801. s = s.columns(oid=sqltypes.Integer)
  1802. if schema:
  1803. s = s.bindparams(sql.bindparam('schema', type_=sqltypes.Unicode))
  1804. c = connection.execute(s, table_name=table_name, schema=schema)
  1805. table_oid = c.scalar()
  1806. if table_oid is None:
  1807. raise exc.NoSuchTableError(table_name)
  1808. return table_oid
  1809. @reflection.cache
  1810. def get_schema_names(self, connection, **kw):
  1811. result = connection.execute(
  1812. sql.text("SELECT nspname FROM pg_namespace "
  1813. "WHERE nspname NOT LIKE 'pg_%' "
  1814. "ORDER BY nspname"
  1815. ).columns(nspname=sqltypes.Unicode))
  1816. return [name for name, in result]
  1817. @reflection.cache
  1818. def get_table_names(self, connection, schema=None, **kw):
  1819. result = connection.execute(
  1820. sql.text("SELECT c.relname FROM pg_class c "
  1821. "JOIN pg_namespace n ON n.oid = c.relnamespace "
  1822. "WHERE n.nspname = :schema AND c.relkind = 'r'"
  1823. ).columns(relname=sqltypes.Unicode),
  1824. schema=schema if schema is not None else self.default_schema_name)
  1825. return [name for name, in result]
  1826. @reflection.cache
  1827. def _get_foreign_table_names(self, connection, schema=None, **kw):
  1828. result = connection.execute(
  1829. sql.text("SELECT c.relname FROM pg_class c "
  1830. "JOIN pg_namespace n ON n.oid = c.relnamespace "
  1831. "WHERE n.nspname = :schema AND c.relkind = 'f'"
  1832. ).columns(relname=sqltypes.Unicode),
  1833. schema=schema if schema is not None else self.default_schema_name)
  1834. return [name for name, in result]
  1835. @reflection.cache
  1836. def get_view_names(
  1837. self, connection, schema=None,
  1838. include=('plain', 'materialized'), **kw):
  1839. include_kind = {'plain': 'v', 'materialized': 'm'}
  1840. try:
  1841. kinds = [include_kind[i] for i in util.to_list(include)]
  1842. except KeyError:
  1843. raise ValueError(
  1844. "include %r unknown, needs to be a sequence containing "
  1845. "one or both of 'plain' and 'materialized'" % (include,))
  1846. if not kinds:
  1847. raise ValueError(
  1848. "empty include, needs to be a sequence containing "
  1849. "one or both of 'plain' and 'materialized'")
  1850. result = connection.execute(
  1851. sql.text("SELECT c.relname FROM pg_class c "
  1852. "JOIN pg_namespace n ON n.oid = c.relnamespace "
  1853. "WHERE n.nspname = :schema AND c.relkind IN (%s)" %
  1854. (", ".join("'%s'" % elem for elem in kinds))
  1855. ).columns(relname=sqltypes.Unicode),
  1856. schema=schema if schema is not None else self.default_schema_name)
  1857. return [name for name, in result]
  1858. @reflection.cache
  1859. def get_view_definition(self, connection, view_name, schema=None, **kw):
  1860. view_def = connection.scalar(
  1861. sql.text("SELECT pg_get_viewdef(c.oid) view_def FROM pg_class c "
  1862. "JOIN pg_namespace n ON n.oid = c.relnamespace "
  1863. "WHERE n.nspname = :schema AND c.relname = :view_name "
  1864. "AND c.relkind IN ('v', 'm')"
  1865. ).columns(view_def=sqltypes.Unicode),
  1866. schema=schema if schema is not None else self.default_schema_name,
  1867. view_name=view_name)
  1868. return view_def
  1869. @reflection.cache
  1870. def get_columns(self, connection, table_name, schema=None, **kw):
  1871. table_oid = self.get_table_oid(connection, table_name, schema,
  1872. info_cache=kw.get('info_cache'))
  1873. SQL_COLS = """
  1874. SELECT a.attname,
  1875. pg_catalog.format_type(a.atttypid, a.atttypmod),
  1876. (SELECT pg_catalog.pg_get_expr(d.adbin, d.adrelid)
  1877. FROM pg_catalog.pg_attrdef d
  1878. WHERE d.adrelid = a.attrelid AND d.adnum = a.attnum
  1879. AND a.atthasdef)
  1880. AS DEFAULT,
  1881. a.attnotnull, a.attnum, a.attrelid as table_oid
  1882. FROM pg_catalog.pg_attribute a
  1883. WHERE a.attrelid = :table_oid
  1884. AND a.attnum > 0 AND NOT a.attisdropped
  1885. ORDER BY a.attnum
  1886. """
  1887. s = sql.text(SQL_COLS,
  1888. bindparams=[
  1889. sql.bindparam('table_oid', type_=sqltypes.Integer)],
  1890. typemap={
  1891. 'attname': sqltypes.Unicode,
  1892. 'default': sqltypes.Unicode}
  1893. )
  1894. c = connection.execute(s, table_oid=table_oid)
  1895. rows = c.fetchall()
  1896. domains = self._load_domains(connection)
  1897. enums = dict(
  1898. (
  1899. "%s.%s" % (rec['schema'], rec['name'])
  1900. if not rec['visible'] else rec['name'], rec) for rec in
  1901. self._load_enums(connection, schema='*')
  1902. )
  1903. # format columns
  1904. columns = []
  1905. for name, format_type, default, notnull, attnum, table_oid in rows:
  1906. column_info = self._get_column_info(
  1907. name, format_type, default, notnull, domains, enums, schema)
  1908. columns.append(column_info)
  1909. return columns
  1910. def _get_column_info(self, name, format_type, default,
  1911. notnull, domains, enums, schema):
  1912. # strip (*) from character varying(5), timestamp(5)
  1913. # with time zone, geometry(POLYGON), etc.
  1914. attype = re.sub(r'\(.*\)', '', format_type)
  1915. # strip '[]' from integer[], etc.
  1916. attype = attype.replace('[]', '')
  1917. nullable = not notnull
  1918. is_array = format_type.endswith('[]')
  1919. charlen = re.search(r'\(([\d,]+)\)', format_type)
  1920. if charlen:
  1921. charlen = charlen.group(1)
  1922. args = re.search(r'\((.*)\)', format_type)
  1923. if args and args.group(1):
  1924. args = tuple(re.split(r'\s*,\s*', args.group(1)))
  1925. else:
  1926. args = ()
  1927. kwargs = {}
  1928. if attype == 'numeric':
  1929. if charlen:
  1930. prec, scale = charlen.split(',')
  1931. args = (int(prec), int(scale))
  1932. else:
  1933. args = ()
  1934. elif attype == 'double precision':
  1935. args = (53, )
  1936. elif attype == 'integer':
  1937. args = ()
  1938. elif attype in ('timestamp with time zone',
  1939. 'time with time zone'):
  1940. kwargs['timezone'] = True
  1941. if charlen:
  1942. kwargs['precision'] = int(charlen)
  1943. args = ()
  1944. elif attype in ('timestamp without time zone',
  1945. 'time without time zone', 'time'):
  1946. kwargs['timezone'] = False
  1947. if charlen:
  1948. kwargs['precision'] = int(charlen)
  1949. args = ()
  1950. elif attype == 'bit varying':
  1951. kwargs['varying'] = True
  1952. if charlen:
  1953. args = (int(charlen),)
  1954. else:
  1955. args = ()
  1956. elif attype in ('interval', 'interval year to month',
  1957. 'interval day to second'):
  1958. if charlen:
  1959. kwargs['precision'] = int(charlen)
  1960. args = ()
  1961. elif charlen:
  1962. args = (int(charlen),)
  1963. while True:
  1964. if attype in self.ischema_names:
  1965. coltype = self.ischema_names[attype]
  1966. break
  1967. elif attype in enums:
  1968. enum = enums[attype]
  1969. coltype = ENUM
  1970. kwargs['name'] = enum['name']
  1971. if not enum['visible']:
  1972. kwargs['schema'] = enum['schema']
  1973. args = tuple(enum['labels'])
  1974. break
  1975. elif attype in domains:
  1976. domain = domains[attype]
  1977. attype = domain['attype']
  1978. # A table can't override whether the domain is nullable.
  1979. nullable = domain['nullable']
  1980. if domain['default'] and not default:
  1981. # It can, however, override the default
  1982. # value, but can't set it to null.
  1983. default = domain['default']
  1984. continue
  1985. else:
  1986. coltype = None
  1987. break
  1988. if coltype:
  1989. coltype = coltype(*args, **kwargs)
  1990. if is_array:
  1991. coltype = self.ischema_names['_array'](coltype)
  1992. else:
  1993. util.warn("Did not recognize type '%s' of column '%s'" %
  1994. (attype, name))
  1995. coltype = sqltypes.NULLTYPE
  1996. # adjust the default value
  1997. autoincrement = False
  1998. if default is not None:
  1999. match = re.search(r"""(nextval\(')([^']+)('.*$)""", default)
  2000. if match is not None:
  2001. if issubclass(coltype._type_affinity, sqltypes.Integer):
  2002. autoincrement = True
  2003. # the default is related to a Sequence
  2004. sch = schema
  2005. if '.' not in match.group(2) and sch is not None:
  2006. # unconditionally quote the schema name. this could
  2007. # later be enhanced to obey quoting rules /
  2008. # "quote schema"
  2009. default = match.group(1) + \
  2010. ('"%s"' % sch) + '.' + \
  2011. match.group(2) + match.group(3)
  2012. column_info = dict(name=name, type=coltype, nullable=nullable,
  2013. default=default, autoincrement=autoincrement)
  2014. return column_info
  2015. @reflection.cache
  2016. def get_pk_constraint(self, connection, table_name, schema=None, **kw):
  2017. table_oid = self.get_table_oid(connection, table_name, schema,
  2018. info_cache=kw.get('info_cache'))
  2019. if self.server_version_info < (8, 4):
  2020. PK_SQL = """
  2021. SELECT a.attname
  2022. FROM
  2023. pg_class t
  2024. join pg_index ix on t.oid = ix.indrelid
  2025. join pg_attribute a
  2026. on t.oid=a.attrelid AND %s
  2027. WHERE
  2028. t.oid = :table_oid and ix.indisprimary = 't'
  2029. ORDER BY a.attnum
  2030. """ % self._pg_index_any("a.attnum", "ix.indkey")
  2031. else:
  2032. # unnest() and generate_subscripts() both introduced in
  2033. # version 8.4
  2034. PK_SQL = """
  2035. SELECT a.attname
  2036. FROM pg_attribute a JOIN (
  2037. SELECT unnest(ix.indkey) attnum,
  2038. generate_subscripts(ix.indkey, 1) ord
  2039. FROM pg_index ix
  2040. WHERE ix.indrelid = :table_oid AND ix.indisprimary
  2041. ) k ON a.attnum=k.attnum
  2042. WHERE a.attrelid = :table_oid
  2043. ORDER BY k.ord
  2044. """
  2045. t = sql.text(PK_SQL, typemap={'attname': sqltypes.Unicode})
  2046. c = connection.execute(t, table_oid=table_oid)
  2047. cols = [r[0] for r in c.fetchall()]
  2048. PK_CONS_SQL = """
  2049. SELECT conname
  2050. FROM pg_catalog.pg_constraint r
  2051. WHERE r.conrelid = :table_oid AND r.contype = 'p'
  2052. ORDER BY 1
  2053. """
  2054. t = sql.text(PK_CONS_SQL, typemap={'conname': sqltypes.Unicode})
  2055. c = connection.execute(t, table_oid=table_oid)
  2056. name = c.scalar()
  2057. return {'constrained_columns': cols, 'name': name}
  2058. @reflection.cache
  2059. def get_foreign_keys(self, connection, table_name, schema=None,
  2060. postgresql_ignore_search_path=False, **kw):
  2061. preparer = self.identifier_preparer
  2062. table_oid = self.get_table_oid(connection, table_name, schema,
  2063. info_cache=kw.get('info_cache'))
  2064. FK_SQL = """
  2065. SELECT r.conname,
  2066. pg_catalog.pg_get_constraintdef(r.oid, true) as condef,
  2067. n.nspname as conschema
  2068. FROM pg_catalog.pg_constraint r,
  2069. pg_namespace n,
  2070. pg_class c
  2071. WHERE r.conrelid = :table AND
  2072. r.contype = 'f' AND
  2073. c.oid = confrelid AND
  2074. n.oid = c.relnamespace
  2075. ORDER BY 1
  2076. """
  2077. # http://www.postgresql.org/docs/9.0/static/sql-createtable.html
  2078. FK_REGEX = re.compile(
  2079. r'FOREIGN KEY \((.*?)\) REFERENCES (?:(.*?)\.)?(.*?)\((.*?)\)'
  2080. r'[\s]?(MATCH (FULL|PARTIAL|SIMPLE)+)?'
  2081. r'[\s]?(ON UPDATE '
  2082. r'(CASCADE|RESTRICT|NO ACTION|SET NULL|SET DEFAULT)+)?'
  2083. r'[\s]?(ON DELETE '
  2084. r'(CASCADE|RESTRICT|NO ACTION|SET NULL|SET DEFAULT)+)?'
  2085. r'[\s]?(DEFERRABLE|NOT DEFERRABLE)?'
  2086. r'[\s]?(INITIALLY (DEFERRED|IMMEDIATE)+)?'
  2087. )
  2088. t = sql.text(FK_SQL, typemap={
  2089. 'conname': sqltypes.Unicode,
  2090. 'condef': sqltypes.Unicode})
  2091. c = connection.execute(t, table=table_oid)
  2092. fkeys = []
  2093. for conname, condef, conschema in c.fetchall():
  2094. m = re.search(FK_REGEX, condef).groups()
  2095. constrained_columns, referred_schema, \
  2096. referred_table, referred_columns, \
  2097. _, match, _, onupdate, _, ondelete, \
  2098. deferrable, _, initially = m
  2099. if deferrable is not None:
  2100. deferrable = True if deferrable == 'DEFERRABLE' else False
  2101. constrained_columns = [preparer._unquote_identifier(x)
  2102. for x in re.split(
  2103. r'\s*,\s*', constrained_columns)]
  2104. if postgresql_ignore_search_path:
  2105. # when ignoring search path, we use the actual schema
  2106. # provided it isn't the "default" schema
  2107. if conschema != self.default_schema_name:
  2108. referred_schema = conschema
  2109. else:
  2110. referred_schema = schema
  2111. elif referred_schema:
  2112. # referred_schema is the schema that we regexp'ed from
  2113. # pg_get_constraintdef(). If the schema is in the search
  2114. # path, pg_get_constraintdef() will give us None.
  2115. referred_schema = \
  2116. preparer._unquote_identifier(referred_schema)
  2117. elif schema is not None and schema == conschema:
  2118. # If the actual schema matches the schema of the table
  2119. # we're reflecting, then we will use that.
  2120. referred_schema = schema
  2121. referred_table = preparer._unquote_identifier(referred_table)
  2122. referred_columns = [preparer._unquote_identifier(x)
  2123. for x in
  2124. re.split(r'\s*,\s', referred_columns)]
  2125. fkey_d = {
  2126. 'name': conname,
  2127. 'constrained_columns': constrained_columns,
  2128. 'referred_schema': referred_schema,
  2129. 'referred_table': referred_table,
  2130. 'referred_columns': referred_columns,
  2131. 'options': {
  2132. 'onupdate': onupdate,
  2133. 'ondelete': ondelete,
  2134. 'deferrable': deferrable,
  2135. 'initially': initially,
  2136. 'match': match
  2137. }
  2138. }
  2139. fkeys.append(fkey_d)
  2140. return fkeys
  2141. def _pg_index_any(self, col, compare_to):
  2142. if self.server_version_info < (8, 1):
  2143. # http://www.postgresql.org/message-id/10279.1124395722@sss.pgh.pa.us
  2144. # "In CVS tip you could replace this with "attnum = ANY (indkey)".
  2145. # Unfortunately, most array support doesn't work on int2vector in
  2146. # pre-8.1 releases, so I think you're kinda stuck with the above
  2147. # for now.
  2148. # regards, tom lane"
  2149. return "(%s)" % " OR ".join(
  2150. "%s[%d] = %s" % (compare_to, ind, col)
  2151. for ind in range(0, 10)
  2152. )
  2153. else:
  2154. return "%s = ANY(%s)" % (col, compare_to)
  2155. @reflection.cache
  2156. def get_indexes(self, connection, table_name, schema, **kw):
  2157. table_oid = self.get_table_oid(connection, table_name, schema,
  2158. info_cache=kw.get('info_cache'))
  2159. # cast indkey as varchar since it's an int2vector,
  2160. # returned as a list by some drivers such as pypostgresql
  2161. if self.server_version_info < (8, 5):
  2162. IDX_SQL = """
  2163. SELECT
  2164. i.relname as relname,
  2165. ix.indisunique, ix.indexprs, ix.indpred,
  2166. a.attname, a.attnum, NULL, ix.indkey%s,
  2167. %s, am.amname
  2168. FROM
  2169. pg_class t
  2170. join pg_index ix on t.oid = ix.indrelid
  2171. join pg_class i on i.oid = ix.indexrelid
  2172. left outer join
  2173. pg_attribute a
  2174. on t.oid = a.attrelid and %s
  2175. left outer join
  2176. pg_am am
  2177. on i.relam = am.oid
  2178. WHERE
  2179. t.relkind IN ('r', 'v', 'f', 'm')
  2180. and t.oid = :table_oid
  2181. and ix.indisprimary = 'f'
  2182. ORDER BY
  2183. t.relname,
  2184. i.relname
  2185. """ % (
  2186. # version 8.3 here was based on observing the
  2187. # cast does not work in PG 8.2.4, does work in 8.3.0.
  2188. # nothing in PG changelogs regarding this.
  2189. "::varchar" if self.server_version_info >= (8, 3) else "",
  2190. "i.reloptions" if self.server_version_info >= (8, 2)
  2191. else "NULL",
  2192. self._pg_index_any("a.attnum", "ix.indkey")
  2193. )
  2194. else:
  2195. IDX_SQL = """
  2196. SELECT
  2197. i.relname as relname,
  2198. ix.indisunique, ix.indexprs, ix.indpred,
  2199. a.attname, a.attnum, c.conrelid, ix.indkey::varchar,
  2200. i.reloptions, am.amname
  2201. FROM
  2202. pg_class t
  2203. join pg_index ix on t.oid = ix.indrelid
  2204. join pg_class i on i.oid = ix.indexrelid
  2205. left outer join
  2206. pg_attribute a
  2207. on t.oid = a.attrelid and a.attnum = ANY(ix.indkey)
  2208. left outer join
  2209. pg_constraint c
  2210. on (ix.indrelid = c.conrelid and
  2211. ix.indexrelid = c.conindid and
  2212. c.contype in ('p', 'u', 'x'))
  2213. left outer join
  2214. pg_am am
  2215. on i.relam = am.oid
  2216. WHERE
  2217. t.relkind IN ('r', 'v', 'f', 'm')
  2218. and t.oid = :table_oid
  2219. and ix.indisprimary = 'f'
  2220. ORDER BY
  2221. t.relname,
  2222. i.relname
  2223. """
  2224. t = sql.text(IDX_SQL, typemap={
  2225. 'relname': sqltypes.Unicode,
  2226. 'attname': sqltypes.Unicode})
  2227. c = connection.execute(t, table_oid=table_oid)
  2228. indexes = defaultdict(lambda: defaultdict(dict))
  2229. sv_idx_name = None
  2230. for row in c.fetchall():
  2231. (idx_name, unique, expr, prd, col,
  2232. col_num, conrelid, idx_key, options, amname) = row
  2233. if expr:
  2234. if idx_name != sv_idx_name:
  2235. util.warn(
  2236. "Skipped unsupported reflection of "
  2237. "expression-based index %s"
  2238. % idx_name)
  2239. sv_idx_name = idx_name
  2240. continue
  2241. if prd and not idx_name == sv_idx_name:
  2242. util.warn(
  2243. "Predicate of partial index %s ignored during reflection"
  2244. % idx_name)
  2245. sv_idx_name = idx_name
  2246. has_idx = idx_name in indexes
  2247. index = indexes[idx_name]
  2248. if col is not None:
  2249. index['cols'][col_num] = col
  2250. if not has_idx:
  2251. index['key'] = [int(k.strip()) for k in idx_key.split()]
  2252. index['unique'] = unique
  2253. if conrelid is not None:
  2254. index['duplicates_constraint'] = idx_name
  2255. if options:
  2256. index['options'] = dict(
  2257. [option.split("=") for option in options])
  2258. # it *might* be nice to include that this is 'btree' in the
  2259. # reflection info. But we don't want an Index object
  2260. # to have a ``postgresql_using`` in it that is just the
  2261. # default, so for the moment leaving this out.
  2262. if amname and amname != 'btree':
  2263. index['amname'] = amname
  2264. result = []
  2265. for name, idx in indexes.items():
  2266. entry = {
  2267. 'name': name,
  2268. 'unique': idx['unique'],
  2269. 'column_names': [idx['cols'][i] for i in idx['key']]
  2270. }
  2271. if 'duplicates_constraint' in idx:
  2272. entry['duplicates_constraint'] = idx['duplicates_constraint']
  2273. if 'options' in idx:
  2274. entry.setdefault(
  2275. 'dialect_options', {})["postgresql_with"] = idx['options']
  2276. if 'amname' in idx:
  2277. entry.setdefault(
  2278. 'dialect_options', {})["postgresql_using"] = idx['amname']
  2279. result.append(entry)
  2280. return result
  2281. @reflection.cache
  2282. def get_unique_constraints(self, connection, table_name,
  2283. schema=None, **kw):
  2284. table_oid = self.get_table_oid(connection, table_name, schema,
  2285. info_cache=kw.get('info_cache'))
  2286. UNIQUE_SQL = """
  2287. SELECT
  2288. cons.conname as name,
  2289. cons.conkey as key,
  2290. a.attnum as col_num,
  2291. a.attname as col_name
  2292. FROM
  2293. pg_catalog.pg_constraint cons
  2294. join pg_attribute a
  2295. on cons.conrelid = a.attrelid AND
  2296. a.attnum = ANY(cons.conkey)
  2297. WHERE
  2298. cons.conrelid = :table_oid AND
  2299. cons.contype = 'u'
  2300. """
  2301. t = sql.text(UNIQUE_SQL, typemap={'col_name': sqltypes.Unicode})
  2302. c = connection.execute(t, table_oid=table_oid)
  2303. uniques = defaultdict(lambda: defaultdict(dict))
  2304. for row in c.fetchall():
  2305. uc = uniques[row.name]
  2306. uc["key"] = row.key
  2307. uc["cols"][row.col_num] = row.col_name
  2308. return [
  2309. {'name': name,
  2310. 'column_names': [uc["cols"][i] for i in uc["key"]]}
  2311. for name, uc in uniques.items()
  2312. ]
  2313. @reflection.cache
  2314. def get_check_constraints(
  2315. self, connection, table_name, schema=None, **kw):
  2316. table_oid = self.get_table_oid(connection, table_name, schema,
  2317. info_cache=kw.get('info_cache'))
  2318. CHECK_SQL = """
  2319. SELECT
  2320. cons.conname as name,
  2321. cons.consrc as src
  2322. FROM
  2323. pg_catalog.pg_constraint cons
  2324. WHERE
  2325. cons.conrelid = :table_oid AND
  2326. cons.contype = 'c'
  2327. """
  2328. c = connection.execute(sql.text(CHECK_SQL), table_oid=table_oid)
  2329. return [
  2330. {'name': name,
  2331. 'sqltext': src[1:-1]}
  2332. for name, src in c.fetchall()
  2333. ]
  2334. def _load_enums(self, connection, schema=None):
  2335. schema = schema or self.default_schema_name
  2336. if not self.supports_native_enum:
  2337. return {}
  2338. # Load data types for enums:
  2339. SQL_ENUMS = """
  2340. SELECT t.typname as "name",
  2341. -- no enum defaults in 8.4 at least
  2342. -- t.typdefault as "default",
  2343. pg_catalog.pg_type_is_visible(t.oid) as "visible",
  2344. n.nspname as "schema",
  2345. e.enumlabel as "label"
  2346. FROM pg_catalog.pg_type t
  2347. LEFT JOIN pg_catalog.pg_namespace n ON n.oid = t.typnamespace
  2348. LEFT JOIN pg_catalog.pg_enum e ON t.oid = e.enumtypid
  2349. WHERE t.typtype = 'e'
  2350. """
  2351. if schema != '*':
  2352. SQL_ENUMS += "AND n.nspname = :schema "
  2353. # e.oid gives us label order within an enum
  2354. SQL_ENUMS += 'ORDER BY "schema", "name", e.oid'
  2355. s = sql.text(SQL_ENUMS, typemap={
  2356. 'attname': sqltypes.Unicode,
  2357. 'label': sqltypes.Unicode})
  2358. if schema != '*':
  2359. s = s.bindparams(schema=schema)
  2360. c = connection.execute(s)
  2361. enums = []
  2362. enum_by_name = {}
  2363. for enum in c.fetchall():
  2364. key = (enum['schema'], enum['name'])
  2365. if key in enum_by_name:
  2366. enum_by_name[key]['labels'].append(enum['label'])
  2367. else:
  2368. enum_by_name[key] = enum_rec = {
  2369. 'name': enum['name'],
  2370. 'schema': enum['schema'],
  2371. 'visible': enum['visible'],
  2372. 'labels': [enum['label']],
  2373. }
  2374. enums.append(enum_rec)
  2375. return enums
  2376. def _load_domains(self, connection):
  2377. # Load data types for domains:
  2378. SQL_DOMAINS = """
  2379. SELECT t.typname as "name",
  2380. pg_catalog.format_type(t.typbasetype, t.typtypmod) as "attype",
  2381. not t.typnotnull as "nullable",
  2382. t.typdefault as "default",
  2383. pg_catalog.pg_type_is_visible(t.oid) as "visible",
  2384. n.nspname as "schema"
  2385. FROM pg_catalog.pg_type t
  2386. LEFT JOIN pg_catalog.pg_namespace n ON n.oid = t.typnamespace
  2387. WHERE t.typtype = 'd'
  2388. """
  2389. s = sql.text(SQL_DOMAINS, typemap={'attname': sqltypes.Unicode})
  2390. c = connection.execute(s)
  2391. domains = {}
  2392. for domain in c.fetchall():
  2393. # strip (30) from character varying(30)
  2394. attype = re.search(r'([^\(]+)', domain['attype']).group(1)
  2395. if domain['visible']:
  2396. # 'visible' just means whether or not the domain is in a
  2397. # schema that's on the search path -- or not overridden by
  2398. # a schema with higher precedence. If it's not visible,
  2399. # it will be prefixed with the schema-name when it's used.
  2400. name = domain['name']
  2401. else:
  2402. name = "%s.%s" % (domain['schema'], domain['name'])
  2403. domains[name] = {
  2404. 'attype': attype,
  2405. 'nullable': domain['nullable'],
  2406. 'default': domain['default']
  2407. }
  2408. return domains