compiler.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555
  1. # ext/compiler.py
  2. # Copyright (C) 2005-2024 the SQLAlchemy authors and contributors
  3. # <see AUTHORS file>
  4. #
  5. # This module is part of SQLAlchemy and is released under
  6. # the MIT License: https://www.opensource.org/licenses/mit-license.php
  7. # mypy: ignore-errors
  8. r"""Provides an API for creation of custom ClauseElements and compilers.
  9. Synopsis
  10. ========
  11. Usage involves the creation of one or more
  12. :class:`~sqlalchemy.sql.expression.ClauseElement` subclasses and one or
  13. more callables defining its compilation::
  14. from sqlalchemy.ext.compiler import compiles
  15. from sqlalchemy.sql.expression import ColumnClause
  16. class MyColumn(ColumnClause):
  17. inherit_cache = True
  18. @compiles(MyColumn)
  19. def compile_mycolumn(element, compiler, **kw):
  20. return "[%s]" % element.name
  21. Above, ``MyColumn`` extends :class:`~sqlalchemy.sql.expression.ColumnClause`,
  22. the base expression element for named column objects. The ``compiles``
  23. decorator registers itself with the ``MyColumn`` class so that it is invoked
  24. when the object is compiled to a string::
  25. from sqlalchemy import select
  26. s = select(MyColumn('x'), MyColumn('y'))
  27. print(str(s))
  28. Produces::
  29. SELECT [x], [y]
  30. Dialect-specific compilation rules
  31. ==================================
  32. Compilers can also be made dialect-specific. The appropriate compiler will be
  33. invoked for the dialect in use::
  34. from sqlalchemy.schema import DDLElement
  35. class AlterColumn(DDLElement):
  36. inherit_cache = False
  37. def __init__(self, column, cmd):
  38. self.column = column
  39. self.cmd = cmd
  40. @compiles(AlterColumn)
  41. def visit_alter_column(element, compiler, **kw):
  42. return "ALTER COLUMN %s ..." % element.column.name
  43. @compiles(AlterColumn, 'postgresql')
  44. def visit_alter_column(element, compiler, **kw):
  45. return "ALTER TABLE %s ALTER COLUMN %s ..." % (element.table.name,
  46. element.column.name)
  47. The second ``visit_alter_table`` will be invoked when any ``postgresql``
  48. dialect is used.
  49. .. _compilerext_compiling_subelements:
  50. Compiling sub-elements of a custom expression construct
  51. =======================================================
  52. The ``compiler`` argument is the
  53. :class:`~sqlalchemy.engine.interfaces.Compiled` object in use. This object
  54. can be inspected for any information about the in-progress compilation,
  55. including ``compiler.dialect``, ``compiler.statement`` etc. The
  56. :class:`~sqlalchemy.sql.compiler.SQLCompiler` and
  57. :class:`~sqlalchemy.sql.compiler.DDLCompiler` both include a ``process()``
  58. method which can be used for compilation of embedded attributes::
  59. from sqlalchemy.sql.expression import Executable, ClauseElement
  60. class InsertFromSelect(Executable, ClauseElement):
  61. inherit_cache = False
  62. def __init__(self, table, select):
  63. self.table = table
  64. self.select = select
  65. @compiles(InsertFromSelect)
  66. def visit_insert_from_select(element, compiler, **kw):
  67. return "INSERT INTO %s (%s)" % (
  68. compiler.process(element.table, asfrom=True, **kw),
  69. compiler.process(element.select, **kw)
  70. )
  71. insert = InsertFromSelect(t1, select(t1).where(t1.c.x>5))
  72. print(insert)
  73. Produces::
  74. "INSERT INTO mytable (SELECT mytable.x, mytable.y, mytable.z
  75. FROM mytable WHERE mytable.x > :x_1)"
  76. .. note::
  77. The above ``InsertFromSelect`` construct is only an example, this actual
  78. functionality is already available using the
  79. :meth:`_expression.Insert.from_select` method.
  80. Cross Compiling between SQL and DDL compilers
  81. ---------------------------------------------
  82. SQL and DDL constructs are each compiled using different base compilers -
  83. ``SQLCompiler`` and ``DDLCompiler``. A common need is to access the
  84. compilation rules of SQL expressions from within a DDL expression. The
  85. ``DDLCompiler`` includes an accessor ``sql_compiler`` for this reason, such as
  86. below where we generate a CHECK constraint that embeds a SQL expression::
  87. @compiles(MyConstraint)
  88. def compile_my_constraint(constraint, ddlcompiler, **kw):
  89. kw['literal_binds'] = True
  90. return "CONSTRAINT %s CHECK (%s)" % (
  91. constraint.name,
  92. ddlcompiler.sql_compiler.process(
  93. constraint.expression, **kw)
  94. )
  95. Above, we add an additional flag to the process step as called by
  96. :meth:`.SQLCompiler.process`, which is the ``literal_binds`` flag. This
  97. indicates that any SQL expression which refers to a :class:`.BindParameter`
  98. object or other "literal" object such as those which refer to strings or
  99. integers should be rendered **in-place**, rather than being referred to as
  100. a bound parameter; when emitting DDL, bound parameters are typically not
  101. supported.
  102. Changing the default compilation of existing constructs
  103. =======================================================
  104. The compiler extension applies just as well to the existing constructs. When
  105. overriding the compilation of a built in SQL construct, the @compiles
  106. decorator is invoked upon the appropriate class (be sure to use the class,
  107. i.e. ``Insert`` or ``Select``, instead of the creation function such
  108. as ``insert()`` or ``select()``).
  109. Within the new compilation function, to get at the "original" compilation
  110. routine, use the appropriate visit_XXX method - this
  111. because compiler.process() will call upon the overriding routine and cause
  112. an endless loop. Such as, to add "prefix" to all insert statements::
  113. from sqlalchemy.sql.expression import Insert
  114. @compiles(Insert)
  115. def prefix_inserts(insert, compiler, **kw):
  116. return compiler.visit_insert(insert.prefix_with("some prefix"), **kw)
  117. The above compiler will prefix all INSERT statements with "some prefix" when
  118. compiled.
  119. .. _type_compilation_extension:
  120. Changing Compilation of Types
  121. =============================
  122. ``compiler`` works for types, too, such as below where we implement the
  123. MS-SQL specific 'max' keyword for ``String``/``VARCHAR``::
  124. @compiles(String, 'mssql')
  125. @compiles(VARCHAR, 'mssql')
  126. def compile_varchar(element, compiler, **kw):
  127. if element.length == 'max':
  128. return "VARCHAR('max')"
  129. else:
  130. return compiler.visit_VARCHAR(element, **kw)
  131. foo = Table('foo', metadata,
  132. Column('data', VARCHAR('max'))
  133. )
  134. Subclassing Guidelines
  135. ======================
  136. A big part of using the compiler extension is subclassing SQLAlchemy
  137. expression constructs. To make this easier, the expression and
  138. schema packages feature a set of "bases" intended for common tasks.
  139. A synopsis is as follows:
  140. * :class:`~sqlalchemy.sql.expression.ClauseElement` - This is the root
  141. expression class. Any SQL expression can be derived from this base, and is
  142. probably the best choice for longer constructs such as specialized INSERT
  143. statements.
  144. * :class:`~sqlalchemy.sql.expression.ColumnElement` - The root of all
  145. "column-like" elements. Anything that you'd place in the "columns" clause of
  146. a SELECT statement (as well as order by and group by) can derive from this -
  147. the object will automatically have Python "comparison" behavior.
  148. :class:`~sqlalchemy.sql.expression.ColumnElement` classes want to have a
  149. ``type`` member which is expression's return type. This can be established
  150. at the instance level in the constructor, or at the class level if its
  151. generally constant::
  152. class timestamp(ColumnElement):
  153. type = TIMESTAMP()
  154. inherit_cache = True
  155. * :class:`~sqlalchemy.sql.functions.FunctionElement` - This is a hybrid of a
  156. ``ColumnElement`` and a "from clause" like object, and represents a SQL
  157. function or stored procedure type of call. Since most databases support
  158. statements along the line of "SELECT FROM <some function>"
  159. ``FunctionElement`` adds in the ability to be used in the FROM clause of a
  160. ``select()`` construct::
  161. from sqlalchemy.sql.expression import FunctionElement
  162. class coalesce(FunctionElement):
  163. name = 'coalesce'
  164. inherit_cache = True
  165. @compiles(coalesce)
  166. def compile(element, compiler, **kw):
  167. return "coalesce(%s)" % compiler.process(element.clauses, **kw)
  168. @compiles(coalesce, 'oracle')
  169. def compile(element, compiler, **kw):
  170. if len(element.clauses) > 2:
  171. raise TypeError("coalesce only supports two arguments on Oracle")
  172. return "nvl(%s)" % compiler.process(element.clauses, **kw)
  173. * :class:`.ExecutableDDLElement` - The root of all DDL expressions,
  174. like CREATE TABLE, ALTER TABLE, etc. Compilation of
  175. :class:`.ExecutableDDLElement` subclasses is issued by a
  176. :class:`.DDLCompiler` instead of a :class:`.SQLCompiler`.
  177. :class:`.ExecutableDDLElement` can also be used as an event hook in
  178. conjunction with event hooks like :meth:`.DDLEvents.before_create` and
  179. :meth:`.DDLEvents.after_create`, allowing the construct to be invoked
  180. automatically during CREATE TABLE and DROP TABLE sequences.
  181. .. seealso::
  182. :ref:`metadata_ddl_toplevel` - contains examples of associating
  183. :class:`.DDL` objects (which are themselves :class:`.ExecutableDDLElement`
  184. instances) with :class:`.DDLEvents` event hooks.
  185. * :class:`~sqlalchemy.sql.expression.Executable` - This is a mixin which
  186. should be used with any expression class that represents a "standalone"
  187. SQL statement that can be passed directly to an ``execute()`` method. It
  188. is already implicit within ``DDLElement`` and ``FunctionElement``.
  189. Most of the above constructs also respond to SQL statement caching. A
  190. subclassed construct will want to define the caching behavior for the object,
  191. which usually means setting the flag ``inherit_cache`` to the value of
  192. ``False`` or ``True``. See the next section :ref:`compilerext_caching`
  193. for background.
  194. .. _compilerext_caching:
  195. Enabling Caching Support for Custom Constructs
  196. ==============================================
  197. SQLAlchemy as of version 1.4 includes a
  198. :ref:`SQL compilation caching facility <sql_caching>` which will allow
  199. equivalent SQL constructs to cache their stringified form, along with other
  200. structural information used to fetch results from the statement.
  201. For reasons discussed at :ref:`caching_caveats`, the implementation of this
  202. caching system takes a conservative approach towards including custom SQL
  203. constructs and/or subclasses within the caching system. This includes that
  204. any user-defined SQL constructs, including all the examples for this
  205. extension, will not participate in caching by default unless they positively
  206. assert that they are able to do so. The :attr:`.HasCacheKey.inherit_cache`
  207. attribute when set to ``True`` at the class level of a specific subclass
  208. will indicate that instances of this class may be safely cached, using the
  209. cache key generation scheme of the immediate superclass. This applies
  210. for example to the "synopsis" example indicated previously::
  211. class MyColumn(ColumnClause):
  212. inherit_cache = True
  213. @compiles(MyColumn)
  214. def compile_mycolumn(element, compiler, **kw):
  215. return "[%s]" % element.name
  216. Above, the ``MyColumn`` class does not include any new state that
  217. affects its SQL compilation; the cache key of ``MyColumn`` instances will
  218. make use of that of the ``ColumnClause`` superclass, meaning it will take
  219. into account the class of the object (``MyColumn``), the string name and
  220. datatype of the object::
  221. >>> MyColumn("some_name", String())._generate_cache_key()
  222. CacheKey(
  223. key=('0', <class '__main__.MyColumn'>,
  224. 'name', 'some_name',
  225. 'type', (<class 'sqlalchemy.sql.sqltypes.String'>,
  226. ('length', None), ('collation', None))
  227. ), bindparams=[])
  228. For objects that are likely to be **used liberally as components within many
  229. larger statements**, such as :class:`_schema.Column` subclasses and custom SQL
  230. datatypes, it's important that **caching be enabled as much as possible**, as
  231. this may otherwise negatively affect performance.
  232. An example of an object that **does** contain state which affects its SQL
  233. compilation is the one illustrated at :ref:`compilerext_compiling_subelements`;
  234. this is an "INSERT FROM SELECT" construct that combines together a
  235. :class:`_schema.Table` as well as a :class:`_sql.Select` construct, each of
  236. which independently affect the SQL string generation of the construct. For
  237. this class, the example illustrates that it simply does not participate in
  238. caching::
  239. class InsertFromSelect(Executable, ClauseElement):
  240. inherit_cache = False
  241. def __init__(self, table, select):
  242. self.table = table
  243. self.select = select
  244. @compiles(InsertFromSelect)
  245. def visit_insert_from_select(element, compiler, **kw):
  246. return "INSERT INTO %s (%s)" % (
  247. compiler.process(element.table, asfrom=True, **kw),
  248. compiler.process(element.select, **kw)
  249. )
  250. While it is also possible that the above ``InsertFromSelect`` could be made to
  251. produce a cache key that is composed of that of the :class:`_schema.Table` and
  252. :class:`_sql.Select` components together, the API for this is not at the moment
  253. fully public. However, for an "INSERT FROM SELECT" construct, which is only
  254. used by itself for specific operations, caching is not as critical as in the
  255. previous example.
  256. For objects that are **used in relative isolation and are generally
  257. standalone**, such as custom :term:`DML` constructs like an "INSERT FROM
  258. SELECT", **caching is generally less critical** as the lack of caching for such
  259. a construct will have only localized implications for that specific operation.
  260. Further Examples
  261. ================
  262. "UTC timestamp" function
  263. -------------------------
  264. A function that works like "CURRENT_TIMESTAMP" except applies the
  265. appropriate conversions so that the time is in UTC time. Timestamps are best
  266. stored in relational databases as UTC, without time zones. UTC so that your
  267. database doesn't think time has gone backwards in the hour when daylight
  268. savings ends, without timezones because timezones are like character
  269. encodings - they're best applied only at the endpoints of an application
  270. (i.e. convert to UTC upon user input, re-apply desired timezone upon display).
  271. For PostgreSQL and Microsoft SQL Server::
  272. from sqlalchemy.sql import expression
  273. from sqlalchemy.ext.compiler import compiles
  274. from sqlalchemy.types import DateTime
  275. class utcnow(expression.FunctionElement):
  276. type = DateTime()
  277. inherit_cache = True
  278. @compiles(utcnow, 'postgresql')
  279. def pg_utcnow(element, compiler, **kw):
  280. return "TIMEZONE('utc', CURRENT_TIMESTAMP)"
  281. @compiles(utcnow, 'mssql')
  282. def ms_utcnow(element, compiler, **kw):
  283. return "GETUTCDATE()"
  284. Example usage::
  285. from sqlalchemy import (
  286. Table, Column, Integer, String, DateTime, MetaData
  287. )
  288. metadata = MetaData()
  289. event = Table("event", metadata,
  290. Column("id", Integer, primary_key=True),
  291. Column("description", String(50), nullable=False),
  292. Column("timestamp", DateTime, server_default=utcnow())
  293. )
  294. "GREATEST" function
  295. -------------------
  296. The "GREATEST" function is given any number of arguments and returns the one
  297. that is of the highest value - its equivalent to Python's ``max``
  298. function. A SQL standard version versus a CASE based version which only
  299. accommodates two arguments::
  300. from sqlalchemy.sql import expression, case
  301. from sqlalchemy.ext.compiler import compiles
  302. from sqlalchemy.types import Numeric
  303. class greatest(expression.FunctionElement):
  304. type = Numeric()
  305. name = 'greatest'
  306. inherit_cache = True
  307. @compiles(greatest)
  308. def default_greatest(element, compiler, **kw):
  309. return compiler.visit_function(element)
  310. @compiles(greatest, 'sqlite')
  311. @compiles(greatest, 'mssql')
  312. @compiles(greatest, 'oracle')
  313. def case_greatest(element, compiler, **kw):
  314. arg1, arg2 = list(element.clauses)
  315. return compiler.process(case((arg1 > arg2, arg1), else_=arg2), **kw)
  316. Example usage::
  317. Session.query(Account).\
  318. filter(
  319. greatest(
  320. Account.checking_balance,
  321. Account.savings_balance) > 10000
  322. )
  323. "false" expression
  324. ------------------
  325. Render a "false" constant expression, rendering as "0" on platforms that
  326. don't have a "false" constant::
  327. from sqlalchemy.sql import expression
  328. from sqlalchemy.ext.compiler import compiles
  329. class sql_false(expression.ColumnElement):
  330. inherit_cache = True
  331. @compiles(sql_false)
  332. def default_false(element, compiler, **kw):
  333. return "false"
  334. @compiles(sql_false, 'mssql')
  335. @compiles(sql_false, 'mysql')
  336. @compiles(sql_false, 'oracle')
  337. def int_false(element, compiler, **kw):
  338. return "0"
  339. Example usage::
  340. from sqlalchemy import select, union_all
  341. exp = union_all(
  342. select(users.c.name, sql_false().label("enrolled")),
  343. select(customers.c.name, customers.c.enrolled)
  344. )
  345. """
  346. from .. import exc
  347. from ..sql import sqltypes
  348. def compiles(class_, *specs):
  349. """Register a function as a compiler for a
  350. given :class:`_expression.ClauseElement` type."""
  351. def decorate(fn):
  352. # get an existing @compiles handler
  353. existing = class_.__dict__.get("_compiler_dispatcher", None)
  354. # get the original handler. All ClauseElement classes have one
  355. # of these, but some TypeEngine classes will not.
  356. existing_dispatch = getattr(class_, "_compiler_dispatch", None)
  357. if not existing:
  358. existing = _dispatcher()
  359. if existing_dispatch:
  360. def _wrap_existing_dispatch(element, compiler, **kw):
  361. try:
  362. return existing_dispatch(element, compiler, **kw)
  363. except exc.UnsupportedCompilationError as uce:
  364. raise exc.UnsupportedCompilationError(
  365. compiler,
  366. type(element),
  367. message="%s construct has no default "
  368. "compilation handler." % type(element),
  369. ) from uce
  370. existing.specs["default"] = _wrap_existing_dispatch
  371. # TODO: why is the lambda needed ?
  372. setattr(
  373. class_,
  374. "_compiler_dispatch",
  375. lambda *arg, **kw: existing(*arg, **kw),
  376. )
  377. setattr(class_, "_compiler_dispatcher", existing)
  378. if specs:
  379. for s in specs:
  380. existing.specs[s] = fn
  381. else:
  382. existing.specs["default"] = fn
  383. return fn
  384. return decorate
  385. def deregister(class_):
  386. """Remove all custom compilers associated with a given
  387. :class:`_expression.ClauseElement` type.
  388. """
  389. if hasattr(class_, "_compiler_dispatcher"):
  390. class_._compiler_dispatch = class_._original_compiler_dispatch
  391. del class_._compiler_dispatcher
  392. class _dispatcher:
  393. def __init__(self):
  394. self.specs = {}
  395. def __call__(self, element, compiler, **kw):
  396. # TODO: yes, this could also switch off of DBAPI in use.
  397. fn = self.specs.get(compiler.dialect.name, None)
  398. if not fn:
  399. try:
  400. fn = self.specs["default"]
  401. except KeyError as ke:
  402. raise exc.UnsupportedCompilationError(
  403. compiler,
  404. type(element),
  405. message="%s construct has no default "
  406. "compilation handler." % type(element),
  407. ) from ke
  408. # if compilation includes add_to_result_map, collect add_to_result_map
  409. # arguments from the user-defined callable, which are probably none
  410. # because this is not public API. if it wasn't called, then call it
  411. # ourselves.
  412. arm = kw.get("add_to_result_map", None)
  413. if arm:
  414. arm_collection = []
  415. kw["add_to_result_map"] = lambda *args: arm_collection.append(args)
  416. expr = fn(element, compiler, **kw)
  417. if arm:
  418. if not arm_collection:
  419. arm_collection.append(
  420. (None, None, (element,), sqltypes.NULLTYPE)
  421. )
  422. for tup in arm_collection:
  423. arm(*tup)
  424. return expr