base.py 118 KB

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