base.py 115 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283
  1. # mysql/base.py
  2. # Copyright (C) 2005-2022 the SQLAlchemy authors and contributors
  3. # <see AUTHORS file>
  4. #
  5. # This module is part of SQLAlchemy and is released under
  6. # the MIT License: https://www.opensource.org/licenses/mit-license.php
  7. r"""
  8. .. dialect:: mysql
  9. :name: MySQL / MariaDB
  10. :full_support: 5.6, 5.7, 8.0 / 10.4, 10.5
  11. :normal_support: 5.6+ / 10+
  12. :best_effort: 5.0.2+ / 5.0.2+
  13. Supported Versions and Features
  14. -------------------------------
  15. SQLAlchemy supports MySQL starting with version 5.0.2 through modern releases,
  16. as well as all modern versions of MariaDB. See the official MySQL
  17. documentation for detailed information about features supported in any given
  18. server release.
  19. .. versionchanged:: 1.4 minimum MySQL version supported is now 5.0.2.
  20. MariaDB Support
  21. ~~~~~~~~~~~~~~~
  22. The MariaDB variant of MySQL retains fundamental compatibility with MySQL's
  23. protocols however the development of these two products continues to diverge.
  24. Within the realm of SQLAlchemy, the two databases have a small number of
  25. syntactical and behavioral differences that SQLAlchemy accommodates automatically.
  26. To connect to a MariaDB database, no changes to the database URL are required::
  27. engine = create_engine("mysql+pymysql://user:pass@some_mariadb/dbname?charset=utf8mb4")
  28. Upon first connect, the SQLAlchemy dialect employs a
  29. server version detection scheme that determines if the
  30. backing database reports as MariaDB. Based on this flag, the dialect
  31. can make different choices in those of areas where its behavior
  32. must be different.
  33. .. _mysql_mariadb_only_mode:
  34. MariaDB-Only Mode
  35. ~~~~~~~~~~~~~~~~~
  36. The dialect also supports an **optional** "MariaDB-only" mode of connection, which may be
  37. useful for the case where an application makes use of MariaDB-specific features
  38. and is not compatible with a MySQL database. To use this mode of operation,
  39. replace the "mysql" token in the above URL with "mariadb"::
  40. engine = create_engine("mariadb+pymysql://user:pass@some_mariadb/dbname?charset=utf8mb4")
  41. The above engine, upon first connect, will raise an error if the server version
  42. detection detects that the backing database is not MariaDB.
  43. When using an engine with ``"mariadb"`` as the dialect name, **all mysql-specific options
  44. that include the name "mysql" in them are now named with "mariadb"**. This means
  45. options like ``mysql_engine`` should be named ``mariadb_engine``, etc. Both
  46. "mysql" and "mariadb" options can be used simultaneously for applications that
  47. use URLs with both "mysql" and "mariadb" dialects::
  48. my_table = Table(
  49. "mytable",
  50. metadata,
  51. Column("id", Integer, primary_key=True),
  52. Column("textdata", String(50)),
  53. mariadb_engine="InnoDB",
  54. mysql_engine="InnoDB",
  55. )
  56. Index(
  57. "textdata_ix",
  58. my_table.c.textdata,
  59. mysql_prefix="FULLTEXT",
  60. mariadb_prefix="FULLTEXT",
  61. )
  62. Similar behavior will occur when the above structures are reflected, i.e. the
  63. "mariadb" prefix will be present in the option names when the database URL
  64. is based on the "mariadb" name.
  65. .. versionadded:: 1.4 Added "mariadb" dialect name supporting "MariaDB-only mode"
  66. for the MySQL dialect.
  67. .. _mysql_connection_timeouts:
  68. Connection Timeouts and Disconnects
  69. -----------------------------------
  70. MySQL / MariaDB feature an automatic connection close behavior, for connections that
  71. have been idle for a fixed period of time, defaulting to eight hours.
  72. To circumvent having this issue, use
  73. the :paramref:`_sa.create_engine.pool_recycle` option which ensures that
  74. a connection will be discarded and replaced with a new one if it has been
  75. present in the pool for a fixed number of seconds::
  76. engine = create_engine('mysql+mysqldb://...', pool_recycle=3600)
  77. For more comprehensive disconnect detection of pooled connections, including
  78. accommodation of server restarts and network issues, a pre-ping approach may
  79. be employed. See :ref:`pool_disconnects` for current approaches.
  80. .. seealso::
  81. :ref:`pool_disconnects` - Background on several techniques for dealing
  82. with timed out connections as well as database restarts.
  83. .. _mysql_storage_engines:
  84. CREATE TABLE arguments including Storage Engines
  85. ------------------------------------------------
  86. Both MySQL's and MariaDB's CREATE TABLE syntax includes a wide array of special options,
  87. including ``ENGINE``, ``CHARSET``, ``MAX_ROWS``, ``ROW_FORMAT``,
  88. ``INSERT_METHOD``, and many more.
  89. To accommodate the rendering of these arguments, specify the form
  90. ``mysql_argument_name="value"``. For example, to specify a table with
  91. ``ENGINE`` of ``InnoDB``, ``CHARSET`` of ``utf8mb4``, and ``KEY_BLOCK_SIZE``
  92. of ``1024``::
  93. Table('mytable', metadata,
  94. Column('data', String(32)),
  95. mysql_engine='InnoDB',
  96. mysql_charset='utf8mb4',
  97. mysql_key_block_size="1024"
  98. )
  99. When supporting :ref:`mysql_mariadb_only_mode` mode, similar keys against
  100. the "mariadb" prefix must be included as well. The values can of course
  101. vary independently so that different settings on MySQL vs. MariaDB may
  102. be maintained::
  103. # support both "mysql" and "mariadb-only" engine URLs
  104. Table('mytable', metadata,
  105. Column('data', String(32)),
  106. mysql_engine='InnoDB',
  107. mariadb_engine='InnoDB',
  108. mysql_charset='utf8mb4',
  109. mariadb_charset='utf8',
  110. mysql_key_block_size="1024"
  111. mariadb_key_block_size="1024"
  112. )
  113. The MySQL / MariaDB dialects will normally transfer any keyword specified as
  114. ``mysql_keyword_name`` to be rendered as ``KEYWORD_NAME`` in the
  115. ``CREATE TABLE`` statement. A handful of these names will render with a space
  116. instead of an underscore; to support this, the MySQL dialect has awareness of
  117. these particular names, which include ``DATA DIRECTORY``
  118. (e.g. ``mysql_data_directory``), ``CHARACTER SET`` (e.g.
  119. ``mysql_character_set``) and ``INDEX DIRECTORY`` (e.g.
  120. ``mysql_index_directory``).
  121. The most common argument is ``mysql_engine``, which refers to the storage
  122. engine for the table. Historically, MySQL server installations would default
  123. to ``MyISAM`` for this value, although newer versions may be defaulting
  124. to ``InnoDB``. The ``InnoDB`` engine is typically preferred for its support
  125. of transactions and foreign keys.
  126. A :class:`_schema.Table`
  127. that is created in a MySQL / MariaDB database with a storage engine
  128. of ``MyISAM`` will be essentially non-transactional, meaning any
  129. INSERT/UPDATE/DELETE statement referring to this table will be invoked as
  130. autocommit. It also will have no support for foreign key constraints; while
  131. the ``CREATE TABLE`` statement accepts foreign key options, when using the
  132. ``MyISAM`` storage engine these arguments are discarded. Reflecting such a
  133. table will also produce no foreign key constraint information.
  134. For fully atomic transactions as well as support for foreign key
  135. constraints, all participating ``CREATE TABLE`` statements must specify a
  136. transactional engine, which in the vast majority of cases is ``InnoDB``.
  137. Case Sensitivity and Table Reflection
  138. -------------------------------------
  139. Both MySQL and MariaDB have inconsistent support for case-sensitive identifier
  140. names, basing support on specific details of the underlying
  141. operating system. However, it has been observed that no matter
  142. what case sensitivity behavior is present, the names of tables in
  143. foreign key declarations are *always* received from the database
  144. as all-lower case, making it impossible to accurately reflect a
  145. schema where inter-related tables use mixed-case identifier names.
  146. Therefore it is strongly advised that table names be declared as
  147. all lower case both within SQLAlchemy as well as on the MySQL / MariaDB
  148. database itself, especially if database reflection features are
  149. to be used.
  150. .. _mysql_isolation_level:
  151. Transaction Isolation Level
  152. ---------------------------
  153. All MySQL / MariaDB dialects support setting of transaction isolation level both via a
  154. dialect-specific parameter :paramref:`_sa.create_engine.isolation_level`
  155. accepted
  156. by :func:`_sa.create_engine`, as well as the
  157. :paramref:`.Connection.execution_options.isolation_level` argument as passed to
  158. :meth:`_engine.Connection.execution_options`.
  159. This feature works by issuing the
  160. command ``SET SESSION TRANSACTION ISOLATION LEVEL <level>`` for each new
  161. connection. For the special AUTOCOMMIT isolation level, DBAPI-specific
  162. techniques are used.
  163. To set isolation level using :func:`_sa.create_engine`::
  164. engine = create_engine(
  165. "mysql://scott:tiger@localhost/test",
  166. isolation_level="READ UNCOMMITTED"
  167. )
  168. To set using per-connection execution options::
  169. connection = engine.connect()
  170. connection = connection.execution_options(
  171. isolation_level="READ COMMITTED"
  172. )
  173. Valid values for ``isolation_level`` include:
  174. * ``READ COMMITTED``
  175. * ``READ UNCOMMITTED``
  176. * ``REPEATABLE READ``
  177. * ``SERIALIZABLE``
  178. * ``AUTOCOMMIT``
  179. The special ``AUTOCOMMIT`` value makes use of the various "autocommit"
  180. attributes provided by specific DBAPIs, and is currently supported by
  181. MySQLdb, MySQL-Client, MySQL-Connector Python, and PyMySQL. Using it,
  182. the database connection will return true for the value of
  183. ``SELECT @@autocommit;``.
  184. .. seealso::
  185. :ref:`dbapi_autocommit`
  186. AUTO_INCREMENT Behavior
  187. -----------------------
  188. When creating tables, SQLAlchemy will automatically set ``AUTO_INCREMENT`` on
  189. the first :class:`.Integer` primary key column which is not marked as a
  190. foreign key::
  191. >>> t = Table('mytable', metadata,
  192. ... Column('mytable_id', Integer, primary_key=True)
  193. ... )
  194. >>> t.create()
  195. CREATE TABLE mytable (
  196. id INTEGER NOT NULL AUTO_INCREMENT,
  197. PRIMARY KEY (id)
  198. )
  199. You can disable this behavior by passing ``False`` to the
  200. :paramref:`_schema.Column.autoincrement` argument of :class:`_schema.Column`.
  201. This flag
  202. can also be used to enable auto-increment on a secondary column in a
  203. multi-column key for some storage engines::
  204. Table('mytable', metadata,
  205. Column('gid', Integer, primary_key=True, autoincrement=False),
  206. Column('id', Integer, primary_key=True)
  207. )
  208. .. _mysql_ss_cursors:
  209. Server Side Cursors
  210. -------------------
  211. Server-side cursor support is available for the mysqlclient, PyMySQL,
  212. mariadbconnector dialects and may also be available in others. This makes use
  213. of either the "buffered=True/False" flag if available or by using a class such
  214. as ``MySQLdb.cursors.SSCursor`` or ``pymysql.cursors.SSCursor`` internally.
  215. Server side cursors are enabled on a per-statement basis by using the
  216. :paramref:`.Connection.execution_options.stream_results` connection execution
  217. option::
  218. with engine.connect() as conn:
  219. result = conn.execution_options(stream_results=True).execute(text("select * from table"))
  220. Note that some kinds of SQL statements may not be supported with
  221. server side cursors; generally, only SQL statements that return rows should be
  222. used with this option.
  223. .. deprecated:: 1.4 The dialect-level server_side_cursors flag is deprecated
  224. and will be removed in a future release. Please use the
  225. :paramref:`_engine.Connection.stream_results` execution option for
  226. unbuffered cursor support.
  227. .. seealso::
  228. :ref:`engine_stream_results`
  229. .. _mysql_unicode:
  230. Unicode
  231. -------
  232. Charset Selection
  233. ~~~~~~~~~~~~~~~~~
  234. Most MySQL / MariaDB DBAPIs offer the option to set the client character set for
  235. a connection. This is typically delivered using the ``charset`` parameter
  236. in the URL, such as::
  237. e = create_engine(
  238. "mysql+pymysql://scott:tiger@localhost/test?charset=utf8mb4")
  239. This charset is the **client character set** for the connection. Some
  240. MySQL DBAPIs will default this to a value such as ``latin1``, and some
  241. will make use of the ``default-character-set`` setting in the ``my.cnf``
  242. file as well. Documentation for the DBAPI in use should be consulted
  243. for specific behavior.
  244. The encoding used for Unicode has traditionally been ``'utf8'``. However, for
  245. MySQL versions 5.5.3 and MariaDB 5.5 on forward, a new MySQL-specific encoding
  246. ``'utf8mb4'`` has been introduced, and as of MySQL 8.0 a warning is emitted by
  247. the server if plain ``utf8`` is specified within any server-side directives,
  248. replaced with ``utf8mb3``. The rationale for this new encoding is due to the
  249. fact that MySQL's legacy utf-8 encoding only supports codepoints up to three
  250. bytes instead of four. Therefore, when communicating with a MySQL or MariaDB
  251. database that includes codepoints more than three bytes in size, this new
  252. charset is preferred, if supported by both the database as well as the client
  253. DBAPI, as in::
  254. e = create_engine(
  255. "mysql+pymysql://scott:tiger@localhost/test?charset=utf8mb4")
  256. All modern DBAPIs should support the ``utf8mb4`` charset.
  257. In order to use ``utf8mb4`` encoding for a schema that was created with legacy
  258. ``utf8``, changes to the MySQL/MariaDB schema and/or server configuration may be
  259. required.
  260. .. seealso::
  261. `The utf8mb4 Character Set \
  262. <https://dev.mysql.com/doc/refman/5.5/en/charset-unicode-utf8mb4.html>`_ - \
  263. in the MySQL documentation
  264. .. _mysql_binary_introducer:
  265. Dealing with Binary Data Warnings and Unicode
  266. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  267. MySQL versions 5.6, 5.7 and later (not MariaDB at the time of this writing) now
  268. emit a warning when attempting to pass binary data to the database, while a
  269. character set encoding is also in place, when the binary data itself is not
  270. valid for that encoding::
  271. default.py:509: Warning: (1300, "Invalid utf8mb4 character string:
  272. 'F9876A'")
  273. cursor.execute(statement, parameters)
  274. This warning is due to the fact that the MySQL client library is attempting to
  275. interpret the binary string as a unicode object even if a datatype such
  276. as :class:`.LargeBinary` is in use. To resolve this, the SQL statement requires
  277. a binary "character set introducer" be present before any non-NULL value
  278. that renders like this::
  279. INSERT INTO table (data) VALUES (_binary %s)
  280. These character set introducers are provided by the DBAPI driver, assuming the
  281. use of mysqlclient or PyMySQL (both of which are recommended). Add the query
  282. string parameter ``binary_prefix=true`` to the URL to repair this warning::
  283. # mysqlclient
  284. engine = create_engine(
  285. "mysql+mysqldb://scott:tiger@localhost/test?charset=utf8mb4&binary_prefix=true")
  286. # PyMySQL
  287. engine = create_engine(
  288. "mysql+pymysql://scott:tiger@localhost/test?charset=utf8mb4&binary_prefix=true")
  289. The ``binary_prefix`` flag may or may not be supported by other MySQL drivers.
  290. SQLAlchemy itself cannot render this ``_binary`` prefix reliably, as it does
  291. not work with the NULL value, which is valid to be sent as a bound parameter.
  292. As the MySQL driver renders parameters directly into the SQL string, it's the
  293. most efficient place for this additional keyword to be passed.
  294. .. seealso::
  295. `Character set introducers <https://dev.mysql.com/doc/refman/5.7/en/charset-introducer.html>`_ - on the MySQL website
  296. ANSI Quoting Style
  297. ------------------
  298. MySQL / MariaDB feature two varieties of identifier "quoting style", one using
  299. backticks and the other using quotes, e.g. ```some_identifier``` vs.
  300. ``"some_identifier"``. All MySQL dialects detect which version
  301. is in use by checking the value of :ref:`sql_mode<mysql_sql_mode>` when a connection is first
  302. established with a particular :class:`_engine.Engine`.
  303. This quoting style comes
  304. into play when rendering table and column names as well as when reflecting
  305. existing database structures. The detection is entirely automatic and
  306. no special configuration is needed to use either quoting style.
  307. .. _mysql_sql_mode:
  308. Changing the sql_mode
  309. ---------------------
  310. MySQL supports operating in multiple
  311. `Server SQL Modes <https://dev.mysql.com/doc/refman/8.0/en/sql-mode.html>`_ for
  312. both Servers and Clients. To change the ``sql_mode`` for a given application, a
  313. developer can leverage SQLAlchemy's Events system.
  314. In the following example, the event system is used to set the ``sql_mode`` on
  315. the ``first_connect`` and ``connect`` events::
  316. from sqlalchemy import create_engine, event
  317. eng = create_engine("mysql://scott:tiger@localhost/test", echo='debug')
  318. # `insert=True` will ensure this is the very first listener to run
  319. @event.listens_for(eng, "connect", insert=True)
  320. def connect(dbapi_connection, connection_record):
  321. cursor = dbapi_connection.cursor()
  322. cursor.execute("SET sql_mode = 'STRICT_ALL_TABLES'")
  323. conn = eng.connect()
  324. In the example illustrated above, the "connect" event will invoke the "SET"
  325. statement on the connection at the moment a particular DBAPI connection is
  326. first created for a given Pool, before the connection is made available to the
  327. connection pool. Additionally, because the function was registered with
  328. ``insert=True``, it will be prepended to the internal list of registered
  329. functions.
  330. MySQL / MariaDB SQL Extensions
  331. ------------------------------
  332. Many of the MySQL / MariaDB SQL extensions are handled through SQLAlchemy's generic
  333. function and operator support::
  334. table.select(table.c.password==func.md5('plaintext'))
  335. table.select(table.c.username.op('regexp')('^[a-d]'))
  336. And of course any valid SQL statement can be executed as a string as well.
  337. Some limited direct support for MySQL / MariaDB extensions to SQL is currently
  338. available.
  339. * INSERT..ON DUPLICATE KEY UPDATE: See
  340. :ref:`mysql_insert_on_duplicate_key_update`
  341. * SELECT pragma, use :meth:`_expression.Select.prefix_with` and
  342. :meth:`_query.Query.prefix_with`::
  343. select(...).prefix_with(['HIGH_PRIORITY', 'SQL_SMALL_RESULT'])
  344. * UPDATE with LIMIT::
  345. update(..., mysql_limit=10, mariadb_limit=10)
  346. * optimizer hints, use :meth:`_expression.Select.prefix_with` and
  347. :meth:`_query.Query.prefix_with`::
  348. select(...).prefix_with("/*+ NO_RANGE_OPTIMIZATION(t4 PRIMARY) */")
  349. * index hints, use :meth:`_expression.Select.with_hint` and
  350. :meth:`_query.Query.with_hint`::
  351. select(...).with_hint(some_table, "USE INDEX xyz")
  352. * MATCH operator support::
  353. from sqlalchemy.dialects.mysql import match
  354. select(...).where(match(col1, col2, against="some expr").in_boolean_mode())
  355. .. seealso::
  356. :class:`_mysql.match`
  357. .. _mysql_insert_on_duplicate_key_update:
  358. INSERT...ON DUPLICATE KEY UPDATE (Upsert)
  359. ------------------------------------------
  360. MySQL / MariaDB allow "upserts" (update or insert)
  361. of rows into a table via the ``ON DUPLICATE KEY UPDATE`` clause of the
  362. ``INSERT`` statement. A candidate row will only be inserted if that row does
  363. not match an existing primary or unique key in the table; otherwise, an UPDATE
  364. will be performed. The statement allows for separate specification of the
  365. values to INSERT versus the values for UPDATE.
  366. SQLAlchemy provides ``ON DUPLICATE KEY UPDATE`` support via the MySQL-specific
  367. :func:`.mysql.insert()` function, which provides
  368. the generative method :meth:`~.mysql.Insert.on_duplicate_key_update`:
  369. .. sourcecode:: pycon+sql
  370. >>> from sqlalchemy.dialects.mysql import insert
  371. >>> insert_stmt = insert(my_table).values(
  372. ... id='some_existing_id',
  373. ... data='inserted value')
  374. >>> on_duplicate_key_stmt = insert_stmt.on_duplicate_key_update(
  375. ... data=insert_stmt.inserted.data,
  376. ... status='U'
  377. ... )
  378. >>> print(on_duplicate_key_stmt)
  379. {opensql}INSERT INTO my_table (id, data) VALUES (%s, %s)
  380. ON DUPLICATE KEY UPDATE data = VALUES(data), status = %s
  381. Unlike PostgreSQL's "ON CONFLICT" phrase, the "ON DUPLICATE KEY UPDATE"
  382. phrase will always match on any primary key or unique key, and will always
  383. perform an UPDATE if there's a match; there are no options for it to raise
  384. an error or to skip performing an UPDATE.
  385. ``ON DUPLICATE KEY UPDATE`` is used to perform an update of the already
  386. existing row, using any combination of new values as well as values
  387. from the proposed insertion. These values are normally specified using
  388. keyword arguments passed to the
  389. :meth:`_mysql.Insert.on_duplicate_key_update`
  390. given column key values (usually the name of the column, unless it
  391. specifies :paramref:`_schema.Column.key`
  392. ) as keys and literal or SQL expressions
  393. as values:
  394. .. sourcecode:: pycon+sql
  395. >>> insert_stmt = insert(my_table).values(
  396. ... id='some_existing_id',
  397. ... data='inserted value')
  398. >>> on_duplicate_key_stmt = insert_stmt.on_duplicate_key_update(
  399. ... data="some data",
  400. ... updated_at=func.current_timestamp(),
  401. ... )
  402. >>> print(on_duplicate_key_stmt)
  403. {opensql}INSERT INTO my_table (id, data) VALUES (%s, %s)
  404. ON DUPLICATE KEY UPDATE data = %s, updated_at = CURRENT_TIMESTAMP
  405. In a manner similar to that of :meth:`.UpdateBase.values`, other parameter
  406. forms are accepted, including a single dictionary:
  407. .. sourcecode:: pycon+sql
  408. >>> on_duplicate_key_stmt = insert_stmt.on_duplicate_key_update(
  409. ... {"data": "some data", "updated_at": func.current_timestamp()},
  410. ... )
  411. as well as a list of 2-tuples, which will automatically provide
  412. a parameter-ordered UPDATE statement in a manner similar to that described
  413. at :ref:`updates_order_parameters`. Unlike the :class:`_expression.Update`
  414. object,
  415. no special flag is needed to specify the intent since the argument form is
  416. this context is unambiguous:
  417. .. sourcecode:: pycon+sql
  418. >>> on_duplicate_key_stmt = insert_stmt.on_duplicate_key_update(
  419. ... [
  420. ... ("data", "some data"),
  421. ... ("updated_at", func.current_timestamp()),
  422. ... ]
  423. ... )
  424. >>> print(on_duplicate_key_stmt)
  425. {opensql}INSERT INTO my_table (id, data) VALUES (%s, %s)
  426. ON DUPLICATE KEY UPDATE data = %s, updated_at = CURRENT_TIMESTAMP
  427. .. versionchanged:: 1.3 support for parameter-ordered UPDATE clause within
  428. MySQL ON DUPLICATE KEY UPDATE
  429. .. warning::
  430. The :meth:`_mysql.Insert.on_duplicate_key_update`
  431. method does **not** take into
  432. account Python-side default UPDATE values or generation functions, e.g.
  433. e.g. those specified using :paramref:`_schema.Column.onupdate`.
  434. These values will not be exercised for an ON DUPLICATE KEY style of UPDATE,
  435. unless they are manually specified explicitly in the parameters.
  436. In order to refer to the proposed insertion row, the special alias
  437. :attr:`_mysql.Insert.inserted` is available as an attribute on
  438. the :class:`_mysql.Insert` object; this object is a
  439. :class:`_expression.ColumnCollection` which contains all columns of the target
  440. table:
  441. .. sourcecode:: pycon+sql
  442. >>> stmt = insert(my_table).values(
  443. ... id='some_id',
  444. ... data='inserted value',
  445. ... author='jlh')
  446. >>> do_update_stmt = stmt.on_duplicate_key_update(
  447. ... data="updated value",
  448. ... author=stmt.inserted.author
  449. ... )
  450. >>> print(do_update_stmt)
  451. {opensql}INSERT INTO my_table (id, data, author) VALUES (%s, %s, %s)
  452. ON DUPLICATE KEY UPDATE data = %s, author = VALUES(author)
  453. When rendered, the "inserted" namespace will produce the expression
  454. ``VALUES(<columnname>)``.
  455. .. versionadded:: 1.2 Added support for MySQL ON DUPLICATE KEY UPDATE clause
  456. rowcount Support
  457. ----------------
  458. SQLAlchemy standardizes the DBAPI ``cursor.rowcount`` attribute to be the
  459. usual definition of "number of rows matched by an UPDATE or DELETE" statement.
  460. This is in contradiction to the default setting on most MySQL DBAPI drivers,
  461. which is "number of rows actually modified/deleted". For this reason, the
  462. SQLAlchemy MySQL dialects always add the ``constants.CLIENT.FOUND_ROWS``
  463. flag, or whatever is equivalent for the target dialect, upon connection.
  464. This setting is currently hardcoded.
  465. .. seealso::
  466. :attr:`_engine.CursorResult.rowcount`
  467. .. _mysql_indexes:
  468. MySQL / MariaDB- Specific Index Options
  469. -----------------------------------------
  470. MySQL and MariaDB-specific extensions to the :class:`.Index` construct are available.
  471. Index Length
  472. ~~~~~~~~~~~~~
  473. MySQL and MariaDB both provide an option to create index entries with a certain length, where
  474. "length" refers to the number of characters or bytes in each value which will
  475. become part of the index. SQLAlchemy provides this feature via the
  476. ``mysql_length`` and/or ``mariadb_length`` parameters::
  477. Index('my_index', my_table.c.data, mysql_length=10, mariadb_length=10)
  478. Index('a_b_idx', my_table.c.a, my_table.c.b, mysql_length={'a': 4,
  479. 'b': 9})
  480. Index('a_b_idx', my_table.c.a, my_table.c.b, mariadb_length={'a': 4,
  481. 'b': 9})
  482. Prefix lengths are given in characters for nonbinary string types and in bytes
  483. for binary string types. The value passed to the keyword argument *must* be
  484. either an integer (and, thus, specify the same prefix length value for all
  485. columns of the index) or a dict in which keys are column names and values are
  486. prefix length values for corresponding columns. MySQL and MariaDB only allow a
  487. length for a column of an index if it is for a CHAR, VARCHAR, TEXT, BINARY,
  488. VARBINARY and BLOB.
  489. Index Prefixes
  490. ~~~~~~~~~~~~~~
  491. MySQL storage engines permit you to specify an index prefix when creating
  492. an index. SQLAlchemy provides this feature via the
  493. ``mysql_prefix`` parameter on :class:`.Index`::
  494. Index('my_index', my_table.c.data, mysql_prefix='FULLTEXT')
  495. The value passed to the keyword argument will be simply passed through to the
  496. underlying CREATE INDEX, so it *must* be a valid index prefix for your MySQL
  497. storage engine.
  498. .. versionadded:: 1.1.5
  499. .. seealso::
  500. `CREATE INDEX <https://dev.mysql.com/doc/refman/5.0/en/create-index.html>`_ - MySQL documentation
  501. Index Types
  502. ~~~~~~~~~~~~~
  503. Some MySQL storage engines permit you to specify an index type when creating
  504. an index or primary key constraint. SQLAlchemy provides this feature via the
  505. ``mysql_using`` parameter on :class:`.Index`::
  506. Index('my_index', my_table.c.data, mysql_using='hash', mariadb_using='hash')
  507. As well as the ``mysql_using`` parameter on :class:`.PrimaryKeyConstraint`::
  508. PrimaryKeyConstraint("data", mysql_using='hash', mariadb_using='hash')
  509. The value passed to the keyword argument will be simply passed through to the
  510. underlying CREATE INDEX or PRIMARY KEY clause, so it *must* be a valid index
  511. type for your MySQL storage engine.
  512. More information can be found at:
  513. https://dev.mysql.com/doc/refman/5.0/en/create-index.html
  514. https://dev.mysql.com/doc/refman/5.0/en/create-table.html
  515. Index Parsers
  516. ~~~~~~~~~~~~~
  517. CREATE FULLTEXT INDEX in MySQL also supports a "WITH PARSER" option. This
  518. is available using the keyword argument ``mysql_with_parser``::
  519. Index(
  520. 'my_index', my_table.c.data,
  521. mysql_prefix='FULLTEXT', mysql_with_parser="ngram",
  522. mariadb_prefix='FULLTEXT', mariadb_with_parser="ngram",
  523. )
  524. .. versionadded:: 1.3
  525. .. _mysql_foreign_keys:
  526. MySQL / MariaDB Foreign Keys
  527. -----------------------------
  528. MySQL and MariaDB's behavior regarding foreign keys has some important caveats.
  529. Foreign Key Arguments to Avoid
  530. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  531. Neither MySQL nor MariaDB support the foreign key arguments "DEFERRABLE", "INITIALLY",
  532. or "MATCH". Using the ``deferrable`` or ``initially`` keyword argument with
  533. :class:`_schema.ForeignKeyConstraint` or :class:`_schema.ForeignKey`
  534. will have the effect of
  535. these keywords being rendered in a DDL expression, which will then raise an
  536. error on MySQL or MariaDB. In order to use these keywords on a foreign key while having
  537. them ignored on a MySQL / MariaDB backend, use a custom compile rule::
  538. from sqlalchemy.ext.compiler import compiles
  539. from sqlalchemy.schema import ForeignKeyConstraint
  540. @compiles(ForeignKeyConstraint, "mysql", "mariadb")
  541. def process(element, compiler, **kw):
  542. element.deferrable = element.initially = None
  543. return compiler.visit_foreign_key_constraint(element, **kw)
  544. The "MATCH" keyword is in fact more insidious, and is explicitly disallowed
  545. by SQLAlchemy in conjunction with the MySQL or MariaDB backends. This argument is
  546. silently ignored by MySQL / MariaDB, but in addition has the effect of ON UPDATE and ON
  547. DELETE options also being ignored by the backend. Therefore MATCH should
  548. never be used with the MySQL / MariaDB backends; as is the case with DEFERRABLE and
  549. INITIALLY, custom compilation rules can be used to correct a
  550. ForeignKeyConstraint at DDL definition time.
  551. Reflection of Foreign Key Constraints
  552. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  553. Not all MySQL / MariaDB storage engines support foreign keys. When using the
  554. very common ``MyISAM`` MySQL storage engine, the information loaded by table
  555. reflection will not include foreign keys. For these tables, you may supply a
  556. :class:`~sqlalchemy.ForeignKeyConstraint` at reflection time::
  557. Table('mytable', metadata,
  558. ForeignKeyConstraint(['other_id'], ['othertable.other_id']),
  559. autoload_with=engine
  560. )
  561. .. seealso::
  562. :ref:`mysql_storage_engines`
  563. .. _mysql_unique_constraints:
  564. MySQL / MariaDB Unique Constraints and Reflection
  565. ----------------------------------------------------
  566. SQLAlchemy supports both the :class:`.Index` construct with the
  567. flag ``unique=True``, indicating a UNIQUE index, as well as the
  568. :class:`.UniqueConstraint` construct, representing a UNIQUE constraint.
  569. Both objects/syntaxes are supported by MySQL / MariaDB when emitting DDL to create
  570. these constraints. However, MySQL / MariaDB does not have a unique constraint
  571. construct that is separate from a unique index; that is, the "UNIQUE"
  572. constraint on MySQL / MariaDB is equivalent to creating a "UNIQUE INDEX".
  573. When reflecting these constructs, the
  574. :meth:`_reflection.Inspector.get_indexes`
  575. and the :meth:`_reflection.Inspector.get_unique_constraints`
  576. methods will **both**
  577. return an entry for a UNIQUE index in MySQL / MariaDB. However, when performing
  578. full table reflection using ``Table(..., autoload_with=engine)``,
  579. the :class:`.UniqueConstraint` construct is
  580. **not** part of the fully reflected :class:`_schema.Table` construct under any
  581. circumstances; this construct is always represented by a :class:`.Index`
  582. with the ``unique=True`` setting present in the :attr:`_schema.Table.indexes`
  583. collection.
  584. TIMESTAMP / DATETIME issues
  585. ---------------------------
  586. .. _mysql_timestamp_onupdate:
  587. Rendering ON UPDATE CURRENT TIMESTAMP for MySQL / MariaDB's explicit_defaults_for_timestamp
  588. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  589. MySQL / MariaDB have historically expanded the DDL for the :class:`_types.TIMESTAMP`
  590. datatype into the phrase "TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE
  591. CURRENT_TIMESTAMP", which includes non-standard SQL that automatically updates
  592. the column with the current timestamp when an UPDATE occurs, eliminating the
  593. usual need to use a trigger in such a case where server-side update changes are
  594. desired.
  595. MySQL 5.6 introduced a new flag `explicit_defaults_for_timestamp
  596. <https://dev.mysql.com/doc/refman/5.6/en/server-system-variables.html
  597. #sysvar_explicit_defaults_for_timestamp>`_ which disables the above behavior,
  598. and in MySQL 8 this flag defaults to true, meaning in order to get a MySQL
  599. "on update timestamp" without changing this flag, the above DDL must be
  600. rendered explicitly. Additionally, the same DDL is valid for use of the
  601. ``DATETIME`` datatype as well.
  602. SQLAlchemy's MySQL dialect does not yet have an option to generate
  603. MySQL's "ON UPDATE CURRENT_TIMESTAMP" clause, noting that this is not a general
  604. purpose "ON UPDATE" as there is no such syntax in standard SQL. SQLAlchemy's
  605. :paramref:`_schema.Column.server_onupdate` parameter is currently not related
  606. to this special MySQL behavior.
  607. To generate this DDL, make use of the :paramref:`_schema.Column.server_default`
  608. parameter and pass a textual clause that also includes the ON UPDATE clause::
  609. from sqlalchemy import Table, MetaData, Column, Integer, String, TIMESTAMP
  610. from sqlalchemy import text
  611. metadata = MetaData()
  612. mytable = Table(
  613. "mytable",
  614. metadata,
  615. Column('id', Integer, primary_key=True),
  616. Column('data', String(50)),
  617. Column(
  618. 'last_updated',
  619. TIMESTAMP,
  620. server_default=text("CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP")
  621. )
  622. )
  623. The same instructions apply to use of the :class:`_types.DateTime` and
  624. :class:`_types.DATETIME` datatypes::
  625. from sqlalchemy import DateTime
  626. mytable = Table(
  627. "mytable",
  628. metadata,
  629. Column('id', Integer, primary_key=True),
  630. Column('data', String(50)),
  631. Column(
  632. 'last_updated',
  633. DateTime,
  634. server_default=text("CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP")
  635. )
  636. )
  637. Even though the :paramref:`_schema.Column.server_onupdate` feature does not
  638. generate this DDL, it still may be desirable to signal to the ORM that this
  639. updated value should be fetched. This syntax looks like the following::
  640. from sqlalchemy.schema import FetchedValue
  641. class MyClass(Base):
  642. __tablename__ = 'mytable'
  643. id = Column(Integer, primary_key=True)
  644. data = Column(String(50))
  645. last_updated = Column(
  646. TIMESTAMP,
  647. server_default=text("CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP"),
  648. server_onupdate=FetchedValue()
  649. )
  650. .. _mysql_timestamp_null:
  651. TIMESTAMP Columns and NULL
  652. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  653. MySQL historically enforces that a column which specifies the
  654. TIMESTAMP datatype implicitly includes a default value of
  655. CURRENT_TIMESTAMP, even though this is not stated, and additionally
  656. sets the column as NOT NULL, the opposite behavior vs. that of all
  657. other datatypes::
  658. mysql> CREATE TABLE ts_test (
  659. -> a INTEGER,
  660. -> b INTEGER NOT NULL,
  661. -> c TIMESTAMP,
  662. -> d TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  663. -> e TIMESTAMP NULL);
  664. Query OK, 0 rows affected (0.03 sec)
  665. mysql> SHOW CREATE TABLE ts_test;
  666. +---------+-----------------------------------------------------
  667. | Table | Create Table
  668. +---------+-----------------------------------------------------
  669. | ts_test | CREATE TABLE `ts_test` (
  670. `a` int(11) DEFAULT NULL,
  671. `b` int(11) NOT NULL,
  672. `c` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  673. `d` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  674. `e` timestamp NULL DEFAULT NULL
  675. ) ENGINE=MyISAM DEFAULT CHARSET=latin1
  676. Above, we see that an INTEGER column defaults to NULL, unless it is specified
  677. with NOT NULL. But when the column is of type TIMESTAMP, an implicit
  678. default of CURRENT_TIMESTAMP is generated which also coerces the column
  679. to be a NOT NULL, even though we did not specify it as such.
  680. This behavior of MySQL can be changed on the MySQL side using the
  681. `explicit_defaults_for_timestamp
  682. <https://dev.mysql.com/doc/refman/5.6/en/server-system-variables.html
  683. #sysvar_explicit_defaults_for_timestamp>`_ configuration flag introduced in
  684. MySQL 5.6. With this server setting enabled, TIMESTAMP columns behave like
  685. any other datatype on the MySQL side with regards to defaults and nullability.
  686. However, to accommodate the vast majority of MySQL databases that do not
  687. specify this new flag, SQLAlchemy emits the "NULL" specifier explicitly with
  688. any TIMESTAMP column that does not specify ``nullable=False``. In order to
  689. accommodate newer databases that specify ``explicit_defaults_for_timestamp``,
  690. SQLAlchemy also emits NOT NULL for TIMESTAMP columns that do specify
  691. ``nullable=False``. The following example illustrates::
  692. from sqlalchemy import MetaData, Integer, Table, Column, text
  693. from sqlalchemy.dialects.mysql import TIMESTAMP
  694. m = MetaData()
  695. t = Table('ts_test', m,
  696. Column('a', Integer),
  697. Column('b', Integer, nullable=False),
  698. Column('c', TIMESTAMP),
  699. Column('d', TIMESTAMP, nullable=False)
  700. )
  701. from sqlalchemy import create_engine
  702. e = create_engine("mysql://scott:tiger@localhost/test", echo=True)
  703. m.create_all(e)
  704. output::
  705. CREATE TABLE ts_test (
  706. a INTEGER,
  707. b INTEGER NOT NULL,
  708. c TIMESTAMP NULL,
  709. d TIMESTAMP NOT NULL
  710. )
  711. .. versionchanged:: 1.0.0 - SQLAlchemy now renders NULL or NOT NULL in all
  712. cases for TIMESTAMP columns, to accommodate
  713. ``explicit_defaults_for_timestamp``. Prior to this version, it will
  714. not render "NOT NULL" for a TIMESTAMP column that is ``nullable=False``.
  715. """ # noqa
  716. from array import array as _array
  717. from collections import defaultdict
  718. from itertools import compress
  719. import re
  720. from sqlalchemy import literal_column
  721. from sqlalchemy import text
  722. from sqlalchemy.sql import visitors
  723. from . import reflection as _reflection
  724. from .enumerated import ENUM
  725. from .enumerated import SET
  726. from .json import JSON
  727. from .json import JSONIndexType
  728. from .json import JSONPathType
  729. from .reserved_words import RESERVED_WORDS_MARIADB
  730. from .reserved_words import RESERVED_WORDS_MYSQL
  731. from .types import _FloatType
  732. from .types import _IntegerType
  733. from .types import _MatchType
  734. from .types import _NumericType
  735. from .types import _StringType
  736. from .types import BIGINT
  737. from .types import BIT
  738. from .types import CHAR
  739. from .types import DATETIME
  740. from .types import DECIMAL
  741. from .types import DOUBLE
  742. from .types import FLOAT
  743. from .types import INTEGER
  744. from .types import LONGBLOB
  745. from .types import LONGTEXT
  746. from .types import MEDIUMBLOB
  747. from .types import MEDIUMINT
  748. from .types import MEDIUMTEXT
  749. from .types import NCHAR
  750. from .types import NUMERIC
  751. from .types import NVARCHAR
  752. from .types import REAL
  753. from .types import SMALLINT
  754. from .types import TEXT
  755. from .types import TIME
  756. from .types import TIMESTAMP
  757. from .types import TINYBLOB
  758. from .types import TINYINT
  759. from .types import TINYTEXT
  760. from .types import VARCHAR
  761. from .types import YEAR
  762. from ... import exc
  763. from ... import log
  764. from ... import schema as sa_schema
  765. from ... import sql
  766. from ... import types as sqltypes
  767. from ... import util
  768. from ...engine import default
  769. from ...engine import reflection
  770. from ...sql import coercions
  771. from ...sql import compiler
  772. from ...sql import elements
  773. from ...sql import functions
  774. from ...sql import operators
  775. from ...sql import roles
  776. from ...sql import util as sql_util
  777. from ...sql.sqltypes import Unicode
  778. from ...types import BINARY
  779. from ...types import BLOB
  780. from ...types import BOOLEAN
  781. from ...types import DATE
  782. from ...types import VARBINARY
  783. from ...util import topological
  784. AUTOCOMMIT_RE = re.compile(
  785. r"\s*(?:UPDATE|INSERT|CREATE|DELETE|DROP|ALTER|LOAD +DATA|REPLACE)",
  786. re.I | re.UNICODE,
  787. )
  788. SET_RE = re.compile(
  789. r"\s*SET\s+(?:(?:GLOBAL|SESSION)\s+)?\w", re.I | re.UNICODE
  790. )
  791. # old names
  792. MSTime = TIME
  793. MSSet = SET
  794. MSEnum = ENUM
  795. MSLongBlob = LONGBLOB
  796. MSMediumBlob = MEDIUMBLOB
  797. MSTinyBlob = TINYBLOB
  798. MSBlob = BLOB
  799. MSBinary = BINARY
  800. MSVarBinary = VARBINARY
  801. MSNChar = NCHAR
  802. MSNVarChar = NVARCHAR
  803. MSChar = CHAR
  804. MSString = VARCHAR
  805. MSLongText = LONGTEXT
  806. MSMediumText = MEDIUMTEXT
  807. MSTinyText = TINYTEXT
  808. MSText = TEXT
  809. MSYear = YEAR
  810. MSTimeStamp = TIMESTAMP
  811. MSBit = BIT
  812. MSSmallInteger = SMALLINT
  813. MSTinyInteger = TINYINT
  814. MSMediumInteger = MEDIUMINT
  815. MSBigInteger = BIGINT
  816. MSNumeric = NUMERIC
  817. MSDecimal = DECIMAL
  818. MSDouble = DOUBLE
  819. MSReal = REAL
  820. MSFloat = FLOAT
  821. MSInteger = INTEGER
  822. colspecs = {
  823. _IntegerType: _IntegerType,
  824. _NumericType: _NumericType,
  825. _FloatType: _FloatType,
  826. sqltypes.Numeric: NUMERIC,
  827. sqltypes.Float: FLOAT,
  828. sqltypes.Time: TIME,
  829. sqltypes.Enum: ENUM,
  830. sqltypes.MatchType: _MatchType,
  831. sqltypes.JSON: JSON,
  832. sqltypes.JSON.JSONIndexType: JSONIndexType,
  833. sqltypes.JSON.JSONPathType: JSONPathType,
  834. }
  835. # Everything 3.23 through 5.1 excepting OpenGIS types.
  836. ischema_names = {
  837. "bigint": BIGINT,
  838. "binary": BINARY,
  839. "bit": BIT,
  840. "blob": BLOB,
  841. "boolean": BOOLEAN,
  842. "char": CHAR,
  843. "date": DATE,
  844. "datetime": DATETIME,
  845. "decimal": DECIMAL,
  846. "double": DOUBLE,
  847. "enum": ENUM,
  848. "fixed": DECIMAL,
  849. "float": FLOAT,
  850. "int": INTEGER,
  851. "integer": INTEGER,
  852. "json": JSON,
  853. "longblob": LONGBLOB,
  854. "longtext": LONGTEXT,
  855. "mediumblob": MEDIUMBLOB,
  856. "mediumint": MEDIUMINT,
  857. "mediumtext": MEDIUMTEXT,
  858. "nchar": NCHAR,
  859. "nvarchar": NVARCHAR,
  860. "numeric": NUMERIC,
  861. "set": SET,
  862. "smallint": SMALLINT,
  863. "text": TEXT,
  864. "time": TIME,
  865. "timestamp": TIMESTAMP,
  866. "tinyblob": TINYBLOB,
  867. "tinyint": TINYINT,
  868. "tinytext": TINYTEXT,
  869. "varbinary": VARBINARY,
  870. "varchar": VARCHAR,
  871. "year": YEAR,
  872. }
  873. class MySQLExecutionContext(default.DefaultExecutionContext):
  874. def should_autocommit_text(self, statement):
  875. return AUTOCOMMIT_RE.match(statement)
  876. def create_server_side_cursor(self):
  877. if self.dialect.supports_server_side_cursors:
  878. return self._dbapi_connection.cursor(self.dialect._sscursor)
  879. else:
  880. raise NotImplementedError()
  881. def fire_sequence(self, seq, type_):
  882. return self._execute_scalar(
  883. (
  884. "select nextval(%s)"
  885. % self.identifier_preparer.format_sequence(seq)
  886. ),
  887. type_,
  888. )
  889. class MySQLCompiler(compiler.SQLCompiler):
  890. render_table_with_column_in_update_from = True
  891. """Overridden from base SQLCompiler value"""
  892. extract_map = compiler.SQLCompiler.extract_map.copy()
  893. extract_map.update({"milliseconds": "millisecond"})
  894. def default_from(self):
  895. """Called when a ``SELECT`` statement has no froms,
  896. and no ``FROM`` clause is to be appended.
  897. """
  898. if self.stack:
  899. stmt = self.stack[-1]["selectable"]
  900. if stmt._where_criteria:
  901. return " FROM DUAL"
  902. return ""
  903. def visit_random_func(self, fn, **kw):
  904. return "rand%s" % self.function_argspec(fn)
  905. def visit_sequence(self, seq, **kw):
  906. return "nextval(%s)" % self.preparer.format_sequence(seq)
  907. def visit_sysdate_func(self, fn, **kw):
  908. return "SYSDATE()"
  909. def _render_json_extract_from_binary(self, binary, operator, **kw):
  910. # note we are intentionally calling upon the process() calls in the
  911. # order in which they appear in the SQL String as this is used
  912. # by positional parameter rendering
  913. if binary.type._type_affinity is sqltypes.JSON:
  914. return "JSON_EXTRACT(%s, %s)" % (
  915. self.process(binary.left, **kw),
  916. self.process(binary.right, **kw),
  917. )
  918. # for non-JSON, MySQL doesn't handle JSON null at all so it has to
  919. # be explicit
  920. case_expression = "CASE JSON_EXTRACT(%s, %s) WHEN 'null' THEN NULL" % (
  921. self.process(binary.left, **kw),
  922. self.process(binary.right, **kw),
  923. )
  924. if binary.type._type_affinity is sqltypes.Integer:
  925. type_expression = (
  926. "ELSE CAST(JSON_EXTRACT(%s, %s) AS SIGNED INTEGER)"
  927. % (
  928. self.process(binary.left, **kw),
  929. self.process(binary.right, **kw),
  930. )
  931. )
  932. elif binary.type._type_affinity is sqltypes.Numeric:
  933. if (
  934. binary.type.scale is not None
  935. and binary.type.precision is not None
  936. ):
  937. # using DECIMAL here because MySQL does not recognize NUMERIC
  938. type_expression = (
  939. "ELSE CAST(JSON_EXTRACT(%s, %s) AS DECIMAL(%s, %s))"
  940. % (
  941. self.process(binary.left, **kw),
  942. self.process(binary.right, **kw),
  943. binary.type.precision,
  944. binary.type.scale,
  945. )
  946. )
  947. else:
  948. # FLOAT / REAL not added in MySQL til 8.0.17
  949. type_expression = (
  950. "ELSE JSON_EXTRACT(%s, %s)+0.0000000000000000000000"
  951. % (
  952. self.process(binary.left, **kw),
  953. self.process(binary.right, **kw),
  954. )
  955. )
  956. elif binary.type._type_affinity is sqltypes.Boolean:
  957. # the NULL handling is particularly weird with boolean, so
  958. # explicitly return true/false constants
  959. type_expression = "WHEN true THEN true ELSE false"
  960. elif binary.type._type_affinity is sqltypes.String:
  961. # (gord): this fails with a JSON value that's a four byte unicode
  962. # string. SQLite has the same problem at the moment
  963. # (zzzeek): I'm not really sure. let's take a look at a test case
  964. # that hits each backend and maybe make a requires rule for it?
  965. type_expression = "ELSE JSON_UNQUOTE(JSON_EXTRACT(%s, %s))" % (
  966. self.process(binary.left, **kw),
  967. self.process(binary.right, **kw),
  968. )
  969. else:
  970. # other affinity....this is not expected right now
  971. type_expression = "ELSE JSON_EXTRACT(%s, %s)" % (
  972. self.process(binary.left, **kw),
  973. self.process(binary.right, **kw),
  974. )
  975. return case_expression + " " + type_expression + " END"
  976. def visit_json_getitem_op_binary(self, binary, operator, **kw):
  977. return self._render_json_extract_from_binary(binary, operator, **kw)
  978. def visit_json_path_getitem_op_binary(self, binary, operator, **kw):
  979. return self._render_json_extract_from_binary(binary, operator, **kw)
  980. def visit_on_duplicate_key_update(self, on_duplicate, **kw):
  981. statement = self.current_executable
  982. if on_duplicate._parameter_ordering:
  983. parameter_ordering = [
  984. coercions.expect(roles.DMLColumnRole, key)
  985. for key in on_duplicate._parameter_ordering
  986. ]
  987. ordered_keys = set(parameter_ordering)
  988. cols = [
  989. statement.table.c[key]
  990. for key in parameter_ordering
  991. if key in statement.table.c
  992. ] + [c for c in statement.table.c if c.key not in ordered_keys]
  993. else:
  994. cols = statement.table.c
  995. clauses = []
  996. # traverses through all table columns to preserve table column order
  997. for column in (col for col in cols if col.key in on_duplicate.update):
  998. val = on_duplicate.update[column.key]
  999. if coercions._is_literal(val):
  1000. val = elements.BindParameter(None, val, type_=column.type)
  1001. value_text = self.process(val.self_group(), use_schema=False)
  1002. else:
  1003. def replace(obj):
  1004. if (
  1005. isinstance(obj, elements.BindParameter)
  1006. and obj.type._isnull
  1007. ):
  1008. obj = obj._clone()
  1009. obj.type = column.type
  1010. return obj
  1011. elif (
  1012. isinstance(obj, elements.ColumnClause)
  1013. and obj.table is on_duplicate.inserted_alias
  1014. ):
  1015. obj = literal_column(
  1016. "VALUES(" + self.preparer.quote(obj.name) + ")"
  1017. )
  1018. return obj
  1019. else:
  1020. # element is not replaced
  1021. return None
  1022. val = visitors.replacement_traverse(val, {}, replace)
  1023. value_text = self.process(val.self_group(), use_schema=False)
  1024. name_text = self.preparer.quote(column.name)
  1025. clauses.append("%s = %s" % (name_text, value_text))
  1026. non_matching = set(on_duplicate.update) - set(c.key for c in cols)
  1027. if non_matching:
  1028. util.warn(
  1029. "Additional column names not matching "
  1030. "any column keys in table '%s': %s"
  1031. % (
  1032. self.statement.table.name,
  1033. (", ".join("'%s'" % c for c in non_matching)),
  1034. )
  1035. )
  1036. return "ON DUPLICATE KEY UPDATE " + ", ".join(clauses)
  1037. def visit_concat_op_binary(self, binary, operator, **kw):
  1038. return "concat(%s, %s)" % (
  1039. self.process(binary.left, **kw),
  1040. self.process(binary.right, **kw),
  1041. )
  1042. _match_valid_flag_combinations = frozenset(
  1043. (
  1044. # (boolean_mode, natural_language, query_expansion)
  1045. (False, False, False),
  1046. (True, False, False),
  1047. (False, True, False),
  1048. (False, False, True),
  1049. (False, True, True),
  1050. )
  1051. )
  1052. _match_flag_expressions = (
  1053. "IN BOOLEAN MODE",
  1054. "IN NATURAL LANGUAGE MODE",
  1055. "WITH QUERY EXPANSION",
  1056. )
  1057. def visit_mysql_match(self, element, **kw):
  1058. return self.visit_match_op_binary(element, element.operator, **kw)
  1059. def visit_match_op_binary(self, binary, operator, **kw):
  1060. """
  1061. Note that `mysql_boolean_mode` is enabled by default because of
  1062. backward compatibility
  1063. """
  1064. modifiers = binary.modifiers
  1065. boolean_mode = modifiers.get("mysql_boolean_mode", True)
  1066. natural_language = modifiers.get("mysql_natural_language", False)
  1067. query_expansion = modifiers.get("mysql_query_expansion", False)
  1068. flag_combination = (boolean_mode, natural_language, query_expansion)
  1069. if flag_combination not in self._match_valid_flag_combinations:
  1070. flags = (
  1071. "in_boolean_mode=%s" % boolean_mode,
  1072. "in_natural_language_mode=%s" % natural_language,
  1073. "with_query_expansion=%s" % query_expansion,
  1074. )
  1075. flags = ", ".join(flags)
  1076. raise exc.CompileError("Invalid MySQL match flags: %s" % flags)
  1077. match_clause = binary.left
  1078. match_clause = self.process(match_clause, **kw)
  1079. against_clause = self.process(binary.right, **kw)
  1080. if any(flag_combination):
  1081. flag_expressions = compress(
  1082. self._match_flag_expressions,
  1083. flag_combination,
  1084. )
  1085. against_clause = [against_clause]
  1086. against_clause.extend(flag_expressions)
  1087. against_clause = " ".join(against_clause)
  1088. return "MATCH (%s) AGAINST (%s)" % (match_clause, against_clause)
  1089. def get_from_hint_text(self, table, text):
  1090. return text
  1091. def visit_typeclause(self, typeclause, type_=None, **kw):
  1092. if type_ is None:
  1093. type_ = typeclause.type.dialect_impl(self.dialect)
  1094. if isinstance(type_, sqltypes.TypeDecorator):
  1095. return self.visit_typeclause(typeclause, type_.impl, **kw)
  1096. elif isinstance(type_, sqltypes.Integer):
  1097. if getattr(type_, "unsigned", False):
  1098. return "UNSIGNED INTEGER"
  1099. else:
  1100. return "SIGNED INTEGER"
  1101. elif isinstance(type_, sqltypes.TIMESTAMP):
  1102. return "DATETIME"
  1103. elif isinstance(
  1104. type_,
  1105. (
  1106. sqltypes.DECIMAL,
  1107. sqltypes.DateTime,
  1108. sqltypes.Date,
  1109. sqltypes.Time,
  1110. ),
  1111. ):
  1112. return self.dialect.type_compiler.process(type_)
  1113. elif isinstance(type_, sqltypes.String) and not isinstance(
  1114. type_, (ENUM, SET)
  1115. ):
  1116. adapted = CHAR._adapt_string_for_cast(type_)
  1117. return self.dialect.type_compiler.process(adapted)
  1118. elif isinstance(type_, sqltypes._Binary):
  1119. return "BINARY"
  1120. elif isinstance(type_, sqltypes.JSON):
  1121. return "JSON"
  1122. elif isinstance(type_, sqltypes.NUMERIC):
  1123. return self.dialect.type_compiler.process(type_).replace(
  1124. "NUMERIC", "DECIMAL"
  1125. )
  1126. elif (
  1127. isinstance(type_, sqltypes.Float)
  1128. and self.dialect._support_float_cast
  1129. ):
  1130. return self.dialect.type_compiler.process(type_)
  1131. else:
  1132. return None
  1133. def visit_cast(self, cast, **kw):
  1134. type_ = self.process(cast.typeclause)
  1135. if type_ is None:
  1136. util.warn(
  1137. "Datatype %s does not support CAST on MySQL/MariaDb; "
  1138. "the CAST will be skipped."
  1139. % self.dialect.type_compiler.process(cast.typeclause.type)
  1140. )
  1141. return self.process(cast.clause.self_group(), **kw)
  1142. return "CAST(%s AS %s)" % (self.process(cast.clause, **kw), type_)
  1143. def render_literal_value(self, value, type_):
  1144. value = super(MySQLCompiler, self).render_literal_value(value, type_)
  1145. if self.dialect._backslash_escapes:
  1146. value = value.replace("\\", "\\\\")
  1147. return value
  1148. # override native_boolean=False behavior here, as
  1149. # MySQL still supports native boolean
  1150. def visit_true(self, element, **kw):
  1151. return "true"
  1152. def visit_false(self, element, **kw):
  1153. return "false"
  1154. def get_select_precolumns(self, select, **kw):
  1155. """Add special MySQL keywords in place of DISTINCT.
  1156. .. deprecated 1.4:: this usage is deprecated.
  1157. :meth:`_expression.Select.prefix_with` should be used for special
  1158. keywords at the start of a SELECT.
  1159. """
  1160. if isinstance(select._distinct, util.string_types):
  1161. util.warn_deprecated(
  1162. "Sending string values for 'distinct' is deprecated in the "
  1163. "MySQL dialect and will be removed in a future release. "
  1164. "Please use :meth:`.Select.prefix_with` for special keywords "
  1165. "at the start of a SELECT statement",
  1166. version="1.4",
  1167. )
  1168. return select._distinct.upper() + " "
  1169. return super(MySQLCompiler, self).get_select_precolumns(select, **kw)
  1170. def visit_join(self, join, asfrom=False, from_linter=None, **kwargs):
  1171. if from_linter:
  1172. from_linter.edges.add((join.left, join.right))
  1173. if join.full:
  1174. join_type = " FULL OUTER JOIN "
  1175. elif join.isouter:
  1176. join_type = " LEFT OUTER JOIN "
  1177. else:
  1178. join_type = " INNER JOIN "
  1179. return "".join(
  1180. (
  1181. self.process(
  1182. join.left, asfrom=True, from_linter=from_linter, **kwargs
  1183. ),
  1184. join_type,
  1185. self.process(
  1186. join.right, asfrom=True, from_linter=from_linter, **kwargs
  1187. ),
  1188. " ON ",
  1189. self.process(join.onclause, from_linter=from_linter, **kwargs),
  1190. )
  1191. )
  1192. def for_update_clause(self, select, **kw):
  1193. if select._for_update_arg.read:
  1194. tmp = " LOCK IN SHARE MODE"
  1195. else:
  1196. tmp = " FOR UPDATE"
  1197. if select._for_update_arg.of and self.dialect.supports_for_update_of:
  1198. tables = util.OrderedSet()
  1199. for c in select._for_update_arg.of:
  1200. tables.update(sql_util.surface_selectables_only(c))
  1201. tmp += " OF " + ", ".join(
  1202. self.process(table, ashint=True, use_schema=False, **kw)
  1203. for table in tables
  1204. )
  1205. if select._for_update_arg.nowait:
  1206. tmp += " NOWAIT"
  1207. if select._for_update_arg.skip_locked:
  1208. tmp += " SKIP LOCKED"
  1209. return tmp
  1210. def limit_clause(self, select, **kw):
  1211. # MySQL supports:
  1212. # LIMIT <limit>
  1213. # LIMIT <offset>, <limit>
  1214. # and in server versions > 3.3:
  1215. # LIMIT <limit> OFFSET <offset>
  1216. # The latter is more readable for offsets but we're stuck with the
  1217. # former until we can refine dialects by server revision.
  1218. limit_clause, offset_clause = (
  1219. select._limit_clause,
  1220. select._offset_clause,
  1221. )
  1222. if limit_clause is None and offset_clause is None:
  1223. return ""
  1224. elif offset_clause is not None:
  1225. # As suggested by the MySQL docs, need to apply an
  1226. # artificial limit if one wasn't provided
  1227. # https://dev.mysql.com/doc/refman/5.0/en/select.html
  1228. if limit_clause is None:
  1229. # hardwire the upper limit. Currently
  1230. # needed by OurSQL with Python 3
  1231. # (https://bugs.launchpad.net/oursql/+bug/686232),
  1232. # but also is consistent with the usage of the upper
  1233. # bound as part of MySQL's "syntax" for OFFSET with
  1234. # no LIMIT
  1235. return " \n LIMIT %s, %s" % (
  1236. self.process(offset_clause, **kw),
  1237. "18446744073709551615",
  1238. )
  1239. else:
  1240. return " \n LIMIT %s, %s" % (
  1241. self.process(offset_clause, **kw),
  1242. self.process(limit_clause, **kw),
  1243. )
  1244. else:
  1245. # No offset provided, so just use the limit
  1246. return " \n LIMIT %s" % (self.process(limit_clause, **kw),)
  1247. def update_limit_clause(self, update_stmt):
  1248. limit = update_stmt.kwargs.get("%s_limit" % self.dialect.name, None)
  1249. if limit:
  1250. return "LIMIT %s" % limit
  1251. else:
  1252. return None
  1253. def update_tables_clause(self, update_stmt, from_table, extra_froms, **kw):
  1254. kw["asfrom"] = True
  1255. return ", ".join(
  1256. t._compiler_dispatch(self, **kw)
  1257. for t in [from_table] + list(extra_froms)
  1258. )
  1259. def update_from_clause(
  1260. self, update_stmt, from_table, extra_froms, from_hints, **kw
  1261. ):
  1262. return None
  1263. def delete_table_clause(self, delete_stmt, from_table, extra_froms):
  1264. """If we have extra froms make sure we render any alias as hint."""
  1265. ashint = False
  1266. if extra_froms:
  1267. ashint = True
  1268. return from_table._compiler_dispatch(
  1269. self, asfrom=True, iscrud=True, ashint=ashint
  1270. )
  1271. def delete_extra_from_clause(
  1272. self, delete_stmt, from_table, extra_froms, from_hints, **kw
  1273. ):
  1274. """Render the DELETE .. USING clause specific to MySQL."""
  1275. kw["asfrom"] = True
  1276. return "USING " + ", ".join(
  1277. t._compiler_dispatch(self, fromhints=from_hints, **kw)
  1278. for t in [from_table] + extra_froms
  1279. )
  1280. def visit_empty_set_expr(self, element_types):
  1281. return (
  1282. "SELECT %(outer)s FROM (SELECT %(inner)s) "
  1283. "as _empty_set WHERE 1!=1"
  1284. % {
  1285. "inner": ", ".join(
  1286. "1 AS _in_%s" % idx
  1287. for idx, type_ in enumerate(element_types)
  1288. ),
  1289. "outer": ", ".join(
  1290. "_in_%s" % idx for idx, type_ in enumerate(element_types)
  1291. ),
  1292. }
  1293. )
  1294. def visit_is_distinct_from_binary(self, binary, operator, **kw):
  1295. return "NOT (%s <=> %s)" % (
  1296. self.process(binary.left),
  1297. self.process(binary.right),
  1298. )
  1299. def visit_is_not_distinct_from_binary(self, binary, operator, **kw):
  1300. return "%s <=> %s" % (
  1301. self.process(binary.left),
  1302. self.process(binary.right),
  1303. )
  1304. def _mariadb_regexp_flags(self, flags, pattern, **kw):
  1305. return "CONCAT('(?', %s, ')', %s)" % (
  1306. self.process(flags, **kw),
  1307. self.process(pattern, **kw),
  1308. )
  1309. def _regexp_match(self, op_string, binary, operator, **kw):
  1310. flags = binary.modifiers["flags"]
  1311. if flags is None:
  1312. return self._generate_generic_binary(binary, op_string, **kw)
  1313. elif self.dialect.is_mariadb:
  1314. return "%s%s%s" % (
  1315. self.process(binary.left, **kw),
  1316. op_string,
  1317. self._mariadb_regexp_flags(flags, binary.right),
  1318. )
  1319. else:
  1320. text = "REGEXP_LIKE(%s, %s, %s)" % (
  1321. self.process(binary.left, **kw),
  1322. self.process(binary.right, **kw),
  1323. self.process(flags, **kw),
  1324. )
  1325. if op_string == " NOT REGEXP ":
  1326. return "NOT %s" % text
  1327. else:
  1328. return text
  1329. def visit_regexp_match_op_binary(self, binary, operator, **kw):
  1330. return self._regexp_match(" REGEXP ", binary, operator, **kw)
  1331. def visit_not_regexp_match_op_binary(self, binary, operator, **kw):
  1332. return self._regexp_match(" NOT REGEXP ", binary, operator, **kw)
  1333. def visit_regexp_replace_op_binary(self, binary, operator, **kw):
  1334. flags = binary.modifiers["flags"]
  1335. replacement = binary.modifiers["replacement"]
  1336. if flags is None:
  1337. return "REGEXP_REPLACE(%s, %s, %s)" % (
  1338. self.process(binary.left, **kw),
  1339. self.process(binary.right, **kw),
  1340. self.process(replacement, **kw),
  1341. )
  1342. elif self.dialect.is_mariadb:
  1343. return "REGEXP_REPLACE(%s, %s, %s)" % (
  1344. self.process(binary.left, **kw),
  1345. self._mariadb_regexp_flags(flags, binary.right),
  1346. self.process(replacement, **kw),
  1347. )
  1348. else:
  1349. return "REGEXP_REPLACE(%s, %s, %s, %s)" % (
  1350. self.process(binary.left, **kw),
  1351. self.process(binary.right, **kw),
  1352. self.process(replacement, **kw),
  1353. self.process(flags, **kw),
  1354. )
  1355. class MySQLDDLCompiler(compiler.DDLCompiler):
  1356. def get_column_specification(self, column, **kw):
  1357. """Builds column DDL."""
  1358. colspec = [
  1359. self.preparer.format_column(column),
  1360. self.dialect.type_compiler.process(
  1361. column.type, type_expression=column
  1362. ),
  1363. ]
  1364. if column.computed is not None:
  1365. colspec.append(self.process(column.computed))
  1366. is_timestamp = isinstance(
  1367. column.type._unwrapped_dialect_impl(self.dialect),
  1368. sqltypes.TIMESTAMP,
  1369. )
  1370. if not column.nullable:
  1371. colspec.append("NOT NULL")
  1372. # see: https://docs.sqlalchemy.org/en/latest/dialects/mysql.html#mysql_timestamp_null # noqa
  1373. elif column.nullable and is_timestamp:
  1374. colspec.append("NULL")
  1375. comment = column.comment
  1376. if comment is not None:
  1377. literal = self.sql_compiler.render_literal_value(
  1378. comment, sqltypes.String()
  1379. )
  1380. colspec.append("COMMENT " + literal)
  1381. if (
  1382. column.table is not None
  1383. and column is column.table._autoincrement_column
  1384. and (
  1385. column.server_default is None
  1386. or isinstance(column.server_default, sa_schema.Identity)
  1387. )
  1388. and not (
  1389. self.dialect.supports_sequences
  1390. and isinstance(column.default, sa_schema.Sequence)
  1391. and not column.default.optional
  1392. )
  1393. ):
  1394. colspec.append("AUTO_INCREMENT")
  1395. else:
  1396. default = self.get_column_default_string(column)
  1397. if default is not None:
  1398. colspec.append("DEFAULT " + default)
  1399. return " ".join(colspec)
  1400. def post_create_table(self, table):
  1401. """Build table-level CREATE options like ENGINE and COLLATE."""
  1402. table_opts = []
  1403. opts = dict(
  1404. (k[len(self.dialect.name) + 1 :].upper(), v)
  1405. for k, v in table.kwargs.items()
  1406. if k.startswith("%s_" % self.dialect.name)
  1407. )
  1408. if table.comment is not None:
  1409. opts["COMMENT"] = table.comment
  1410. partition_options = [
  1411. "PARTITION_BY",
  1412. "PARTITIONS",
  1413. "SUBPARTITIONS",
  1414. "SUBPARTITION_BY",
  1415. ]
  1416. nonpart_options = set(opts).difference(partition_options)
  1417. part_options = set(opts).intersection(partition_options)
  1418. for opt in topological.sort(
  1419. [
  1420. ("DEFAULT_CHARSET", "COLLATE"),
  1421. ("DEFAULT_CHARACTER_SET", "COLLATE"),
  1422. ("CHARSET", "COLLATE"),
  1423. ("CHARACTER_SET", "COLLATE"),
  1424. ],
  1425. nonpart_options,
  1426. ):
  1427. arg = opts[opt]
  1428. if opt in _reflection._options_of_type_string:
  1429. arg = self.sql_compiler.render_literal_value(
  1430. arg, sqltypes.String()
  1431. )
  1432. if opt in (
  1433. "DATA_DIRECTORY",
  1434. "INDEX_DIRECTORY",
  1435. "DEFAULT_CHARACTER_SET",
  1436. "CHARACTER_SET",
  1437. "DEFAULT_CHARSET",
  1438. "DEFAULT_COLLATE",
  1439. ):
  1440. opt = opt.replace("_", " ")
  1441. joiner = "="
  1442. if opt in (
  1443. "TABLESPACE",
  1444. "DEFAULT CHARACTER SET",
  1445. "CHARACTER SET",
  1446. "COLLATE",
  1447. ):
  1448. joiner = " "
  1449. table_opts.append(joiner.join((opt, arg)))
  1450. for opt in topological.sort(
  1451. [
  1452. ("PARTITION_BY", "PARTITIONS"),
  1453. ("PARTITION_BY", "SUBPARTITION_BY"),
  1454. ("PARTITION_BY", "SUBPARTITIONS"),
  1455. ("PARTITIONS", "SUBPARTITIONS"),
  1456. ("PARTITIONS", "SUBPARTITION_BY"),
  1457. ("SUBPARTITION_BY", "SUBPARTITIONS"),
  1458. ],
  1459. part_options,
  1460. ):
  1461. arg = opts[opt]
  1462. if opt in _reflection._options_of_type_string:
  1463. arg = self.sql_compiler.render_literal_value(
  1464. arg, sqltypes.String()
  1465. )
  1466. opt = opt.replace("_", " ")
  1467. joiner = " "
  1468. table_opts.append(joiner.join((opt, arg)))
  1469. return " ".join(table_opts)
  1470. def visit_create_index(self, create, **kw):
  1471. index = create.element
  1472. self._verify_index_table(index)
  1473. preparer = self.preparer
  1474. table = preparer.format_table(index.table)
  1475. columns = [
  1476. self.sql_compiler.process(
  1477. elements.Grouping(expr)
  1478. if (
  1479. isinstance(expr, elements.BinaryExpression)
  1480. or (
  1481. isinstance(expr, elements.UnaryExpression)
  1482. and expr.modifier
  1483. not in (operators.desc_op, operators.asc_op)
  1484. )
  1485. or isinstance(expr, functions.FunctionElement)
  1486. )
  1487. else expr,
  1488. include_table=False,
  1489. literal_binds=True,
  1490. )
  1491. for expr in index.expressions
  1492. ]
  1493. name = self._prepared_index_name(index)
  1494. text = "CREATE "
  1495. if index.unique:
  1496. text += "UNIQUE "
  1497. index_prefix = index.kwargs.get("%s_prefix" % self.dialect.name, None)
  1498. if index_prefix:
  1499. text += index_prefix + " "
  1500. text += "INDEX "
  1501. if create.if_not_exists:
  1502. text += "IF NOT EXISTS "
  1503. text += "%s ON %s " % (name, table)
  1504. length = index.dialect_options[self.dialect.name]["length"]
  1505. if length is not None:
  1506. if isinstance(length, dict):
  1507. # length value can be a (column_name --> integer value)
  1508. # mapping specifying the prefix length for each column of the
  1509. # index
  1510. columns = ", ".join(
  1511. "%s(%d)" % (expr, length[col.name])
  1512. if col.name in length
  1513. else (
  1514. "%s(%d)" % (expr, length[expr])
  1515. if expr in length
  1516. else "%s" % expr
  1517. )
  1518. for col, expr in zip(index.expressions, columns)
  1519. )
  1520. else:
  1521. # or can be an integer value specifying the same
  1522. # prefix length for all columns of the index
  1523. columns = ", ".join(
  1524. "%s(%d)" % (col, length) for col in columns
  1525. )
  1526. else:
  1527. columns = ", ".join(columns)
  1528. text += "(%s)" % columns
  1529. parser = index.dialect_options["mysql"]["with_parser"]
  1530. if parser is not None:
  1531. text += " WITH PARSER %s" % (parser,)
  1532. using = index.dialect_options["mysql"]["using"]
  1533. if using is not None:
  1534. text += " USING %s" % (preparer.quote(using))
  1535. return text
  1536. def visit_primary_key_constraint(self, constraint):
  1537. text = super(MySQLDDLCompiler, self).visit_primary_key_constraint(
  1538. constraint
  1539. )
  1540. using = constraint.dialect_options["mysql"]["using"]
  1541. if using:
  1542. text += " USING %s" % (self.preparer.quote(using))
  1543. return text
  1544. def visit_drop_index(self, drop):
  1545. index = drop.element
  1546. text = "\nDROP INDEX "
  1547. if drop.if_exists:
  1548. text += "IF EXISTS "
  1549. return text + "%s ON %s" % (
  1550. self._prepared_index_name(index, include_schema=False),
  1551. self.preparer.format_table(index.table),
  1552. )
  1553. def visit_drop_constraint(self, drop):
  1554. constraint = drop.element
  1555. if isinstance(constraint, sa_schema.ForeignKeyConstraint):
  1556. qual = "FOREIGN KEY "
  1557. const = self.preparer.format_constraint(constraint)
  1558. elif isinstance(constraint, sa_schema.PrimaryKeyConstraint):
  1559. qual = "PRIMARY KEY "
  1560. const = ""
  1561. elif isinstance(constraint, sa_schema.UniqueConstraint):
  1562. qual = "INDEX "
  1563. const = self.preparer.format_constraint(constraint)
  1564. elif isinstance(constraint, sa_schema.CheckConstraint):
  1565. if self.dialect.is_mariadb:
  1566. qual = "CONSTRAINT "
  1567. else:
  1568. qual = "CHECK "
  1569. const = self.preparer.format_constraint(constraint)
  1570. else:
  1571. qual = ""
  1572. const = self.preparer.format_constraint(constraint)
  1573. return "ALTER TABLE %s DROP %s%s" % (
  1574. self.preparer.format_table(constraint.table),
  1575. qual,
  1576. const,
  1577. )
  1578. def define_constraint_match(self, constraint):
  1579. if constraint.match is not None:
  1580. raise exc.CompileError(
  1581. "MySQL ignores the 'MATCH' keyword while at the same time "
  1582. "causes ON UPDATE/ON DELETE clauses to be ignored."
  1583. )
  1584. return ""
  1585. def visit_set_table_comment(self, create):
  1586. return "ALTER TABLE %s COMMENT %s" % (
  1587. self.preparer.format_table(create.element),
  1588. self.sql_compiler.render_literal_value(
  1589. create.element.comment, sqltypes.String()
  1590. ),
  1591. )
  1592. def visit_drop_table_comment(self, create):
  1593. return "ALTER TABLE %s COMMENT ''" % (
  1594. self.preparer.format_table(create.element)
  1595. )
  1596. def visit_set_column_comment(self, create):
  1597. return "ALTER TABLE %s CHANGE %s %s" % (
  1598. self.preparer.format_table(create.element.table),
  1599. self.preparer.format_column(create.element),
  1600. self.get_column_specification(create.element),
  1601. )
  1602. class MySQLTypeCompiler(compiler.GenericTypeCompiler):
  1603. def _extend_numeric(self, type_, spec):
  1604. "Extend a numeric-type declaration with MySQL specific extensions."
  1605. if not self._mysql_type(type_):
  1606. return spec
  1607. if type_.unsigned:
  1608. spec += " UNSIGNED"
  1609. if type_.zerofill:
  1610. spec += " ZEROFILL"
  1611. return spec
  1612. def _extend_string(self, type_, defaults, spec):
  1613. """Extend a string-type declaration with standard SQL CHARACTER SET /
  1614. COLLATE annotations and MySQL specific extensions.
  1615. """
  1616. def attr(name):
  1617. return getattr(type_, name, defaults.get(name))
  1618. if attr("charset"):
  1619. charset = "CHARACTER SET %s" % attr("charset")
  1620. elif attr("ascii"):
  1621. charset = "ASCII"
  1622. elif attr("unicode"):
  1623. charset = "UNICODE"
  1624. else:
  1625. charset = None
  1626. if attr("collation"):
  1627. collation = "COLLATE %s" % type_.collation
  1628. elif attr("binary"):
  1629. collation = "BINARY"
  1630. else:
  1631. collation = None
  1632. if attr("national"):
  1633. # NATIONAL (aka NCHAR/NVARCHAR) trumps charsets.
  1634. return " ".join(
  1635. [c for c in ("NATIONAL", spec, collation) if c is not None]
  1636. )
  1637. return " ".join(
  1638. [c for c in (spec, charset, collation) if c is not None]
  1639. )
  1640. def _mysql_type(self, type_):
  1641. return isinstance(type_, (_StringType, _NumericType))
  1642. def visit_NUMERIC(self, type_, **kw):
  1643. if type_.precision is None:
  1644. return self._extend_numeric(type_, "NUMERIC")
  1645. elif type_.scale is None:
  1646. return self._extend_numeric(
  1647. type_,
  1648. "NUMERIC(%(precision)s)" % {"precision": type_.precision},
  1649. )
  1650. else:
  1651. return self._extend_numeric(
  1652. type_,
  1653. "NUMERIC(%(precision)s, %(scale)s)"
  1654. % {"precision": type_.precision, "scale": type_.scale},
  1655. )
  1656. def visit_DECIMAL(self, type_, **kw):
  1657. if type_.precision is None:
  1658. return self._extend_numeric(type_, "DECIMAL")
  1659. elif type_.scale is None:
  1660. return self._extend_numeric(
  1661. type_,
  1662. "DECIMAL(%(precision)s)" % {"precision": type_.precision},
  1663. )
  1664. else:
  1665. return self._extend_numeric(
  1666. type_,
  1667. "DECIMAL(%(precision)s, %(scale)s)"
  1668. % {"precision": type_.precision, "scale": type_.scale},
  1669. )
  1670. def visit_DOUBLE(self, type_, **kw):
  1671. if type_.precision is not None and type_.scale is not None:
  1672. return self._extend_numeric(
  1673. type_,
  1674. "DOUBLE(%(precision)s, %(scale)s)"
  1675. % {"precision": type_.precision, "scale": type_.scale},
  1676. )
  1677. else:
  1678. return self._extend_numeric(type_, "DOUBLE")
  1679. def visit_REAL(self, type_, **kw):
  1680. if type_.precision is not None and type_.scale is not None:
  1681. return self._extend_numeric(
  1682. type_,
  1683. "REAL(%(precision)s, %(scale)s)"
  1684. % {"precision": type_.precision, "scale": type_.scale},
  1685. )
  1686. else:
  1687. return self._extend_numeric(type_, "REAL")
  1688. def visit_FLOAT(self, type_, **kw):
  1689. if (
  1690. self._mysql_type(type_)
  1691. and type_.scale is not None
  1692. and type_.precision is not None
  1693. ):
  1694. return self._extend_numeric(
  1695. type_, "FLOAT(%s, %s)" % (type_.precision, type_.scale)
  1696. )
  1697. elif type_.precision is not None:
  1698. return self._extend_numeric(
  1699. type_, "FLOAT(%s)" % (type_.precision,)
  1700. )
  1701. else:
  1702. return self._extend_numeric(type_, "FLOAT")
  1703. def visit_INTEGER(self, type_, **kw):
  1704. if self._mysql_type(type_) and type_.display_width is not None:
  1705. return self._extend_numeric(
  1706. type_,
  1707. "INTEGER(%(display_width)s)"
  1708. % {"display_width": type_.display_width},
  1709. )
  1710. else:
  1711. return self._extend_numeric(type_, "INTEGER")
  1712. def visit_BIGINT(self, type_, **kw):
  1713. if self._mysql_type(type_) and type_.display_width is not None:
  1714. return self._extend_numeric(
  1715. type_,
  1716. "BIGINT(%(display_width)s)"
  1717. % {"display_width": type_.display_width},
  1718. )
  1719. else:
  1720. return self._extend_numeric(type_, "BIGINT")
  1721. def visit_MEDIUMINT(self, type_, **kw):
  1722. if self._mysql_type(type_) and type_.display_width is not None:
  1723. return self._extend_numeric(
  1724. type_,
  1725. "MEDIUMINT(%(display_width)s)"
  1726. % {"display_width": type_.display_width},
  1727. )
  1728. else:
  1729. return self._extend_numeric(type_, "MEDIUMINT")
  1730. def visit_TINYINT(self, type_, **kw):
  1731. if self._mysql_type(type_) and type_.display_width is not None:
  1732. return self._extend_numeric(
  1733. type_, "TINYINT(%s)" % type_.display_width
  1734. )
  1735. else:
  1736. return self._extend_numeric(type_, "TINYINT")
  1737. def visit_SMALLINT(self, type_, **kw):
  1738. if self._mysql_type(type_) and type_.display_width is not None:
  1739. return self._extend_numeric(
  1740. type_,
  1741. "SMALLINT(%(display_width)s)"
  1742. % {"display_width": type_.display_width},
  1743. )
  1744. else:
  1745. return self._extend_numeric(type_, "SMALLINT")
  1746. def visit_BIT(self, type_, **kw):
  1747. if type_.length is not None:
  1748. return "BIT(%s)" % type_.length
  1749. else:
  1750. return "BIT"
  1751. def visit_DATETIME(self, type_, **kw):
  1752. if getattr(type_, "fsp", None):
  1753. return "DATETIME(%d)" % type_.fsp
  1754. else:
  1755. return "DATETIME"
  1756. def visit_DATE(self, type_, **kw):
  1757. return "DATE"
  1758. def visit_TIME(self, type_, **kw):
  1759. if getattr(type_, "fsp", None):
  1760. return "TIME(%d)" % type_.fsp
  1761. else:
  1762. return "TIME"
  1763. def visit_TIMESTAMP(self, type_, **kw):
  1764. if getattr(type_, "fsp", None):
  1765. return "TIMESTAMP(%d)" % type_.fsp
  1766. else:
  1767. return "TIMESTAMP"
  1768. def visit_YEAR(self, type_, **kw):
  1769. if type_.display_width is None:
  1770. return "YEAR"
  1771. else:
  1772. return "YEAR(%s)" % type_.display_width
  1773. def visit_TEXT(self, type_, **kw):
  1774. if type_.length:
  1775. return self._extend_string(type_, {}, "TEXT(%d)" % type_.length)
  1776. else:
  1777. return self._extend_string(type_, {}, "TEXT")
  1778. def visit_TINYTEXT(self, type_, **kw):
  1779. return self._extend_string(type_, {}, "TINYTEXT")
  1780. def visit_MEDIUMTEXT(self, type_, **kw):
  1781. return self._extend_string(type_, {}, "MEDIUMTEXT")
  1782. def visit_LONGTEXT(self, type_, **kw):
  1783. return self._extend_string(type_, {}, "LONGTEXT")
  1784. def visit_VARCHAR(self, type_, **kw):
  1785. if type_.length:
  1786. return self._extend_string(type_, {}, "VARCHAR(%d)" % type_.length)
  1787. else:
  1788. raise exc.CompileError(
  1789. "VARCHAR requires a length on dialect %s" % self.dialect.name
  1790. )
  1791. def visit_CHAR(self, type_, **kw):
  1792. if type_.length:
  1793. return self._extend_string(
  1794. type_, {}, "CHAR(%(length)s)" % {"length": type_.length}
  1795. )
  1796. else:
  1797. return self._extend_string(type_, {}, "CHAR")
  1798. def visit_NVARCHAR(self, type_, **kw):
  1799. # We'll actually generate the equiv. "NATIONAL VARCHAR" instead
  1800. # of "NVARCHAR".
  1801. if type_.length:
  1802. return self._extend_string(
  1803. type_,
  1804. {"national": True},
  1805. "VARCHAR(%(length)s)" % {"length": type_.length},
  1806. )
  1807. else:
  1808. raise exc.CompileError(
  1809. "NVARCHAR requires a length on dialect %s" % self.dialect.name
  1810. )
  1811. def visit_NCHAR(self, type_, **kw):
  1812. # We'll actually generate the equiv.
  1813. # "NATIONAL CHAR" instead of "NCHAR".
  1814. if type_.length:
  1815. return self._extend_string(
  1816. type_,
  1817. {"national": True},
  1818. "CHAR(%(length)s)" % {"length": type_.length},
  1819. )
  1820. else:
  1821. return self._extend_string(type_, {"national": True}, "CHAR")
  1822. def visit_VARBINARY(self, type_, **kw):
  1823. return "VARBINARY(%d)" % type_.length
  1824. def visit_JSON(self, type_, **kw):
  1825. return "JSON"
  1826. def visit_large_binary(self, type_, **kw):
  1827. return self.visit_BLOB(type_)
  1828. def visit_enum(self, type_, **kw):
  1829. if not type_.native_enum:
  1830. return super(MySQLTypeCompiler, self).visit_enum(type_)
  1831. else:
  1832. return self._visit_enumerated_values("ENUM", type_, type_.enums)
  1833. def visit_BLOB(self, type_, **kw):
  1834. if type_.length:
  1835. return "BLOB(%d)" % type_.length
  1836. else:
  1837. return "BLOB"
  1838. def visit_TINYBLOB(self, type_, **kw):
  1839. return "TINYBLOB"
  1840. def visit_MEDIUMBLOB(self, type_, **kw):
  1841. return "MEDIUMBLOB"
  1842. def visit_LONGBLOB(self, type_, **kw):
  1843. return "LONGBLOB"
  1844. def _visit_enumerated_values(self, name, type_, enumerated_values):
  1845. quoted_enums = []
  1846. for e in enumerated_values:
  1847. quoted_enums.append("'%s'" % e.replace("'", "''"))
  1848. return self._extend_string(
  1849. type_, {}, "%s(%s)" % (name, ",".join(quoted_enums))
  1850. )
  1851. def visit_ENUM(self, type_, **kw):
  1852. return self._visit_enumerated_values("ENUM", type_, type_.enums)
  1853. def visit_SET(self, type_, **kw):
  1854. return self._visit_enumerated_values("SET", type_, type_.values)
  1855. def visit_BOOLEAN(self, type_, **kw):
  1856. return "BOOL"
  1857. class MySQLIdentifierPreparer(compiler.IdentifierPreparer):
  1858. reserved_words = RESERVED_WORDS_MYSQL
  1859. def __init__(self, dialect, server_ansiquotes=False, **kw):
  1860. if not server_ansiquotes:
  1861. quote = "`"
  1862. else:
  1863. quote = '"'
  1864. super(MySQLIdentifierPreparer, self).__init__(
  1865. dialect, initial_quote=quote, escape_quote=quote
  1866. )
  1867. def _quote_free_identifiers(self, *ids):
  1868. """Unilaterally identifier-quote any number of strings."""
  1869. return tuple([self.quote_identifier(i) for i in ids if i is not None])
  1870. class MariaDBIdentifierPreparer(MySQLIdentifierPreparer):
  1871. reserved_words = RESERVED_WORDS_MARIADB
  1872. @log.class_logger
  1873. class MySQLDialect(default.DefaultDialect):
  1874. """Details of the MySQL dialect.
  1875. Not used directly in application code.
  1876. """
  1877. name = "mysql"
  1878. supports_statement_cache = True
  1879. supports_alter = True
  1880. # MySQL has no true "boolean" type; we
  1881. # allow for the "true" and "false" keywords, however
  1882. supports_native_boolean = False
  1883. # identifiers are 64, however aliases can be 255...
  1884. max_identifier_length = 255
  1885. max_index_name_length = 64
  1886. max_constraint_name_length = 64
  1887. supports_native_enum = True
  1888. supports_sequences = False # default for MySQL ...
  1889. # ... may be updated to True for MariaDB 10.3+ in initialize()
  1890. sequences_optional = False
  1891. supports_for_update_of = False # default for MySQL ...
  1892. # ... may be updated to True for MySQL 8+ in initialize()
  1893. # MySQL doesn't support "DEFAULT VALUES" but *does* support
  1894. # "VALUES (DEFAULT)"
  1895. supports_default_values = False
  1896. supports_default_metavalue = True
  1897. supports_sane_rowcount = True
  1898. supports_sane_multi_rowcount = False
  1899. supports_multivalues_insert = True
  1900. supports_comments = True
  1901. inline_comments = True
  1902. default_paramstyle = "format"
  1903. colspecs = colspecs
  1904. cte_follows_insert = True
  1905. statement_compiler = MySQLCompiler
  1906. ddl_compiler = MySQLDDLCompiler
  1907. type_compiler = MySQLTypeCompiler
  1908. ischema_names = ischema_names
  1909. preparer = MySQLIdentifierPreparer
  1910. is_mariadb = False
  1911. _mariadb_normalized_version_info = None
  1912. # default SQL compilation settings -
  1913. # these are modified upon initialize(),
  1914. # i.e. first connect
  1915. _backslash_escapes = True
  1916. _server_ansiquotes = False
  1917. construct_arguments = [
  1918. (sa_schema.Table, {"*": None}),
  1919. (sql.Update, {"limit": None}),
  1920. (sa_schema.PrimaryKeyConstraint, {"using": None}),
  1921. (
  1922. sa_schema.Index,
  1923. {
  1924. "using": None,
  1925. "length": None,
  1926. "prefix": None,
  1927. "with_parser": None,
  1928. },
  1929. ),
  1930. ]
  1931. def __init__(
  1932. self,
  1933. isolation_level=None,
  1934. json_serializer=None,
  1935. json_deserializer=None,
  1936. is_mariadb=None,
  1937. **kwargs
  1938. ):
  1939. kwargs.pop("use_ansiquotes", None) # legacy
  1940. default.DefaultDialect.__init__(self, **kwargs)
  1941. self.isolation_level = isolation_level
  1942. self._json_serializer = json_serializer
  1943. self._json_deserializer = json_deserializer
  1944. self._set_mariadb(is_mariadb, None)
  1945. def on_connect(self):
  1946. if self.isolation_level is not None:
  1947. def connect(conn):
  1948. self.set_isolation_level(conn, self.isolation_level)
  1949. return connect
  1950. else:
  1951. return None
  1952. _isolation_lookup = set(
  1953. [
  1954. "SERIALIZABLE",
  1955. "READ UNCOMMITTED",
  1956. "READ COMMITTED",
  1957. "REPEATABLE READ",
  1958. ]
  1959. )
  1960. def set_isolation_level(self, connection, level):
  1961. level = level.replace("_", " ")
  1962. # adjust for ConnectionFairy being present
  1963. # allows attribute set e.g. "connection.autocommit = True"
  1964. # to work properly
  1965. if hasattr(connection, "dbapi_connection"):
  1966. connection = connection.dbapi_connection
  1967. self._set_isolation_level(connection, level)
  1968. def _set_isolation_level(self, connection, level):
  1969. if level not in self._isolation_lookup:
  1970. raise exc.ArgumentError(
  1971. "Invalid value '%s' for isolation_level. "
  1972. "Valid isolation levels for %s are %s"
  1973. % (level, self.name, ", ".join(self._isolation_lookup))
  1974. )
  1975. cursor = connection.cursor()
  1976. cursor.execute("SET SESSION TRANSACTION ISOLATION LEVEL %s" % level)
  1977. cursor.execute("COMMIT")
  1978. cursor.close()
  1979. def get_isolation_level(self, connection):
  1980. cursor = connection.cursor()
  1981. if self._is_mysql and self.server_version_info >= (5, 7, 20):
  1982. cursor.execute("SELECT @@transaction_isolation")
  1983. else:
  1984. cursor.execute("SELECT @@tx_isolation")
  1985. row = cursor.fetchone()
  1986. if row is None:
  1987. util.warn(
  1988. "Could not retrieve transaction isolation level for MySQL "
  1989. "connection."
  1990. )
  1991. raise NotImplementedError()
  1992. val = row[0]
  1993. cursor.close()
  1994. if util.py3k and isinstance(val, bytes):
  1995. val = val.decode()
  1996. return val.upper().replace("-", " ")
  1997. @classmethod
  1998. def _is_mariadb_from_url(cls, url):
  1999. dbapi = cls.dbapi()
  2000. dialect = cls(dbapi=dbapi)
  2001. cargs, cparams = dialect.create_connect_args(url)
  2002. conn = dialect.connect(*cargs, **cparams)
  2003. try:
  2004. cursor = conn.cursor()
  2005. cursor.execute("SELECT VERSION() LIKE '%MariaDB%'")
  2006. val = cursor.fetchone()[0]
  2007. except:
  2008. raise
  2009. else:
  2010. return bool(val)
  2011. finally:
  2012. conn.close()
  2013. def _get_server_version_info(self, connection):
  2014. # get database server version info explicitly over the wire
  2015. # to avoid proxy servers like MaxScale getting in the
  2016. # way with their own values, see #4205
  2017. dbapi_con = connection.connection
  2018. cursor = dbapi_con.cursor()
  2019. cursor.execute("SELECT VERSION()")
  2020. val = cursor.fetchone()[0]
  2021. cursor.close()
  2022. if util.py3k and isinstance(val, bytes):
  2023. val = val.decode()
  2024. return self._parse_server_version(val)
  2025. def _parse_server_version(self, val):
  2026. version = []
  2027. is_mariadb = False
  2028. r = re.compile(r"[.\-+]")
  2029. tokens = r.split(val)
  2030. for token in tokens:
  2031. parsed_token = re.match(
  2032. r"^(?:(\d+)(?:a|b|c)?|(MariaDB\w*))$", token
  2033. )
  2034. if not parsed_token:
  2035. continue
  2036. elif parsed_token.group(2):
  2037. self._mariadb_normalized_version_info = tuple(version[-3:])
  2038. is_mariadb = True
  2039. else:
  2040. digit = int(parsed_token.group(1))
  2041. version.append(digit)
  2042. server_version_info = tuple(version)
  2043. self._set_mariadb(server_version_info and is_mariadb, val)
  2044. if not is_mariadb:
  2045. self._mariadb_normalized_version_info = server_version_info
  2046. if server_version_info < (5, 0, 2):
  2047. raise NotImplementedError(
  2048. "the MySQL/MariaDB dialect supports server "
  2049. "version info 5.0.2 and above."
  2050. )
  2051. # setting it here to help w the test suite
  2052. self.server_version_info = server_version_info
  2053. return server_version_info
  2054. def _set_mariadb(self, is_mariadb, server_version_info):
  2055. if is_mariadb is None:
  2056. return
  2057. if not is_mariadb and self.is_mariadb:
  2058. raise exc.InvalidRequestError(
  2059. "MySQL version %s is not a MariaDB variant."
  2060. % (server_version_info,)
  2061. )
  2062. if is_mariadb:
  2063. self.preparer = MariaDBIdentifierPreparer
  2064. # this would have been set by the default dialect already,
  2065. # so set it again
  2066. self.identifier_preparer = self.preparer(self)
  2067. self.is_mariadb = is_mariadb
  2068. def do_begin_twophase(self, connection, xid):
  2069. connection.execute(sql.text("XA BEGIN :xid"), dict(xid=xid))
  2070. def do_prepare_twophase(self, connection, xid):
  2071. connection.execute(sql.text("XA END :xid"), dict(xid=xid))
  2072. connection.execute(sql.text("XA PREPARE :xid"), dict(xid=xid))
  2073. def do_rollback_twophase(
  2074. self, connection, xid, is_prepared=True, recover=False
  2075. ):
  2076. if not is_prepared:
  2077. connection.execute(sql.text("XA END :xid"), dict(xid=xid))
  2078. connection.execute(sql.text("XA ROLLBACK :xid"), dict(xid=xid))
  2079. def do_commit_twophase(
  2080. self, connection, xid, is_prepared=True, recover=False
  2081. ):
  2082. if not is_prepared:
  2083. self.do_prepare_twophase(connection, xid)
  2084. connection.execute(sql.text("XA COMMIT :xid"), dict(xid=xid))
  2085. def do_recover_twophase(self, connection):
  2086. resultset = connection.exec_driver_sql("XA RECOVER")
  2087. return [row["data"][0 : row["gtrid_length"]] for row in resultset]
  2088. def is_disconnect(self, e, connection, cursor):
  2089. if isinstance(
  2090. e,
  2091. (
  2092. self.dbapi.OperationalError,
  2093. self.dbapi.ProgrammingError,
  2094. self.dbapi.InterfaceError,
  2095. ),
  2096. ) and self._extract_error_code(e) in (
  2097. 1927,
  2098. 2006,
  2099. 2013,
  2100. 2014,
  2101. 2045,
  2102. 2055,
  2103. ):
  2104. return True
  2105. elif isinstance(
  2106. e, (self.dbapi.InterfaceError, self.dbapi.InternalError)
  2107. ):
  2108. # if underlying connection is closed,
  2109. # this is the error you get
  2110. return "(0, '')" in str(e)
  2111. else:
  2112. return False
  2113. def _compat_fetchall(self, rp, charset=None):
  2114. """Proxy result rows to smooth over MySQL-Python driver
  2115. inconsistencies."""
  2116. return [_DecodingRow(row, charset) for row in rp.fetchall()]
  2117. def _compat_fetchone(self, rp, charset=None):
  2118. """Proxy a result row to smooth over MySQL-Python driver
  2119. inconsistencies."""
  2120. row = rp.fetchone()
  2121. if row:
  2122. return _DecodingRow(row, charset)
  2123. else:
  2124. return None
  2125. def _compat_first(self, rp, charset=None):
  2126. """Proxy a result row to smooth over MySQL-Python driver
  2127. inconsistencies."""
  2128. row = rp.first()
  2129. if row:
  2130. return _DecodingRow(row, charset)
  2131. else:
  2132. return None
  2133. def _extract_error_code(self, exception):
  2134. raise NotImplementedError()
  2135. def _get_default_schema_name(self, connection):
  2136. return connection.exec_driver_sql("SELECT DATABASE()").scalar()
  2137. def has_table(self, connection, table_name, schema=None):
  2138. self._ensure_has_table_connection(connection)
  2139. if schema is None:
  2140. schema = self.default_schema_name
  2141. rs = connection.execute(
  2142. text(
  2143. "SELECT COUNT(*) FROM information_schema.tables WHERE "
  2144. "table_schema = :table_schema AND "
  2145. "table_name = :table_name"
  2146. ).bindparams(
  2147. sql.bindparam("table_schema", type_=Unicode),
  2148. sql.bindparam("table_name", type_=Unicode),
  2149. ),
  2150. {
  2151. "table_schema": util.text_type(schema),
  2152. "table_name": util.text_type(table_name),
  2153. },
  2154. )
  2155. return bool(rs.scalar())
  2156. def has_sequence(self, connection, sequence_name, schema=None):
  2157. if not self.supports_sequences:
  2158. self._sequences_not_supported()
  2159. if not schema:
  2160. schema = self.default_schema_name
  2161. # MariaDB implements sequences as a special type of table
  2162. #
  2163. cursor = connection.execute(
  2164. sql.text(
  2165. "SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES "
  2166. "WHERE TABLE_TYPE='SEQUENCE' and TABLE_NAME=:name AND "
  2167. "TABLE_SCHEMA=:schema_name"
  2168. ),
  2169. dict(
  2170. name=util.text_type(sequence_name),
  2171. schema_name=util.text_type(schema),
  2172. ),
  2173. )
  2174. return cursor.first() is not None
  2175. def _sequences_not_supported(self):
  2176. raise NotImplementedError(
  2177. "Sequences are supported only by the "
  2178. "MariaDB series 10.3 or greater"
  2179. )
  2180. @reflection.cache
  2181. def get_sequence_names(self, connection, schema=None, **kw):
  2182. if not self.supports_sequences:
  2183. self._sequences_not_supported()
  2184. if not schema:
  2185. schema = self.default_schema_name
  2186. # MariaDB implements sequences as a special type of table
  2187. cursor = connection.execute(
  2188. sql.text(
  2189. "SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES "
  2190. "WHERE TABLE_TYPE='SEQUENCE' and TABLE_SCHEMA=:schema_name"
  2191. ),
  2192. dict(schema_name=schema),
  2193. )
  2194. return [
  2195. row[0]
  2196. for row in self._compat_fetchall(
  2197. cursor, charset=self._connection_charset
  2198. )
  2199. ]
  2200. def initialize(self, connection):
  2201. self._connection_charset = self._detect_charset(connection)
  2202. self._detect_sql_mode(connection)
  2203. self._detect_ansiquotes(connection)
  2204. self._detect_casing(connection)
  2205. if self._server_ansiquotes:
  2206. # if ansiquotes == True, build a new IdentifierPreparer
  2207. # with the new setting
  2208. self.identifier_preparer = self.preparer(
  2209. self, server_ansiquotes=self._server_ansiquotes
  2210. )
  2211. default.DefaultDialect.initialize(self, connection)
  2212. self.supports_sequences = (
  2213. self.is_mariadb and self.server_version_info >= (10, 3)
  2214. )
  2215. self.supports_for_update_of = (
  2216. self._is_mysql and self.server_version_info >= (8,)
  2217. )
  2218. self._needs_correct_for_88718_96365 = (
  2219. not self.is_mariadb and self.server_version_info >= (8,)
  2220. )
  2221. self._warn_for_known_db_issues()
  2222. def _warn_for_known_db_issues(self):
  2223. if self.is_mariadb:
  2224. mdb_version = self._mariadb_normalized_version_info
  2225. if mdb_version > (10, 2) and mdb_version < (10, 2, 9):
  2226. util.warn(
  2227. "MariaDB %r before 10.2.9 has known issues regarding "
  2228. "CHECK constraints, which impact handling of NULL values "
  2229. "with SQLAlchemy's boolean datatype (MDEV-13596). An "
  2230. "additional issue prevents proper migrations of columns "
  2231. "with CHECK constraints (MDEV-11114). Please upgrade to "
  2232. "MariaDB 10.2.9 or greater, or use the MariaDB 10.1 "
  2233. "series, to avoid these issues." % (mdb_version,)
  2234. )
  2235. @property
  2236. def _support_float_cast(self):
  2237. if not self.server_version_info:
  2238. return False
  2239. elif self.is_mariadb:
  2240. # ref https://mariadb.com/kb/en/mariadb-1045-release-notes/
  2241. return self.server_version_info >= (10, 4, 5)
  2242. else:
  2243. # ref https://dev.mysql.com/doc/relnotes/mysql/8.0/en/news-8-0-17.html#mysqld-8-0-17-feature # noqa
  2244. return self.server_version_info >= (8, 0, 17)
  2245. @property
  2246. def _is_mariadb(self):
  2247. return self.is_mariadb
  2248. @property
  2249. def _is_mysql(self):
  2250. return not self.is_mariadb
  2251. @property
  2252. def _is_mariadb_102(self):
  2253. return self.is_mariadb and self._mariadb_normalized_version_info > (
  2254. 10,
  2255. 2,
  2256. )
  2257. @reflection.cache
  2258. def get_schema_names(self, connection, **kw):
  2259. rp = connection.exec_driver_sql("SHOW schemas")
  2260. return [r[0] for r in rp]
  2261. @reflection.cache
  2262. def get_table_names(self, connection, schema=None, **kw):
  2263. """Return a Unicode SHOW TABLES from a given schema."""
  2264. if schema is not None:
  2265. current_schema = schema
  2266. else:
  2267. current_schema = self.default_schema_name
  2268. charset = self._connection_charset
  2269. rp = connection.exec_driver_sql(
  2270. "SHOW FULL TABLES FROM %s"
  2271. % self.identifier_preparer.quote_identifier(current_schema)
  2272. )
  2273. return [
  2274. row[0]
  2275. for row in self._compat_fetchall(rp, charset=charset)
  2276. if row[1] == "BASE TABLE"
  2277. ]
  2278. @reflection.cache
  2279. def get_view_names(self, connection, schema=None, **kw):
  2280. if schema is None:
  2281. schema = self.default_schema_name
  2282. charset = self._connection_charset
  2283. rp = connection.exec_driver_sql(
  2284. "SHOW FULL TABLES FROM %s"
  2285. % self.identifier_preparer.quote_identifier(schema)
  2286. )
  2287. return [
  2288. row[0]
  2289. for row in self._compat_fetchall(rp, charset=charset)
  2290. if row[1] in ("VIEW", "SYSTEM VIEW")
  2291. ]
  2292. @reflection.cache
  2293. def get_table_options(self, connection, table_name, schema=None, **kw):
  2294. parsed_state = self._parsed_state_or_create(
  2295. connection, table_name, schema, **kw
  2296. )
  2297. return parsed_state.table_options
  2298. @reflection.cache
  2299. def get_columns(self, connection, table_name, schema=None, **kw):
  2300. parsed_state = self._parsed_state_or_create(
  2301. connection, table_name, schema, **kw
  2302. )
  2303. return parsed_state.columns
  2304. @reflection.cache
  2305. def get_pk_constraint(self, connection, table_name, schema=None, **kw):
  2306. parsed_state = self._parsed_state_or_create(
  2307. connection, table_name, schema, **kw
  2308. )
  2309. for key in parsed_state.keys:
  2310. if key["type"] == "PRIMARY":
  2311. # There can be only one.
  2312. cols = [s[0] for s in key["columns"]]
  2313. return {"constrained_columns": cols, "name": None}
  2314. return {"constrained_columns": [], "name": None}
  2315. @reflection.cache
  2316. def get_foreign_keys(self, connection, table_name, schema=None, **kw):
  2317. parsed_state = self._parsed_state_or_create(
  2318. connection, table_name, schema, **kw
  2319. )
  2320. default_schema = None
  2321. fkeys = []
  2322. for spec in parsed_state.fk_constraints:
  2323. ref_name = spec["table"][-1]
  2324. ref_schema = len(spec["table"]) > 1 and spec["table"][-2] or schema
  2325. if not ref_schema:
  2326. if default_schema is None:
  2327. default_schema = connection.dialect.default_schema_name
  2328. if schema == default_schema:
  2329. ref_schema = schema
  2330. loc_names = spec["local"]
  2331. ref_names = spec["foreign"]
  2332. con_kw = {}
  2333. for opt in ("onupdate", "ondelete"):
  2334. if spec.get(opt, False) not in ("NO ACTION", None):
  2335. con_kw[opt] = spec[opt]
  2336. fkey_d = {
  2337. "name": spec["name"],
  2338. "constrained_columns": loc_names,
  2339. "referred_schema": ref_schema,
  2340. "referred_table": ref_name,
  2341. "referred_columns": ref_names,
  2342. "options": con_kw,
  2343. }
  2344. fkeys.append(fkey_d)
  2345. if self._needs_correct_for_88718_96365:
  2346. self._correct_for_mysql_bugs_88718_96365(fkeys, connection)
  2347. return fkeys
  2348. def _correct_for_mysql_bugs_88718_96365(self, fkeys, connection):
  2349. # Foreign key is always in lower case (MySQL 8.0)
  2350. # https://bugs.mysql.com/bug.php?id=88718
  2351. # issue #4344 for SQLAlchemy
  2352. # table name also for MySQL 8.0
  2353. # https://bugs.mysql.com/bug.php?id=96365
  2354. # issue #4751 for SQLAlchemy
  2355. # for lower_case_table_names=2, information_schema.columns
  2356. # preserves the original table/schema casing, but SHOW CREATE
  2357. # TABLE does not. this problem is not in lower_case_table_names=1,
  2358. # but use case-insensitive matching for these two modes in any case.
  2359. if self._casing in (1, 2):
  2360. def lower(s):
  2361. return s.lower()
  2362. else:
  2363. # if on case sensitive, there can be two tables referenced
  2364. # with the same name different casing, so we need to use
  2365. # case-sensitive matching.
  2366. def lower(s):
  2367. return s
  2368. default_schema_name = connection.dialect.default_schema_name
  2369. col_tuples = [
  2370. (
  2371. lower(rec["referred_schema"] or default_schema_name),
  2372. lower(rec["referred_table"]),
  2373. col_name,
  2374. )
  2375. for rec in fkeys
  2376. for col_name in rec["referred_columns"]
  2377. ]
  2378. if col_tuples:
  2379. correct_for_wrong_fk_case = connection.execute(
  2380. sql.text(
  2381. """
  2382. select table_schema, table_name, column_name
  2383. from information_schema.columns
  2384. where (table_schema, table_name, lower(column_name)) in
  2385. :table_data;
  2386. """
  2387. ).bindparams(sql.bindparam("table_data", expanding=True)),
  2388. dict(table_data=col_tuples),
  2389. )
  2390. # in casing=0, table name and schema name come back in their
  2391. # exact case.
  2392. # in casing=1, table name and schema name come back in lower
  2393. # case.
  2394. # in casing=2, table name and schema name come back from the
  2395. # information_schema.columns view in the case
  2396. # that was used in CREATE DATABASE and CREATE TABLE, but
  2397. # SHOW CREATE TABLE converts them to *lower case*, therefore
  2398. # not matching. So for this case, case-insensitive lookup
  2399. # is necessary
  2400. d = defaultdict(dict)
  2401. for schema, tname, cname in correct_for_wrong_fk_case:
  2402. d[(lower(schema), lower(tname))]["SCHEMANAME"] = schema
  2403. d[(lower(schema), lower(tname))]["TABLENAME"] = tname
  2404. d[(lower(schema), lower(tname))][cname.lower()] = cname
  2405. for fkey in fkeys:
  2406. rec = d[
  2407. (
  2408. lower(fkey["referred_schema"] or default_schema_name),
  2409. lower(fkey["referred_table"]),
  2410. )
  2411. ]
  2412. fkey["referred_table"] = rec["TABLENAME"]
  2413. if fkey["referred_schema"] is not None:
  2414. fkey["referred_schema"] = rec["SCHEMANAME"]
  2415. fkey["referred_columns"] = [
  2416. rec[col.lower()] for col in fkey["referred_columns"]
  2417. ]
  2418. @reflection.cache
  2419. def get_check_constraints(self, connection, table_name, schema=None, **kw):
  2420. parsed_state = self._parsed_state_or_create(
  2421. connection, table_name, schema, **kw
  2422. )
  2423. return [
  2424. {"name": spec["name"], "sqltext": spec["sqltext"]}
  2425. for spec in parsed_state.ck_constraints
  2426. ]
  2427. @reflection.cache
  2428. def get_table_comment(self, connection, table_name, schema=None, **kw):
  2429. parsed_state = self._parsed_state_or_create(
  2430. connection, table_name, schema, **kw
  2431. )
  2432. return {
  2433. "text": parsed_state.table_options.get(
  2434. "%s_comment" % self.name, None
  2435. )
  2436. }
  2437. @reflection.cache
  2438. def get_indexes(self, connection, table_name, schema=None, **kw):
  2439. parsed_state = self._parsed_state_or_create(
  2440. connection, table_name, schema, **kw
  2441. )
  2442. indexes = []
  2443. for spec in parsed_state.keys:
  2444. dialect_options = {}
  2445. unique = False
  2446. flavor = spec["type"]
  2447. if flavor == "PRIMARY":
  2448. continue
  2449. if flavor == "UNIQUE":
  2450. unique = True
  2451. elif flavor in ("FULLTEXT", "SPATIAL"):
  2452. dialect_options["%s_prefix" % self.name] = flavor
  2453. elif flavor is None:
  2454. pass
  2455. else:
  2456. self.logger.info(
  2457. "Converting unknown KEY type %s to a plain KEY", flavor
  2458. )
  2459. pass
  2460. if spec["parser"]:
  2461. dialect_options["%s_with_parser" % (self.name)] = spec[
  2462. "parser"
  2463. ]
  2464. index_d = {}
  2465. if dialect_options:
  2466. index_d["dialect_options"] = dialect_options
  2467. index_d["name"] = spec["name"]
  2468. index_d["column_names"] = [s[0] for s in spec["columns"]]
  2469. index_d["unique"] = unique
  2470. if flavor:
  2471. index_d["type"] = flavor
  2472. indexes.append(index_d)
  2473. return indexes
  2474. @reflection.cache
  2475. def get_unique_constraints(
  2476. self, connection, table_name, schema=None, **kw
  2477. ):
  2478. parsed_state = self._parsed_state_or_create(
  2479. connection, table_name, schema, **kw
  2480. )
  2481. return [
  2482. {
  2483. "name": key["name"],
  2484. "column_names": [col[0] for col in key["columns"]],
  2485. "duplicates_index": key["name"],
  2486. }
  2487. for key in parsed_state.keys
  2488. if key["type"] == "UNIQUE"
  2489. ]
  2490. @reflection.cache
  2491. def get_view_definition(self, connection, view_name, schema=None, **kw):
  2492. charset = self._connection_charset
  2493. full_name = ".".join(
  2494. self.identifier_preparer._quote_free_identifiers(schema, view_name)
  2495. )
  2496. sql = self._show_create_table(
  2497. connection, None, charset, full_name=full_name
  2498. )
  2499. return sql
  2500. def _parsed_state_or_create(
  2501. self, connection, table_name, schema=None, **kw
  2502. ):
  2503. return self._setup_parser(
  2504. connection,
  2505. table_name,
  2506. schema,
  2507. info_cache=kw.get("info_cache", None),
  2508. )
  2509. @util.memoized_property
  2510. def _tabledef_parser(self):
  2511. """return the MySQLTableDefinitionParser, generate if needed.
  2512. The deferred creation ensures that the dialect has
  2513. retrieved server version information first.
  2514. """
  2515. preparer = self.identifier_preparer
  2516. return _reflection.MySQLTableDefinitionParser(self, preparer)
  2517. @reflection.cache
  2518. def _setup_parser(self, connection, table_name, schema=None, **kw):
  2519. charset = self._connection_charset
  2520. parser = self._tabledef_parser
  2521. full_name = ".".join(
  2522. self.identifier_preparer._quote_free_identifiers(
  2523. schema, table_name
  2524. )
  2525. )
  2526. sql = self._show_create_table(
  2527. connection, None, charset, full_name=full_name
  2528. )
  2529. if re.match(r"^CREATE (?:ALGORITHM)?.* VIEW", sql):
  2530. # Adapt views to something table-like.
  2531. columns = self._describe_table(
  2532. connection, None, charset, full_name=full_name
  2533. )
  2534. sql = parser._describe_to_create(table_name, columns)
  2535. return parser.parse(sql, charset)
  2536. def _detect_charset(self, connection):
  2537. raise NotImplementedError()
  2538. def _detect_casing(self, connection):
  2539. """Sniff out identifier case sensitivity.
  2540. Cached per-connection. This value can not change without a server
  2541. restart.
  2542. """
  2543. # https://dev.mysql.com/doc/refman/en/identifier-case-sensitivity.html
  2544. charset = self._connection_charset
  2545. show_var = connection.exec_driver_sql(
  2546. "SELECT @@lower_case_table_names"
  2547. )
  2548. row = self._compat_first(show_var, charset=charset)
  2549. if not row:
  2550. cs = 0
  2551. else:
  2552. # 4.0.15 returns OFF or ON according to [ticket:489]
  2553. # 3.23 doesn't, 4.0.27 doesn't..
  2554. if row[0] == "OFF":
  2555. cs = 0
  2556. elif row[0] == "ON":
  2557. cs = 1
  2558. else:
  2559. cs = int(row[0])
  2560. self._casing = cs
  2561. return cs
  2562. def _detect_collations(self, connection):
  2563. """Pull the active COLLATIONS list from the server.
  2564. Cached per-connection.
  2565. """
  2566. collations = {}
  2567. charset = self._connection_charset
  2568. rs = connection.exec_driver_sql("SHOW COLLATION")
  2569. for row in self._compat_fetchall(rs, charset):
  2570. collations[row[0]] = row[1]
  2571. return collations
  2572. def _detect_sql_mode(self, connection):
  2573. row = self._compat_first(
  2574. connection.exec_driver_sql("SELECT @@sql_mode"),
  2575. charset=self._connection_charset,
  2576. )
  2577. if not row:
  2578. util.warn(
  2579. "Could not retrieve SQL_MODE; please ensure the "
  2580. "MySQL user has permissions to SHOW VARIABLES"
  2581. )
  2582. self._sql_mode = ""
  2583. else:
  2584. self._sql_mode = row[0] or ""
  2585. def _detect_ansiquotes(self, connection):
  2586. """Detect and adjust for the ANSI_QUOTES sql mode."""
  2587. mode = self._sql_mode
  2588. if not mode:
  2589. mode = ""
  2590. elif mode.isdigit():
  2591. mode_no = int(mode)
  2592. mode = (mode_no | 4 == mode_no) and "ANSI_QUOTES" or ""
  2593. self._server_ansiquotes = "ANSI_QUOTES" in mode
  2594. # as of MySQL 5.0.1
  2595. self._backslash_escapes = "NO_BACKSLASH_ESCAPES" not in mode
  2596. def _show_create_table(
  2597. self, connection, table, charset=None, full_name=None
  2598. ):
  2599. """Run SHOW CREATE TABLE for a ``Table``."""
  2600. if full_name is None:
  2601. full_name = self.identifier_preparer.format_table(table)
  2602. st = "SHOW CREATE TABLE %s" % full_name
  2603. rp = None
  2604. try:
  2605. rp = connection.execution_options(
  2606. skip_user_error_events=True
  2607. ).exec_driver_sql(st)
  2608. except exc.DBAPIError as e:
  2609. if self._extract_error_code(e.orig) == 1146:
  2610. util.raise_(exc.NoSuchTableError(full_name), replace_context=e)
  2611. else:
  2612. raise
  2613. row = self._compat_first(rp, charset=charset)
  2614. if not row:
  2615. raise exc.NoSuchTableError(full_name)
  2616. return row[1].strip()
  2617. def _describe_table(self, connection, table, charset=None, full_name=None):
  2618. """Run DESCRIBE for a ``Table`` and return processed rows."""
  2619. if full_name is None:
  2620. full_name = self.identifier_preparer.format_table(table)
  2621. st = "DESCRIBE %s" % full_name
  2622. rp, rows = None, None
  2623. try:
  2624. try:
  2625. rp = connection.execution_options(
  2626. skip_user_error_events=True
  2627. ).exec_driver_sql(st)
  2628. except exc.DBAPIError as e:
  2629. code = self._extract_error_code(e.orig)
  2630. if code == 1146:
  2631. util.raise_(
  2632. exc.NoSuchTableError(full_name), replace_context=e
  2633. )
  2634. elif code == 1356:
  2635. util.raise_(
  2636. exc.UnreflectableTableError(
  2637. "Table or view named %s could not be "
  2638. "reflected: %s" % (full_name, e)
  2639. ),
  2640. replace_context=e,
  2641. )
  2642. else:
  2643. raise
  2644. rows = self._compat_fetchall(rp, charset=charset)
  2645. finally:
  2646. if rp:
  2647. rp.close()
  2648. return rows
  2649. class _DecodingRow(object):
  2650. """Return unicode-decoded values based on type inspection.
  2651. Smooth over data type issues (esp. with alpha driver versions) and
  2652. normalize strings as Unicode regardless of user-configured driver
  2653. encoding settings.
  2654. """
  2655. # Some MySQL-python versions can return some columns as
  2656. # sets.Set(['value']) (seriously) but thankfully that doesn't
  2657. # seem to come up in DDL queries.
  2658. _encoding_compat = {
  2659. "koi8r": "koi8_r",
  2660. "koi8u": "koi8_u",
  2661. "utf16": "utf-16-be", # MySQL's uft16 is always bigendian
  2662. "utf8mb4": "utf8", # real utf8
  2663. "utf8mb3": "utf8", # real utf8; saw this happen on CI but I cannot
  2664. # reproduce, possibly mariadb10.6 related
  2665. "eucjpms": "ujis",
  2666. }
  2667. def __init__(self, rowproxy, charset):
  2668. self.rowproxy = rowproxy
  2669. self.charset = self._encoding_compat.get(charset, charset)
  2670. def __getitem__(self, index):
  2671. item = self.rowproxy[index]
  2672. if isinstance(item, _array):
  2673. item = item.tostring()
  2674. if self.charset and isinstance(item, util.binary_type):
  2675. return item.decode(self.charset)
  2676. else:
  2677. return item
  2678. def __getattr__(self, attr):
  2679. item = getattr(self.rowproxy, attr)
  2680. if isinstance(item, _array):
  2681. item = item.tostring()
  2682. if self.charset and isinstance(item, util.binary_type):
  2683. return item.decode(self.charset)
  2684. else:
  2685. return item