You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

509 lines
18KB

  1. # ext/compiler.py
  2. # Copyright (C) 2005-2021 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: http://www.opensource.org/licenses/mit-license.php
  7. r"""Provides an API for creation of custom ClauseElements and compilers.
  8. Synopsis
  9. ========
  10. Usage involves the creation of one or more
  11. :class:`~sqlalchemy.sql.expression.ClauseElement` subclasses and one or
  12. more callables defining its compilation::
  13. from sqlalchemy.ext.compiler import compiles
  14. from sqlalchemy.sql.expression import ColumnClause
  15. class MyColumn(ColumnClause):
  16. pass
  17. @compiles(MyColumn)
  18. def compile_mycolumn(element, compiler, **kw):
  19. return "[%s]" % element.name
  20. Above, ``MyColumn`` extends :class:`~sqlalchemy.sql.expression.ColumnClause`,
  21. the base expression element for named column objects. The ``compiles``
  22. decorator registers itself with the ``MyColumn`` class so that it is invoked
  23. when the object is compiled to a string::
  24. from sqlalchemy import select
  25. s = select(MyColumn('x'), MyColumn('y'))
  26. print(str(s))
  27. Produces::
  28. SELECT [x], [y]
  29. Dialect-specific compilation rules
  30. ==================================
  31. Compilers can also be made dialect-specific. The appropriate compiler will be
  32. invoked for the dialect in use::
  33. from sqlalchemy.schema import DDLElement
  34. class AlterColumn(DDLElement):
  35. def __init__(self, column, cmd):
  36. self.column = column
  37. self.cmd = cmd
  38. @compiles(AlterColumn)
  39. def visit_alter_column(element, compiler, **kw):
  40. return "ALTER COLUMN %s ..." % element.column.name
  41. @compiles(AlterColumn, 'postgresql')
  42. def visit_alter_column(element, compiler, **kw):
  43. return "ALTER TABLE %s ALTER COLUMN %s ..." % (element.table.name,
  44. element.column.name)
  45. The second ``visit_alter_table`` will be invoked when any ``postgresql``
  46. dialect is used.
  47. Compiling sub-elements of a custom expression construct
  48. =======================================================
  49. The ``compiler`` argument is the
  50. :class:`~sqlalchemy.engine.interfaces.Compiled` object in use. This object
  51. can be inspected for any information about the in-progress compilation,
  52. including ``compiler.dialect``, ``compiler.statement`` etc. The
  53. :class:`~sqlalchemy.sql.compiler.SQLCompiler` and
  54. :class:`~sqlalchemy.sql.compiler.DDLCompiler` both include a ``process()``
  55. method which can be used for compilation of embedded attributes::
  56. from sqlalchemy.sql.expression import Executable, ClauseElement
  57. class InsertFromSelect(Executable, ClauseElement):
  58. def __init__(self, table, select):
  59. self.table = table
  60. self.select = select
  61. @compiles(InsertFromSelect)
  62. def visit_insert_from_select(element, compiler, **kw):
  63. return "INSERT INTO %s (%s)" % (
  64. compiler.process(element.table, asfrom=True, **kw),
  65. compiler.process(element.select, **kw)
  66. )
  67. insert = InsertFromSelect(t1, select(t1).where(t1.c.x>5))
  68. print(insert)
  69. Produces::
  70. "INSERT INTO mytable (SELECT mytable.x, mytable.y, mytable.z
  71. FROM mytable WHERE mytable.x > :x_1)"
  72. .. note::
  73. The above ``InsertFromSelect`` construct is only an example, this actual
  74. functionality is already available using the
  75. :meth:`_expression.Insert.from_select` method.
  76. .. note::
  77. The above ``InsertFromSelect`` construct probably wants to have "autocommit"
  78. enabled. See :ref:`enabling_compiled_autocommit` for this step.
  79. Cross Compiling between SQL and DDL compilers
  80. ---------------------------------------------
  81. SQL and DDL constructs are each compiled using different base compilers -
  82. ``SQLCompiler`` and ``DDLCompiler``. A common need is to access the
  83. compilation rules of SQL expressions from within a DDL expression. The
  84. ``DDLCompiler`` includes an accessor ``sql_compiler`` for this reason, such as
  85. below where we generate a CHECK constraint that embeds a SQL expression::
  86. @compiles(MyConstraint)
  87. def compile_my_constraint(constraint, ddlcompiler, **kw):
  88. kw['literal_binds'] = True
  89. return "CONSTRAINT %s CHECK (%s)" % (
  90. constraint.name,
  91. ddlcompiler.sql_compiler.process(
  92. constraint.expression, **kw)
  93. )
  94. Above, we add an additional flag to the process step as called by
  95. :meth:`.SQLCompiler.process`, which is the ``literal_binds`` flag. This
  96. indicates that any SQL expression which refers to a :class:`.BindParameter`
  97. object or other "literal" object such as those which refer to strings or
  98. integers should be rendered **in-place**, rather than being referred to as
  99. a bound parameter; when emitting DDL, bound parameters are typically not
  100. supported.
  101. .. _enabling_compiled_autocommit:
  102. Enabling Autocommit on a Construct
  103. ==================================
  104. Recall from the section :ref:`autocommit` that the :class:`_engine.Engine`,
  105. when
  106. asked to execute a construct in the absence of a user-defined transaction,
  107. detects if the given construct represents DML or DDL, that is, a data
  108. modification or data definition statement, which requires (or may require,
  109. in the case of DDL) that the transaction generated by the DBAPI be committed
  110. (recall that DBAPI always has a transaction going on regardless of what
  111. SQLAlchemy does). Checking for this is actually accomplished by checking for
  112. the "autocommit" execution option on the construct. When building a
  113. construct like an INSERT derivation, a new DDL type, or perhaps a stored
  114. procedure that alters data, the "autocommit" option needs to be set in order
  115. for the statement to function with "connectionless" execution
  116. (as described in :ref:`dbengine_implicit`).
  117. Currently a quick way to do this is to subclass :class:`.Executable`, then
  118. add the "autocommit" flag to the ``_execution_options`` dictionary (note this
  119. is a "frozen" dictionary which supplies a generative ``union()`` method)::
  120. from sqlalchemy.sql.expression import Executable, ClauseElement
  121. class MyInsertThing(Executable, ClauseElement):
  122. _execution_options = \
  123. Executable._execution_options.union({'autocommit': True})
  124. More succinctly, if the construct is truly similar to an INSERT, UPDATE, or
  125. DELETE, :class:`.UpdateBase` can be used, which already is a subclass
  126. of :class:`.Executable`, :class:`_expression.ClauseElement` and includes the
  127. ``autocommit`` flag::
  128. from sqlalchemy.sql.expression import UpdateBase
  129. class MyInsertThing(UpdateBase):
  130. def __init__(self, ...):
  131. ...
  132. DDL elements that subclass :class:`.DDLElement` already have the
  133. "autocommit" flag turned on.
  134. Changing the default compilation of existing constructs
  135. =======================================================
  136. The compiler extension applies just as well to the existing constructs. When
  137. overriding the compilation of a built in SQL construct, the @compiles
  138. decorator is invoked upon the appropriate class (be sure to use the class,
  139. i.e. ``Insert`` or ``Select``, instead of the creation function such
  140. as ``insert()`` or ``select()``).
  141. Within the new compilation function, to get at the "original" compilation
  142. routine, use the appropriate visit_XXX method - this
  143. because compiler.process() will call upon the overriding routine and cause
  144. an endless loop. Such as, to add "prefix" to all insert statements::
  145. from sqlalchemy.sql.expression import Insert
  146. @compiles(Insert)
  147. def prefix_inserts(insert, compiler, **kw):
  148. return compiler.visit_insert(insert.prefix_with("some prefix"), **kw)
  149. The above compiler will prefix all INSERT statements with "some prefix" when
  150. compiled.
  151. .. _type_compilation_extension:
  152. Changing Compilation of Types
  153. =============================
  154. ``compiler`` works for types, too, such as below where we implement the
  155. MS-SQL specific 'max' keyword for ``String``/``VARCHAR``::
  156. @compiles(String, 'mssql')
  157. @compiles(VARCHAR, 'mssql')
  158. def compile_varchar(element, compiler, **kw):
  159. if element.length == 'max':
  160. return "VARCHAR('max')"
  161. else:
  162. return compiler.visit_VARCHAR(element, **kw)
  163. foo = Table('foo', metadata,
  164. Column('data', VARCHAR('max'))
  165. )
  166. Subclassing Guidelines
  167. ======================
  168. A big part of using the compiler extension is subclassing SQLAlchemy
  169. expression constructs. To make this easier, the expression and
  170. schema packages feature a set of "bases" intended for common tasks.
  171. A synopsis is as follows:
  172. * :class:`~sqlalchemy.sql.expression.ClauseElement` - This is the root
  173. expression class. Any SQL expression can be derived from this base, and is
  174. probably the best choice for longer constructs such as specialized INSERT
  175. statements.
  176. * :class:`~sqlalchemy.sql.expression.ColumnElement` - The root of all
  177. "column-like" elements. Anything that you'd place in the "columns" clause of
  178. a SELECT statement (as well as order by and group by) can derive from this -
  179. the object will automatically have Python "comparison" behavior.
  180. :class:`~sqlalchemy.sql.expression.ColumnElement` classes want to have a
  181. ``type`` member which is expression's return type. This can be established
  182. at the instance level in the constructor, or at the class level if its
  183. generally constant::
  184. class timestamp(ColumnElement):
  185. type = TIMESTAMP()
  186. * :class:`~sqlalchemy.sql.functions.FunctionElement` - This is a hybrid of a
  187. ``ColumnElement`` and a "from clause" like object, and represents a SQL
  188. function or stored procedure type of call. Since most databases support
  189. statements along the line of "SELECT FROM <some function>"
  190. ``FunctionElement`` adds in the ability to be used in the FROM clause of a
  191. ``select()`` construct::
  192. from sqlalchemy.sql.expression import FunctionElement
  193. class coalesce(FunctionElement):
  194. name = 'coalesce'
  195. @compiles(coalesce)
  196. def compile(element, compiler, **kw):
  197. return "coalesce(%s)" % compiler.process(element.clauses, **kw)
  198. @compiles(coalesce, 'oracle')
  199. def compile(element, compiler, **kw):
  200. if len(element.clauses) > 2:
  201. raise TypeError("coalesce only supports two arguments on Oracle")
  202. return "nvl(%s)" % compiler.process(element.clauses, **kw)
  203. * :class:`~sqlalchemy.schema.DDLElement` - The root of all DDL expressions,
  204. like CREATE TABLE, ALTER TABLE, etc. Compilation of ``DDLElement``
  205. subclasses is issued by a ``DDLCompiler`` instead of a ``SQLCompiler``.
  206. ``DDLElement`` also features ``Table`` and ``MetaData`` event hooks via the
  207. ``execute_at()`` method, allowing the construct to be invoked during CREATE
  208. TABLE and DROP TABLE sequences.
  209. * :class:`~sqlalchemy.sql.expression.Executable` - This is a mixin which
  210. should be used with any expression class that represents a "standalone"
  211. SQL statement that can be passed directly to an ``execute()`` method. It
  212. is already implicit within ``DDLElement`` and ``FunctionElement``.
  213. Further Examples
  214. ================
  215. "UTC timestamp" function
  216. -------------------------
  217. A function that works like "CURRENT_TIMESTAMP" except applies the
  218. appropriate conversions so that the time is in UTC time. Timestamps are best
  219. stored in relational databases as UTC, without time zones. UTC so that your
  220. database doesn't think time has gone backwards in the hour when daylight
  221. savings ends, without timezones because timezones are like character
  222. encodings - they're best applied only at the endpoints of an application
  223. (i.e. convert to UTC upon user input, re-apply desired timezone upon display).
  224. For PostgreSQL and Microsoft SQL Server::
  225. from sqlalchemy.sql import expression
  226. from sqlalchemy.ext.compiler import compiles
  227. from sqlalchemy.types import DateTime
  228. class utcnow(expression.FunctionElement):
  229. type = DateTime()
  230. @compiles(utcnow, 'postgresql')
  231. def pg_utcnow(element, compiler, **kw):
  232. return "TIMEZONE('utc', CURRENT_TIMESTAMP)"
  233. @compiles(utcnow, 'mssql')
  234. def ms_utcnow(element, compiler, **kw):
  235. return "GETUTCDATE()"
  236. Example usage::
  237. from sqlalchemy import (
  238. Table, Column, Integer, String, DateTime, MetaData
  239. )
  240. metadata = MetaData()
  241. event = Table("event", metadata,
  242. Column("id", Integer, primary_key=True),
  243. Column("description", String(50), nullable=False),
  244. Column("timestamp", DateTime, server_default=utcnow())
  245. )
  246. "GREATEST" function
  247. -------------------
  248. The "GREATEST" function is given any number of arguments and returns the one
  249. that is of the highest value - its equivalent to Python's ``max``
  250. function. A SQL standard version versus a CASE based version which only
  251. accommodates two arguments::
  252. from sqlalchemy.sql import expression, case
  253. from sqlalchemy.ext.compiler import compiles
  254. from sqlalchemy.types import Numeric
  255. class greatest(expression.FunctionElement):
  256. type = Numeric()
  257. name = 'greatest'
  258. @compiles(greatest)
  259. def default_greatest(element, compiler, **kw):
  260. return compiler.visit_function(element)
  261. @compiles(greatest, 'sqlite')
  262. @compiles(greatest, 'mssql')
  263. @compiles(greatest, 'oracle')
  264. def case_greatest(element, compiler, **kw):
  265. arg1, arg2 = list(element.clauses)
  266. return compiler.process(case([(arg1 > arg2, arg1)], else_=arg2), **kw)
  267. Example usage::
  268. Session.query(Account).\
  269. filter(
  270. greatest(
  271. Account.checking_balance,
  272. Account.savings_balance) > 10000
  273. )
  274. "false" expression
  275. ------------------
  276. Render a "false" constant expression, rendering as "0" on platforms that
  277. don't have a "false" constant::
  278. from sqlalchemy.sql import expression
  279. from sqlalchemy.ext.compiler import compiles
  280. class sql_false(expression.ColumnElement):
  281. pass
  282. @compiles(sql_false)
  283. def default_false(element, compiler, **kw):
  284. return "false"
  285. @compiles(sql_false, 'mssql')
  286. @compiles(sql_false, 'mysql')
  287. @compiles(sql_false, 'oracle')
  288. def int_false(element, compiler, **kw):
  289. return "0"
  290. Example usage::
  291. from sqlalchemy import select, union_all
  292. exp = union_all(
  293. select(users.c.name, sql_false().label("enrolled")),
  294. select(customers.c.name, customers.c.enrolled)
  295. )
  296. """
  297. from .. import exc
  298. from .. import util
  299. from ..sql import sqltypes
  300. def compiles(class_, *specs):
  301. """Register a function as a compiler for a
  302. given :class:`_expression.ClauseElement` type."""
  303. def decorate(fn):
  304. # get an existing @compiles handler
  305. existing = class_.__dict__.get("_compiler_dispatcher", None)
  306. # get the original handler. All ClauseElement classes have one
  307. # of these, but some TypeEngine classes will not.
  308. existing_dispatch = getattr(class_, "_compiler_dispatch", None)
  309. if not existing:
  310. existing = _dispatcher()
  311. if existing_dispatch:
  312. def _wrap_existing_dispatch(element, compiler, **kw):
  313. try:
  314. return existing_dispatch(element, compiler, **kw)
  315. except exc.UnsupportedCompilationError as uce:
  316. util.raise_(
  317. exc.UnsupportedCompilationError(
  318. compiler,
  319. type(element),
  320. message="%s construct has no default "
  321. "compilation handler." % type(element),
  322. ),
  323. from_=uce,
  324. )
  325. existing.specs["default"] = _wrap_existing_dispatch
  326. # TODO: why is the lambda needed ?
  327. setattr(
  328. class_,
  329. "_compiler_dispatch",
  330. lambda *arg, **kw: existing(*arg, **kw),
  331. )
  332. setattr(class_, "_compiler_dispatcher", existing)
  333. if specs:
  334. for s in specs:
  335. existing.specs[s] = fn
  336. else:
  337. existing.specs["default"] = fn
  338. return fn
  339. return decorate
  340. def deregister(class_):
  341. """Remove all custom compilers associated with a given
  342. :class:`_expression.ClauseElement` type.
  343. """
  344. if hasattr(class_, "_compiler_dispatcher"):
  345. class_._compiler_dispatch = class_._original_compiler_dispatch
  346. del class_._compiler_dispatcher
  347. class _dispatcher(object):
  348. def __init__(self):
  349. self.specs = {}
  350. def __call__(self, element, compiler, **kw):
  351. # TODO: yes, this could also switch off of DBAPI in use.
  352. fn = self.specs.get(compiler.dialect.name, None)
  353. if not fn:
  354. try:
  355. fn = self.specs["default"]
  356. except KeyError as ke:
  357. util.raise_(
  358. exc.UnsupportedCompilationError(
  359. compiler,
  360. type(element),
  361. message="%s construct has no default "
  362. "compilation handler." % type(element),
  363. ),
  364. replace_context=ke,
  365. )
  366. # if compilation includes add_to_result_map, collect add_to_result_map
  367. # arguments from the user-defined callable, which are probably none
  368. # because this is not public API. if it wasn't called, then call it
  369. # ourselves.
  370. arm = kw.get("add_to_result_map", None)
  371. if arm:
  372. arm_collection = []
  373. kw["add_to_result_map"] = lambda *args: arm_collection.append(args)
  374. expr = fn(element, compiler, **kw)
  375. if arm:
  376. if not arm_collection:
  377. arm_collection.append(
  378. (None, None, (element,), sqltypes.NULLTYPE)
  379. )
  380. for tup in arm_collection:
  381. arm(*tup)
  382. return expr