base.py 113 KB

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