base.py 135 KB

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