base.py 135 KB

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