SQLAlchemy 2.0.47__cp313-cp313t-win32.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (274) hide show
  1. sqlalchemy/__init__.py +283 -0
  2. sqlalchemy/connectors/__init__.py +18 -0
  3. sqlalchemy/connectors/aioodbc.py +184 -0
  4. sqlalchemy/connectors/asyncio.py +429 -0
  5. sqlalchemy/connectors/pyodbc.py +250 -0
  6. sqlalchemy/cyextension/__init__.py +6 -0
  7. sqlalchemy/cyextension/collections.cp313t-win32.pyd +0 -0
  8. sqlalchemy/cyextension/collections.pyx +409 -0
  9. sqlalchemy/cyextension/immutabledict.cp313t-win32.pyd +0 -0
  10. sqlalchemy/cyextension/immutabledict.pxd +8 -0
  11. sqlalchemy/cyextension/immutabledict.pyx +133 -0
  12. sqlalchemy/cyextension/processors.cp313t-win32.pyd +0 -0
  13. sqlalchemy/cyextension/processors.pyx +68 -0
  14. sqlalchemy/cyextension/resultproxy.cp313t-win32.pyd +0 -0
  15. sqlalchemy/cyextension/resultproxy.pyx +102 -0
  16. sqlalchemy/cyextension/util.cp313t-win32.pyd +0 -0
  17. sqlalchemy/cyextension/util.pyx +90 -0
  18. sqlalchemy/dialects/__init__.py +62 -0
  19. sqlalchemy/dialects/_typing.py +30 -0
  20. sqlalchemy/dialects/mssql/__init__.py +88 -0
  21. sqlalchemy/dialects/mssql/aioodbc.py +63 -0
  22. sqlalchemy/dialects/mssql/base.py +4093 -0
  23. sqlalchemy/dialects/mssql/information_schema.py +285 -0
  24. sqlalchemy/dialects/mssql/json.py +129 -0
  25. sqlalchemy/dialects/mssql/provision.py +185 -0
  26. sqlalchemy/dialects/mssql/pymssql.py +126 -0
  27. sqlalchemy/dialects/mssql/pyodbc.py +760 -0
  28. sqlalchemy/dialects/mysql/__init__.py +104 -0
  29. sqlalchemy/dialects/mysql/aiomysql.py +250 -0
  30. sqlalchemy/dialects/mysql/asyncmy.py +231 -0
  31. sqlalchemy/dialects/mysql/base.py +3949 -0
  32. sqlalchemy/dialects/mysql/cymysql.py +106 -0
  33. sqlalchemy/dialects/mysql/dml.py +225 -0
  34. sqlalchemy/dialects/mysql/enumerated.py +282 -0
  35. sqlalchemy/dialects/mysql/expression.py +146 -0
  36. sqlalchemy/dialects/mysql/json.py +91 -0
  37. sqlalchemy/dialects/mysql/mariadb.py +72 -0
  38. sqlalchemy/dialects/mysql/mariadbconnector.py +322 -0
  39. sqlalchemy/dialects/mysql/mysqlconnector.py +302 -0
  40. sqlalchemy/dialects/mysql/mysqldb.py +314 -0
  41. sqlalchemy/dialects/mysql/provision.py +153 -0
  42. sqlalchemy/dialects/mysql/pymysql.py +158 -0
  43. sqlalchemy/dialects/mysql/pyodbc.py +157 -0
  44. sqlalchemy/dialects/mysql/reflection.py +727 -0
  45. sqlalchemy/dialects/mysql/reserved_words.py +570 -0
  46. sqlalchemy/dialects/mysql/types.py +835 -0
  47. sqlalchemy/dialects/oracle/__init__.py +81 -0
  48. sqlalchemy/dialects/oracle/base.py +3802 -0
  49. sqlalchemy/dialects/oracle/cx_oracle.py +1555 -0
  50. sqlalchemy/dialects/oracle/dictionary.py +507 -0
  51. sqlalchemy/dialects/oracle/oracledb.py +941 -0
  52. sqlalchemy/dialects/oracle/provision.py +297 -0
  53. sqlalchemy/dialects/oracle/types.py +316 -0
  54. sqlalchemy/dialects/oracle/vector.py +365 -0
  55. sqlalchemy/dialects/postgresql/__init__.py +167 -0
  56. sqlalchemy/dialects/postgresql/_psycopg_common.py +189 -0
  57. sqlalchemy/dialects/postgresql/array.py +519 -0
  58. sqlalchemy/dialects/postgresql/asyncpg.py +1284 -0
  59. sqlalchemy/dialects/postgresql/base.py +5378 -0
  60. sqlalchemy/dialects/postgresql/dml.py +339 -0
  61. sqlalchemy/dialects/postgresql/ext.py +540 -0
  62. sqlalchemy/dialects/postgresql/hstore.py +406 -0
  63. sqlalchemy/dialects/postgresql/json.py +404 -0
  64. sqlalchemy/dialects/postgresql/named_types.py +524 -0
  65. sqlalchemy/dialects/postgresql/operators.py +129 -0
  66. sqlalchemy/dialects/postgresql/pg8000.py +669 -0
  67. sqlalchemy/dialects/postgresql/pg_catalog.py +326 -0
  68. sqlalchemy/dialects/postgresql/provision.py +183 -0
  69. sqlalchemy/dialects/postgresql/psycopg.py +862 -0
  70. sqlalchemy/dialects/postgresql/psycopg2.py +892 -0
  71. sqlalchemy/dialects/postgresql/psycopg2cffi.py +61 -0
  72. sqlalchemy/dialects/postgresql/ranges.py +1031 -0
  73. sqlalchemy/dialects/postgresql/types.py +313 -0
  74. sqlalchemy/dialects/sqlite/__init__.py +57 -0
  75. sqlalchemy/dialects/sqlite/aiosqlite.py +482 -0
  76. sqlalchemy/dialects/sqlite/base.py +3056 -0
  77. sqlalchemy/dialects/sqlite/dml.py +263 -0
  78. sqlalchemy/dialects/sqlite/json.py +92 -0
  79. sqlalchemy/dialects/sqlite/provision.py +229 -0
  80. sqlalchemy/dialects/sqlite/pysqlcipher.py +157 -0
  81. sqlalchemy/dialects/sqlite/pysqlite.py +756 -0
  82. sqlalchemy/dialects/type_migration_guidelines.txt +145 -0
  83. sqlalchemy/engine/__init__.py +62 -0
  84. sqlalchemy/engine/_py_processors.py +136 -0
  85. sqlalchemy/engine/_py_row.py +128 -0
  86. sqlalchemy/engine/_py_util.py +74 -0
  87. sqlalchemy/engine/base.py +3390 -0
  88. sqlalchemy/engine/characteristics.py +155 -0
  89. sqlalchemy/engine/create.py +893 -0
  90. sqlalchemy/engine/cursor.py +2298 -0
  91. sqlalchemy/engine/default.py +2394 -0
  92. sqlalchemy/engine/events.py +965 -0
  93. sqlalchemy/engine/interfaces.py +3471 -0
  94. sqlalchemy/engine/mock.py +134 -0
  95. sqlalchemy/engine/processors.py +61 -0
  96. sqlalchemy/engine/reflection.py +2102 -0
  97. sqlalchemy/engine/result.py +2399 -0
  98. sqlalchemy/engine/row.py +400 -0
  99. sqlalchemy/engine/strategies.py +16 -0
  100. sqlalchemy/engine/url.py +924 -0
  101. sqlalchemy/engine/util.py +167 -0
  102. sqlalchemy/event/__init__.py +26 -0
  103. sqlalchemy/event/api.py +220 -0
  104. sqlalchemy/event/attr.py +676 -0
  105. sqlalchemy/event/base.py +472 -0
  106. sqlalchemy/event/legacy.py +258 -0
  107. sqlalchemy/event/registry.py +390 -0
  108. sqlalchemy/events.py +17 -0
  109. sqlalchemy/exc.py +832 -0
  110. sqlalchemy/ext/__init__.py +11 -0
  111. sqlalchemy/ext/associationproxy.py +2027 -0
  112. sqlalchemy/ext/asyncio/__init__.py +25 -0
  113. sqlalchemy/ext/asyncio/base.py +281 -0
  114. sqlalchemy/ext/asyncio/engine.py +1471 -0
  115. sqlalchemy/ext/asyncio/exc.py +21 -0
  116. sqlalchemy/ext/asyncio/result.py +965 -0
  117. sqlalchemy/ext/asyncio/scoping.py +1599 -0
  118. sqlalchemy/ext/asyncio/session.py +1947 -0
  119. sqlalchemy/ext/automap.py +1701 -0
  120. sqlalchemy/ext/baked.py +570 -0
  121. sqlalchemy/ext/compiler.py +600 -0
  122. sqlalchemy/ext/declarative/__init__.py +65 -0
  123. sqlalchemy/ext/declarative/extensions.py +564 -0
  124. sqlalchemy/ext/horizontal_shard.py +478 -0
  125. sqlalchemy/ext/hybrid.py +1535 -0
  126. sqlalchemy/ext/indexable.py +364 -0
  127. sqlalchemy/ext/instrumentation.py +450 -0
  128. sqlalchemy/ext/mutable.py +1085 -0
  129. sqlalchemy/ext/mypy/__init__.py +6 -0
  130. sqlalchemy/ext/mypy/apply.py +324 -0
  131. sqlalchemy/ext/mypy/decl_class.py +515 -0
  132. sqlalchemy/ext/mypy/infer.py +590 -0
  133. sqlalchemy/ext/mypy/names.py +335 -0
  134. sqlalchemy/ext/mypy/plugin.py +303 -0
  135. sqlalchemy/ext/mypy/util.py +357 -0
  136. sqlalchemy/ext/orderinglist.py +439 -0
  137. sqlalchemy/ext/serializer.py +185 -0
  138. sqlalchemy/future/__init__.py +16 -0
  139. sqlalchemy/future/engine.py +15 -0
  140. sqlalchemy/inspection.py +174 -0
  141. sqlalchemy/log.py +288 -0
  142. sqlalchemy/orm/__init__.py +171 -0
  143. sqlalchemy/orm/_orm_constructors.py +2661 -0
  144. sqlalchemy/orm/_typing.py +179 -0
  145. sqlalchemy/orm/attributes.py +2845 -0
  146. sqlalchemy/orm/base.py +971 -0
  147. sqlalchemy/orm/bulk_persistence.py +2135 -0
  148. sqlalchemy/orm/clsregistry.py +571 -0
  149. sqlalchemy/orm/collections.py +1627 -0
  150. sqlalchemy/orm/context.py +3334 -0
  151. sqlalchemy/orm/decl_api.py +2004 -0
  152. sqlalchemy/orm/decl_base.py +2192 -0
  153. sqlalchemy/orm/dependency.py +1302 -0
  154. sqlalchemy/orm/descriptor_props.py +1092 -0
  155. sqlalchemy/orm/dynamic.py +300 -0
  156. sqlalchemy/orm/evaluator.py +379 -0
  157. sqlalchemy/orm/events.py +3252 -0
  158. sqlalchemy/orm/exc.py +237 -0
  159. sqlalchemy/orm/identity.py +302 -0
  160. sqlalchemy/orm/instrumentation.py +754 -0
  161. sqlalchemy/orm/interfaces.py +1496 -0
  162. sqlalchemy/orm/loading.py +1686 -0
  163. sqlalchemy/orm/mapped_collection.py +557 -0
  164. sqlalchemy/orm/mapper.py +4444 -0
  165. sqlalchemy/orm/path_registry.py +809 -0
  166. sqlalchemy/orm/persistence.py +1788 -0
  167. sqlalchemy/orm/properties.py +935 -0
  168. sqlalchemy/orm/query.py +3459 -0
  169. sqlalchemy/orm/relationships.py +3508 -0
  170. sqlalchemy/orm/scoping.py +2148 -0
  171. sqlalchemy/orm/session.py +5280 -0
  172. sqlalchemy/orm/state.py +1168 -0
  173. sqlalchemy/orm/state_changes.py +196 -0
  174. sqlalchemy/orm/strategies.py +3470 -0
  175. sqlalchemy/orm/strategy_options.py +2568 -0
  176. sqlalchemy/orm/sync.py +164 -0
  177. sqlalchemy/orm/unitofwork.py +796 -0
  178. sqlalchemy/orm/util.py +2403 -0
  179. sqlalchemy/orm/writeonly.py +674 -0
  180. sqlalchemy/pool/__init__.py +44 -0
  181. sqlalchemy/pool/base.py +1524 -0
  182. sqlalchemy/pool/events.py +375 -0
  183. sqlalchemy/pool/impl.py +588 -0
  184. sqlalchemy/py.typed +0 -0
  185. sqlalchemy/schema.py +69 -0
  186. sqlalchemy/sql/__init__.py +145 -0
  187. sqlalchemy/sql/_dml_constructors.py +132 -0
  188. sqlalchemy/sql/_elements_constructors.py +1872 -0
  189. sqlalchemy/sql/_orm_types.py +20 -0
  190. sqlalchemy/sql/_py_util.py +75 -0
  191. sqlalchemy/sql/_selectable_constructors.py +763 -0
  192. sqlalchemy/sql/_typing.py +482 -0
  193. sqlalchemy/sql/annotation.py +587 -0
  194. sqlalchemy/sql/base.py +2293 -0
  195. sqlalchemy/sql/cache_key.py +1057 -0
  196. sqlalchemy/sql/coercions.py +1404 -0
  197. sqlalchemy/sql/compiler.py +8081 -0
  198. sqlalchemy/sql/crud.py +1752 -0
  199. sqlalchemy/sql/ddl.py +1444 -0
  200. sqlalchemy/sql/default_comparator.py +551 -0
  201. sqlalchemy/sql/dml.py +1850 -0
  202. sqlalchemy/sql/elements.py +5589 -0
  203. sqlalchemy/sql/events.py +458 -0
  204. sqlalchemy/sql/expression.py +159 -0
  205. sqlalchemy/sql/functions.py +2158 -0
  206. sqlalchemy/sql/lambdas.py +1442 -0
  207. sqlalchemy/sql/naming.py +209 -0
  208. sqlalchemy/sql/operators.py +2623 -0
  209. sqlalchemy/sql/roles.py +323 -0
  210. sqlalchemy/sql/schema.py +6222 -0
  211. sqlalchemy/sql/selectable.py +7265 -0
  212. sqlalchemy/sql/sqltypes.py +3930 -0
  213. sqlalchemy/sql/traversals.py +1024 -0
  214. sqlalchemy/sql/type_api.py +2368 -0
  215. sqlalchemy/sql/util.py +1485 -0
  216. sqlalchemy/sql/visitors.py +1164 -0
  217. sqlalchemy/testing/__init__.py +96 -0
  218. sqlalchemy/testing/assertions.py +994 -0
  219. sqlalchemy/testing/assertsql.py +520 -0
  220. sqlalchemy/testing/asyncio.py +135 -0
  221. sqlalchemy/testing/config.py +434 -0
  222. sqlalchemy/testing/engines.py +483 -0
  223. sqlalchemy/testing/entities.py +117 -0
  224. sqlalchemy/testing/exclusions.py +476 -0
  225. sqlalchemy/testing/fixtures/__init__.py +28 -0
  226. sqlalchemy/testing/fixtures/base.py +384 -0
  227. sqlalchemy/testing/fixtures/mypy.py +332 -0
  228. sqlalchemy/testing/fixtures/orm.py +227 -0
  229. sqlalchemy/testing/fixtures/sql.py +482 -0
  230. sqlalchemy/testing/pickleable.py +155 -0
  231. sqlalchemy/testing/plugin/__init__.py +6 -0
  232. sqlalchemy/testing/plugin/bootstrap.py +51 -0
  233. sqlalchemy/testing/plugin/plugin_base.py +828 -0
  234. sqlalchemy/testing/plugin/pytestplugin.py +892 -0
  235. sqlalchemy/testing/profiling.py +329 -0
  236. sqlalchemy/testing/provision.py +603 -0
  237. sqlalchemy/testing/requirements.py +1945 -0
  238. sqlalchemy/testing/schema.py +198 -0
  239. sqlalchemy/testing/suite/__init__.py +19 -0
  240. sqlalchemy/testing/suite/test_cte.py +237 -0
  241. sqlalchemy/testing/suite/test_ddl.py +389 -0
  242. sqlalchemy/testing/suite/test_deprecations.py +153 -0
  243. sqlalchemy/testing/suite/test_dialect.py +776 -0
  244. sqlalchemy/testing/suite/test_insert.py +630 -0
  245. sqlalchemy/testing/suite/test_reflection.py +3557 -0
  246. sqlalchemy/testing/suite/test_results.py +504 -0
  247. sqlalchemy/testing/suite/test_rowcount.py +258 -0
  248. sqlalchemy/testing/suite/test_select.py +2010 -0
  249. sqlalchemy/testing/suite/test_sequence.py +317 -0
  250. sqlalchemy/testing/suite/test_types.py +2147 -0
  251. sqlalchemy/testing/suite/test_unicode_ddl.py +189 -0
  252. sqlalchemy/testing/suite/test_update_delete.py +139 -0
  253. sqlalchemy/testing/util.py +535 -0
  254. sqlalchemy/testing/warnings.py +52 -0
  255. sqlalchemy/types.py +74 -0
  256. sqlalchemy/util/__init__.py +162 -0
  257. sqlalchemy/util/_collections.py +712 -0
  258. sqlalchemy/util/_concurrency_py3k.py +288 -0
  259. sqlalchemy/util/_has_cy.py +40 -0
  260. sqlalchemy/util/_py_collections.py +541 -0
  261. sqlalchemy/util/compat.py +421 -0
  262. sqlalchemy/util/concurrency.py +110 -0
  263. sqlalchemy/util/deprecations.py +401 -0
  264. sqlalchemy/util/langhelpers.py +2203 -0
  265. sqlalchemy/util/preloaded.py +150 -0
  266. sqlalchemy/util/queue.py +322 -0
  267. sqlalchemy/util/tool_support.py +201 -0
  268. sqlalchemy/util/topological.py +120 -0
  269. sqlalchemy/util/typing.py +734 -0
  270. sqlalchemy-2.0.47.dist-info/METADATA +243 -0
  271. sqlalchemy-2.0.47.dist-info/RECORD +274 -0
  272. sqlalchemy-2.0.47.dist-info/WHEEL +5 -0
  273. sqlalchemy-2.0.47.dist-info/licenses/LICENSE +19 -0
  274. sqlalchemy-2.0.47.dist-info/top_level.txt +1 -0
@@ -0,0 +1,600 @@
1
+ # ext/compiler.py
2
+ # Copyright (C) 2005-2026 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
+
8
+ r"""Provides an API for creation of custom ClauseElements and compilers.
9
+
10
+ Synopsis
11
+ ========
12
+
13
+ Usage involves the creation of one or more
14
+ :class:`~sqlalchemy.sql.expression.ClauseElement` subclasses and one or
15
+ more callables defining its compilation::
16
+
17
+ from sqlalchemy.ext.compiler import compiles
18
+ from sqlalchemy.sql.expression import ColumnClause
19
+
20
+
21
+ class MyColumn(ColumnClause):
22
+ inherit_cache = True
23
+
24
+
25
+ @compiles(MyColumn)
26
+ def compile_mycolumn(element, compiler, **kw):
27
+ return "[%s]" % element.name
28
+
29
+ Above, ``MyColumn`` extends :class:`~sqlalchemy.sql.expression.ColumnClause`,
30
+ the base expression element for named column objects. The ``compiles``
31
+ decorator registers itself with the ``MyColumn`` class so that it is invoked
32
+ when the object is compiled to a string::
33
+
34
+ from sqlalchemy import select
35
+
36
+ s = select(MyColumn("x"), MyColumn("y"))
37
+ print(str(s))
38
+
39
+ Produces:
40
+
41
+ .. sourcecode:: sql
42
+
43
+ SELECT [x], [y]
44
+
45
+ Dialect-specific compilation rules
46
+ ==================================
47
+
48
+ Compilers can also be made dialect-specific. The appropriate compiler will be
49
+ invoked for the dialect in use::
50
+
51
+ from sqlalchemy.schema import DDLElement
52
+
53
+
54
+ class AlterColumn(DDLElement):
55
+ inherit_cache = False
56
+
57
+ def __init__(self, column, cmd):
58
+ self.column = column
59
+ self.cmd = cmd
60
+
61
+
62
+ @compiles(AlterColumn)
63
+ def visit_alter_column(element, compiler, **kw):
64
+ return "ALTER COLUMN %s ..." % element.column.name
65
+
66
+
67
+ @compiles(AlterColumn, "postgresql")
68
+ def visit_alter_column(element, compiler, **kw):
69
+ return "ALTER TABLE %s ALTER COLUMN %s ..." % (
70
+ element.table.name,
71
+ element.column.name,
72
+ )
73
+
74
+ The second ``visit_alter_table`` will be invoked when any ``postgresql``
75
+ dialect is used.
76
+
77
+ .. _compilerext_compiling_subelements:
78
+
79
+ Compiling sub-elements of a custom expression construct
80
+ =======================================================
81
+
82
+ The ``compiler`` argument is the
83
+ :class:`~sqlalchemy.engine.interfaces.Compiled` object in use. This object
84
+ can be inspected for any information about the in-progress compilation,
85
+ including ``compiler.dialect``, ``compiler.statement`` etc. The
86
+ :class:`~sqlalchemy.sql.compiler.SQLCompiler` and
87
+ :class:`~sqlalchemy.sql.compiler.DDLCompiler` both include a ``process()``
88
+ method which can be used for compilation of embedded attributes::
89
+
90
+ from sqlalchemy.sql.expression import Executable, ClauseElement
91
+
92
+
93
+ class InsertFromSelect(Executable, ClauseElement):
94
+ inherit_cache = False
95
+
96
+ def __init__(self, table, select):
97
+ self.table = table
98
+ self.select = select
99
+
100
+
101
+ @compiles(InsertFromSelect)
102
+ def visit_insert_from_select(element, compiler, **kw):
103
+ return "INSERT INTO %s (%s)" % (
104
+ compiler.process(element.table, asfrom=True, **kw),
105
+ compiler.process(element.select, **kw),
106
+ )
107
+
108
+
109
+ insert = InsertFromSelect(t1, select(t1).where(t1.c.x > 5))
110
+ print(insert)
111
+
112
+ Produces (formatted for readability):
113
+
114
+ .. sourcecode:: sql
115
+
116
+ INSERT INTO mytable (
117
+ SELECT mytable.x, mytable.y, mytable.z
118
+ FROM mytable
119
+ WHERE mytable.x > :x_1
120
+ )
121
+
122
+ .. note::
123
+
124
+ The above ``InsertFromSelect`` construct is only an example, this actual
125
+ functionality is already available using the
126
+ :meth:`_expression.Insert.from_select` method.
127
+
128
+
129
+ Cross Compiling between SQL and DDL compilers
130
+ ---------------------------------------------
131
+
132
+ SQL and DDL constructs are each compiled using different base compilers -
133
+ ``SQLCompiler`` and ``DDLCompiler``. A common need is to access the
134
+ compilation rules of SQL expressions from within a DDL expression. The
135
+ ``DDLCompiler`` includes an accessor ``sql_compiler`` for this reason, such as
136
+ below where we generate a CHECK constraint that embeds a SQL expression::
137
+
138
+ @compiles(MyConstraint)
139
+ def compile_my_constraint(constraint, ddlcompiler, **kw):
140
+ kw["literal_binds"] = True
141
+ return "CONSTRAINT %s CHECK (%s)" % (
142
+ constraint.name,
143
+ ddlcompiler.sql_compiler.process(constraint.expression, **kw),
144
+ )
145
+
146
+ Above, we add an additional flag to the process step as called by
147
+ :meth:`.SQLCompiler.process`, which is the ``literal_binds`` flag. This
148
+ indicates that any SQL expression which refers to a :class:`.BindParameter`
149
+ object or other "literal" object such as those which refer to strings or
150
+ integers should be rendered **in-place**, rather than being referred to as
151
+ a bound parameter; when emitting DDL, bound parameters are typically not
152
+ supported.
153
+
154
+
155
+ Changing the default compilation of existing constructs
156
+ =======================================================
157
+
158
+ The compiler extension applies just as well to the existing constructs. When
159
+ overriding the compilation of a built in SQL construct, the @compiles
160
+ decorator is invoked upon the appropriate class (be sure to use the class,
161
+ i.e. ``Insert`` or ``Select``, instead of the creation function such
162
+ as ``insert()`` or ``select()``).
163
+
164
+ Within the new compilation function, to get at the "original" compilation
165
+ routine, use the appropriate visit_XXX method - this
166
+ because compiler.process() will call upon the overriding routine and cause
167
+ an endless loop. Such as, to add "prefix" to all insert statements::
168
+
169
+ from sqlalchemy.sql.expression import Insert
170
+
171
+
172
+ @compiles(Insert)
173
+ def prefix_inserts(insert, compiler, **kw):
174
+ return compiler.visit_insert(insert.prefix_with("some prefix"), **kw)
175
+
176
+ The above compiler will prefix all INSERT statements with "some prefix" when
177
+ compiled.
178
+
179
+ .. _type_compilation_extension:
180
+
181
+ Changing Compilation of Types
182
+ =============================
183
+
184
+ ``compiler`` works for types, too, such as below where we implement the
185
+ MS-SQL specific 'max' keyword for ``String``/``VARCHAR``::
186
+
187
+ @compiles(String, "mssql")
188
+ @compiles(VARCHAR, "mssql")
189
+ def compile_varchar(element, compiler, **kw):
190
+ if element.length == "max":
191
+ return "VARCHAR('max')"
192
+ else:
193
+ return compiler.visit_VARCHAR(element, **kw)
194
+
195
+
196
+ foo = Table("foo", metadata, Column("data", VARCHAR("max")))
197
+
198
+ Subclassing Guidelines
199
+ ======================
200
+
201
+ A big part of using the compiler extension is subclassing SQLAlchemy
202
+ expression constructs. To make this easier, the expression and
203
+ schema packages feature a set of "bases" intended for common tasks.
204
+ A synopsis is as follows:
205
+
206
+ * :class:`~sqlalchemy.sql.expression.ClauseElement` - This is the root
207
+ expression class. Any SQL expression can be derived from this base, and is
208
+ probably the best choice for longer constructs such as specialized INSERT
209
+ statements.
210
+
211
+ * :class:`~sqlalchemy.sql.expression.ColumnElement` - The root of all
212
+ "column-like" elements. Anything that you'd place in the "columns" clause of
213
+ a SELECT statement (as well as order by and group by) can derive from this -
214
+ the object will automatically have Python "comparison" behavior.
215
+
216
+ :class:`~sqlalchemy.sql.expression.ColumnElement` classes want to have a
217
+ ``type`` member which is expression's return type. This can be established
218
+ at the instance level in the constructor, or at the class level if its
219
+ generally constant::
220
+
221
+ class timestamp(ColumnElement):
222
+ type = TIMESTAMP()
223
+ inherit_cache = True
224
+
225
+ * :class:`~sqlalchemy.sql.functions.FunctionElement` - This is a hybrid of a
226
+ ``ColumnElement`` and a "from clause" like object, and represents a SQL
227
+ function or stored procedure type of call. Since most databases support
228
+ statements along the line of "SELECT FROM <some function>"
229
+ ``FunctionElement`` adds in the ability to be used in the FROM clause of a
230
+ ``select()`` construct::
231
+
232
+ from sqlalchemy.sql.expression import FunctionElement
233
+
234
+
235
+ class coalesce(FunctionElement):
236
+ name = "coalesce"
237
+ inherit_cache = True
238
+
239
+
240
+ @compiles(coalesce)
241
+ def compile(element, compiler, **kw):
242
+ return "coalesce(%s)" % compiler.process(element.clauses, **kw)
243
+
244
+
245
+ @compiles(coalesce, "oracle")
246
+ def compile(element, compiler, **kw):
247
+ if len(element.clauses) > 2:
248
+ raise TypeError(
249
+ "coalesce only supports two arguments on " "Oracle Database"
250
+ )
251
+ return "nvl(%s)" % compiler.process(element.clauses, **kw)
252
+
253
+ * :class:`.ExecutableDDLElement` - The root of all DDL expressions,
254
+ like CREATE TABLE, ALTER TABLE, etc. Compilation of
255
+ :class:`.ExecutableDDLElement` subclasses is issued by a
256
+ :class:`.DDLCompiler` instead of a :class:`.SQLCompiler`.
257
+ :class:`.ExecutableDDLElement` can also be used as an event hook in
258
+ conjunction with event hooks like :meth:`.DDLEvents.before_create` and
259
+ :meth:`.DDLEvents.after_create`, allowing the construct to be invoked
260
+ automatically during CREATE TABLE and DROP TABLE sequences.
261
+
262
+ .. seealso::
263
+
264
+ :ref:`metadata_ddl_toplevel` - contains examples of associating
265
+ :class:`.DDL` objects (which are themselves :class:`.ExecutableDDLElement`
266
+ instances) with :class:`.DDLEvents` event hooks.
267
+
268
+ * :class:`~sqlalchemy.sql.expression.Executable` - This is a mixin which
269
+ should be used with any expression class that represents a "standalone"
270
+ SQL statement that can be passed directly to an ``execute()`` method. It
271
+ is already implicit within ``DDLElement`` and ``FunctionElement``.
272
+
273
+ Most of the above constructs also respond to SQL statement caching. A
274
+ subclassed construct will want to define the caching behavior for the object,
275
+ which usually means setting the flag ``inherit_cache`` to the value of
276
+ ``False`` or ``True``. See the next section :ref:`compilerext_caching`
277
+ for background.
278
+
279
+
280
+ .. _compilerext_caching:
281
+
282
+ Enabling Caching Support for Custom Constructs
283
+ ==============================================
284
+
285
+ SQLAlchemy as of version 1.4 includes a
286
+ :ref:`SQL compilation caching facility <sql_caching>` which will allow
287
+ equivalent SQL constructs to cache their stringified form, along with other
288
+ structural information used to fetch results from the statement.
289
+
290
+ For reasons discussed at :ref:`caching_caveats`, the implementation of this
291
+ caching system takes a conservative approach towards including custom SQL
292
+ constructs and/or subclasses within the caching system. This includes that
293
+ any user-defined SQL constructs, including all the examples for this
294
+ extension, will not participate in caching by default unless they positively
295
+ assert that they are able to do so. The :attr:`.HasCacheKey.inherit_cache`
296
+ attribute when set to ``True`` at the class level of a specific subclass
297
+ will indicate that instances of this class may be safely cached, using the
298
+ cache key generation scheme of the immediate superclass. This applies
299
+ for example to the "synopsis" example indicated previously::
300
+
301
+ class MyColumn(ColumnClause):
302
+ inherit_cache = True
303
+
304
+
305
+ @compiles(MyColumn)
306
+ def compile_mycolumn(element, compiler, **kw):
307
+ return "[%s]" % element.name
308
+
309
+ Above, the ``MyColumn`` class does not include any new state that
310
+ affects its SQL compilation; the cache key of ``MyColumn`` instances will
311
+ make use of that of the ``ColumnClause`` superclass, meaning it will take
312
+ into account the class of the object (``MyColumn``), the string name and
313
+ datatype of the object::
314
+
315
+ >>> MyColumn("some_name", String())._generate_cache_key()
316
+ CacheKey(
317
+ key=('0', <class '__main__.MyColumn'>,
318
+ 'name', 'some_name',
319
+ 'type', (<class 'sqlalchemy.sql.sqltypes.String'>,
320
+ ('length', None), ('collation', None))
321
+ ), bindparams=[])
322
+
323
+ For objects that are likely to be **used liberally as components within many
324
+ larger statements**, such as :class:`_schema.Column` subclasses and custom SQL
325
+ datatypes, it's important that **caching be enabled as much as possible**, as
326
+ this may otherwise negatively affect performance.
327
+
328
+ An example of an object that **does** contain state which affects its SQL
329
+ compilation is the one illustrated at :ref:`compilerext_compiling_subelements`;
330
+ this is an "INSERT FROM SELECT" construct that combines together a
331
+ :class:`_schema.Table` as well as a :class:`_sql.Select` construct, each of
332
+ which independently affect the SQL string generation of the construct. For
333
+ this class, the example illustrates that it simply does not participate in
334
+ caching::
335
+
336
+ class InsertFromSelect(Executable, ClauseElement):
337
+ inherit_cache = False
338
+
339
+ def __init__(self, table, select):
340
+ self.table = table
341
+ self.select = select
342
+
343
+
344
+ @compiles(InsertFromSelect)
345
+ def visit_insert_from_select(element, compiler, **kw):
346
+ return "INSERT INTO %s (%s)" % (
347
+ compiler.process(element.table, asfrom=True, **kw),
348
+ compiler.process(element.select, **kw),
349
+ )
350
+
351
+ While it is also possible that the above ``InsertFromSelect`` could be made to
352
+ produce a cache key that is composed of that of the :class:`_schema.Table` and
353
+ :class:`_sql.Select` components together, the API for this is not at the moment
354
+ fully public. However, for an "INSERT FROM SELECT" construct, which is only
355
+ used by itself for specific operations, caching is not as critical as in the
356
+ previous example.
357
+
358
+ For objects that are **used in relative isolation and are generally
359
+ standalone**, such as custom :term:`DML` constructs like an "INSERT FROM
360
+ SELECT", **caching is generally less critical** as the lack of caching for such
361
+ a construct will have only localized implications for that specific operation.
362
+
363
+
364
+ Further Examples
365
+ ================
366
+
367
+ "UTC timestamp" function
368
+ -------------------------
369
+
370
+ A function that works like "CURRENT_TIMESTAMP" except applies the
371
+ appropriate conversions so that the time is in UTC time. Timestamps are best
372
+ stored in relational databases as UTC, without time zones. UTC so that your
373
+ database doesn't think time has gone backwards in the hour when daylight
374
+ savings ends, without timezones because timezones are like character
375
+ encodings - they're best applied only at the endpoints of an application
376
+ (i.e. convert to UTC upon user input, re-apply desired timezone upon display).
377
+
378
+ For PostgreSQL and Microsoft SQL Server::
379
+
380
+ from sqlalchemy.sql import expression
381
+ from sqlalchemy.ext.compiler import compiles
382
+ from sqlalchemy.types import DateTime
383
+
384
+
385
+ class utcnow(expression.FunctionElement):
386
+ type = DateTime()
387
+ inherit_cache = True
388
+
389
+
390
+ @compiles(utcnow, "postgresql")
391
+ def pg_utcnow(element, compiler, **kw):
392
+ return "TIMEZONE('utc', CURRENT_TIMESTAMP)"
393
+
394
+
395
+ @compiles(utcnow, "mssql")
396
+ def ms_utcnow(element, compiler, **kw):
397
+ return "GETUTCDATE()"
398
+
399
+ Example usage::
400
+
401
+ from sqlalchemy import Table, Column, Integer, String, DateTime, MetaData
402
+
403
+ metadata = MetaData()
404
+ event = Table(
405
+ "event",
406
+ metadata,
407
+ Column("id", Integer, primary_key=True),
408
+ Column("description", String(50), nullable=False),
409
+ Column("timestamp", DateTime, server_default=utcnow()),
410
+ )
411
+
412
+ "GREATEST" function
413
+ -------------------
414
+
415
+ The "GREATEST" function is given any number of arguments and returns the one
416
+ that is of the highest value - its equivalent to Python's ``max``
417
+ function. A SQL standard version versus a CASE based version which only
418
+ accommodates two arguments::
419
+
420
+ from sqlalchemy.sql import expression, case
421
+ from sqlalchemy.ext.compiler import compiles
422
+ from sqlalchemy.types import Numeric
423
+
424
+
425
+ class greatest(expression.FunctionElement):
426
+ type = Numeric()
427
+ name = "greatest"
428
+ inherit_cache = True
429
+
430
+
431
+ @compiles(greatest)
432
+ def default_greatest(element, compiler, **kw):
433
+ return compiler.visit_function(element)
434
+
435
+
436
+ @compiles(greatest, "sqlite")
437
+ @compiles(greatest, "mssql")
438
+ @compiles(greatest, "oracle")
439
+ def case_greatest(element, compiler, **kw):
440
+ arg1, arg2 = list(element.clauses)
441
+ return compiler.process(case((arg1 > arg2, arg1), else_=arg2), **kw)
442
+
443
+ Example usage::
444
+
445
+ Session.query(Account).filter(
446
+ greatest(Account.checking_balance, Account.savings_balance) > 10000
447
+ )
448
+
449
+ "false" expression
450
+ ------------------
451
+
452
+ Render a "false" constant expression, rendering as "0" on platforms that
453
+ don't have a "false" constant::
454
+
455
+ from sqlalchemy.sql import expression
456
+ from sqlalchemy.ext.compiler import compiles
457
+
458
+
459
+ class sql_false(expression.ColumnElement):
460
+ inherit_cache = True
461
+
462
+
463
+ @compiles(sql_false)
464
+ def default_false(element, compiler, **kw):
465
+ return "false"
466
+
467
+
468
+ @compiles(sql_false, "mssql")
469
+ @compiles(sql_false, "mysql")
470
+ @compiles(sql_false, "oracle")
471
+ def int_false(element, compiler, **kw):
472
+ return "0"
473
+
474
+ Example usage::
475
+
476
+ from sqlalchemy import select, union_all
477
+
478
+ exp = union_all(
479
+ select(users.c.name, sql_false().label("enrolled")),
480
+ select(customers.c.name, customers.c.enrolled),
481
+ )
482
+
483
+ """
484
+ from __future__ import annotations
485
+
486
+ from typing import Any
487
+ from typing import Callable
488
+ from typing import Dict
489
+ from typing import Type
490
+ from typing import TYPE_CHECKING
491
+ from typing import TypeVar
492
+
493
+ from .. import exc
494
+ from ..sql import sqltypes
495
+
496
+ if TYPE_CHECKING:
497
+ from ..sql.compiler import SQLCompiler
498
+
499
+ _F = TypeVar("_F", bound=Callable[..., Any])
500
+
501
+
502
+ def compiles(class_: Type[Any], *specs: str) -> Callable[[_F], _F]:
503
+ """Register a function as a compiler for a
504
+ given :class:`_expression.ClauseElement` type."""
505
+
506
+ def decorate(fn: _F) -> _F:
507
+ # get an existing @compiles handler
508
+ existing = class_.__dict__.get("_compiler_dispatcher", None)
509
+
510
+ # get the original handler. All ClauseElement classes have one
511
+ # of these, but some TypeEngine classes will not.
512
+ existing_dispatch = getattr(class_, "_compiler_dispatch", None)
513
+
514
+ if not existing:
515
+ existing = _dispatcher()
516
+
517
+ if existing_dispatch:
518
+
519
+ def _wrap_existing_dispatch(
520
+ element: Any, compiler: SQLCompiler, **kw: Any
521
+ ) -> Any:
522
+ try:
523
+ return existing_dispatch(element, compiler, **kw)
524
+ except exc.UnsupportedCompilationError as uce:
525
+ raise exc.UnsupportedCompilationError(
526
+ compiler,
527
+ type(element),
528
+ message="%s construct has no default "
529
+ "compilation handler." % type(element),
530
+ ) from uce
531
+
532
+ existing.specs["default"] = _wrap_existing_dispatch
533
+
534
+ # TODO: why is the lambda needed ?
535
+ setattr(
536
+ class_,
537
+ "_compiler_dispatch",
538
+ lambda *arg, **kw: existing(*arg, **kw),
539
+ )
540
+ setattr(class_, "_compiler_dispatcher", existing)
541
+
542
+ if specs:
543
+ for s in specs:
544
+ existing.specs[s] = fn
545
+
546
+ else:
547
+ existing.specs["default"] = fn
548
+ return fn
549
+
550
+ return decorate
551
+
552
+
553
+ def deregister(class_: Type[Any]) -> None:
554
+ """Remove all custom compilers associated with a given
555
+ :class:`_expression.ClauseElement` type.
556
+
557
+ """
558
+
559
+ if hasattr(class_, "_compiler_dispatcher"):
560
+ class_._compiler_dispatch = class_._original_compiler_dispatch
561
+ del class_._compiler_dispatcher
562
+
563
+
564
+ class _dispatcher:
565
+ def __init__(self) -> None:
566
+ self.specs: Dict[str, Callable[..., Any]] = {}
567
+
568
+ def __call__(self, element: Any, compiler: SQLCompiler, **kw: Any) -> Any:
569
+ # TODO: yes, this could also switch off of DBAPI in use.
570
+ fn = self.specs.get(compiler.dialect.name, None)
571
+ if not fn:
572
+ try:
573
+ fn = self.specs["default"]
574
+ except KeyError as ke:
575
+ raise exc.UnsupportedCompilationError(
576
+ compiler,
577
+ type(element),
578
+ message="%s construct has no default "
579
+ "compilation handler." % type(element),
580
+ ) from ke
581
+
582
+ # if compilation includes add_to_result_map, collect add_to_result_map
583
+ # arguments from the user-defined callable, which are probably none
584
+ # because this is not public API. if it wasn't called, then call it
585
+ # ourselves.
586
+ arm = kw.get("add_to_result_map", None)
587
+ if arm:
588
+ arm_collection = []
589
+ kw["add_to_result_map"] = lambda *args: arm_collection.append(args)
590
+
591
+ expr = fn(element, compiler, **kw)
592
+
593
+ if arm:
594
+ if not arm_collection:
595
+ arm_collection.append(
596
+ (None, None, (element,), sqltypes.NULLTYPE)
597
+ )
598
+ for tup in arm_collection:
599
+ arm(*tup)
600
+ return expr
@@ -0,0 +1,65 @@
1
+ # ext/declarative/__init__.py
2
+ # Copyright (C) 2005-2026 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
+
9
+
10
+ from .extensions import AbstractConcreteBase
11
+ from .extensions import ConcreteBase
12
+ from .extensions import DeferredReflection
13
+ from ... import util
14
+ from ...orm.decl_api import as_declarative as _as_declarative
15
+ from ...orm.decl_api import declarative_base as _declarative_base
16
+ from ...orm.decl_api import DeclarativeMeta
17
+ from ...orm.decl_api import declared_attr
18
+ from ...orm.decl_api import has_inherited_table as _has_inherited_table
19
+ from ...orm.decl_api import synonym_for as _synonym_for
20
+
21
+
22
+ @util.moved_20(
23
+ "The ``declarative_base()`` function is now available as "
24
+ ":func:`sqlalchemy.orm.declarative_base`."
25
+ )
26
+ def declarative_base(*arg, **kw):
27
+ return _declarative_base(*arg, **kw)
28
+
29
+
30
+ @util.moved_20(
31
+ "The ``as_declarative()`` function is now available as "
32
+ ":func:`sqlalchemy.orm.as_declarative`"
33
+ )
34
+ def as_declarative(*arg, **kw):
35
+ return _as_declarative(*arg, **kw)
36
+
37
+
38
+ @util.moved_20(
39
+ "The ``has_inherited_table()`` function is now available as "
40
+ ":func:`sqlalchemy.orm.has_inherited_table`."
41
+ )
42
+ def has_inherited_table(*arg, **kw):
43
+ return _has_inherited_table(*arg, **kw)
44
+
45
+
46
+ @util.moved_20(
47
+ "The ``synonym_for()`` function is now available as "
48
+ ":func:`sqlalchemy.orm.synonym_for`"
49
+ )
50
+ def synonym_for(*arg, **kw):
51
+ return _synonym_for(*arg, **kw)
52
+
53
+
54
+ __all__ = [
55
+ "declarative_base",
56
+ "synonym_for",
57
+ "has_inherited_table",
58
+ "instrument_declarative",
59
+ "declared_attr",
60
+ "as_declarative",
61
+ "ConcreteBase",
62
+ "AbstractConcreteBase",
63
+ "DeclarativeMeta",
64
+ "DeferredReflection",
65
+ ]