base.py 122 KB

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