SQLAlchemy 2.0.36__cp313-cp313-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 (273) hide show
  1. SQLAlchemy-2.0.36.dist-info/LICENSE +19 -0
  2. SQLAlchemy-2.0.36.dist-info/METADATA +243 -0
  3. SQLAlchemy-2.0.36.dist-info/RECORD +273 -0
  4. SQLAlchemy-2.0.36.dist-info/WHEEL +5 -0
  5. SQLAlchemy-2.0.36.dist-info/top_level.txt +1 -0
  6. sqlalchemy/__init__.py +294 -0
  7. sqlalchemy/connectors/__init__.py +18 -0
  8. sqlalchemy/connectors/aioodbc.py +174 -0
  9. sqlalchemy/connectors/asyncio.py +213 -0
  10. sqlalchemy/connectors/pyodbc.py +249 -0
  11. sqlalchemy/cyextension/__init__.py +6 -0
  12. sqlalchemy/cyextension/collections.cp313-win32.pyd +0 -0
  13. sqlalchemy/cyextension/collections.pyx +409 -0
  14. sqlalchemy/cyextension/immutabledict.cp313-win32.pyd +0 -0
  15. sqlalchemy/cyextension/immutabledict.pxd +8 -0
  16. sqlalchemy/cyextension/immutabledict.pyx +133 -0
  17. sqlalchemy/cyextension/processors.cp313-win32.pyd +0 -0
  18. sqlalchemy/cyextension/processors.pyx +68 -0
  19. sqlalchemy/cyextension/resultproxy.cp313-win32.pyd +0 -0
  20. sqlalchemy/cyextension/resultproxy.pyx +102 -0
  21. sqlalchemy/cyextension/util.cp313-win32.pyd +0 -0
  22. sqlalchemy/cyextension/util.pyx +91 -0
  23. sqlalchemy/dialects/__init__.py +61 -0
  24. sqlalchemy/dialects/_typing.py +25 -0
  25. sqlalchemy/dialects/mssql/__init__.py +88 -0
  26. sqlalchemy/dialects/mssql/aioodbc.py +64 -0
  27. sqlalchemy/dialects/mssql/base.py +4010 -0
  28. sqlalchemy/dialects/mssql/information_schema.py +254 -0
  29. sqlalchemy/dialects/mssql/json.py +133 -0
  30. sqlalchemy/dialects/mssql/provision.py +162 -0
  31. sqlalchemy/dialects/mssql/pymssql.py +126 -0
  32. sqlalchemy/dialects/mssql/pyodbc.py +745 -0
  33. sqlalchemy/dialects/mysql/__init__.py +101 -0
  34. sqlalchemy/dialects/mysql/aiomysql.py +333 -0
  35. sqlalchemy/dialects/mysql/asyncmy.py +337 -0
  36. sqlalchemy/dialects/mysql/base.py +3494 -0
  37. sqlalchemy/dialects/mysql/cymysql.py +84 -0
  38. sqlalchemy/dialects/mysql/dml.py +219 -0
  39. sqlalchemy/dialects/mysql/enumerated.py +244 -0
  40. sqlalchemy/dialects/mysql/expression.py +141 -0
  41. sqlalchemy/dialects/mysql/json.py +81 -0
  42. sqlalchemy/dialects/mysql/mariadb.py +32 -0
  43. sqlalchemy/dialects/mysql/mariadbconnector.py +277 -0
  44. sqlalchemy/dialects/mysql/mysqlconnector.py +180 -0
  45. sqlalchemy/dialects/mysql/mysqldb.py +303 -0
  46. sqlalchemy/dialects/mysql/provision.py +110 -0
  47. sqlalchemy/dialects/mysql/pymysql.py +137 -0
  48. sqlalchemy/dialects/mysql/pyodbc.py +138 -0
  49. sqlalchemy/dialects/mysql/reflection.py +677 -0
  50. sqlalchemy/dialects/mysql/reserved_words.py +571 -0
  51. sqlalchemy/dialects/mysql/types.py +774 -0
  52. sqlalchemy/dialects/oracle/__init__.py +67 -0
  53. sqlalchemy/dialects/oracle/base.py +3271 -0
  54. sqlalchemy/dialects/oracle/cx_oracle.py +1483 -0
  55. sqlalchemy/dialects/oracle/dictionary.py +507 -0
  56. sqlalchemy/dialects/oracle/oracledb.py +431 -0
  57. sqlalchemy/dialects/oracle/provision.py +220 -0
  58. sqlalchemy/dialects/oracle/types.py +287 -0
  59. sqlalchemy/dialects/postgresql/__init__.py +167 -0
  60. sqlalchemy/dialects/postgresql/_psycopg_common.py +187 -0
  61. sqlalchemy/dialects/postgresql/array.py +425 -0
  62. sqlalchemy/dialects/postgresql/asyncpg.py +1274 -0
  63. sqlalchemy/dialects/postgresql/base.py +5008 -0
  64. sqlalchemy/dialects/postgresql/dml.py +310 -0
  65. sqlalchemy/dialects/postgresql/ext.py +496 -0
  66. sqlalchemy/dialects/postgresql/hstore.py +397 -0
  67. sqlalchemy/dialects/postgresql/json.py +333 -0
  68. sqlalchemy/dialects/postgresql/named_types.py +509 -0
  69. sqlalchemy/dialects/postgresql/operators.py +129 -0
  70. sqlalchemy/dialects/postgresql/pg8000.py +662 -0
  71. sqlalchemy/dialects/postgresql/pg_catalog.py +300 -0
  72. sqlalchemy/dialects/postgresql/provision.py +175 -0
  73. sqlalchemy/dialects/postgresql/psycopg.py +772 -0
  74. sqlalchemy/dialects/postgresql/psycopg2.py +886 -0
  75. sqlalchemy/dialects/postgresql/psycopg2cffi.py +61 -0
  76. sqlalchemy/dialects/postgresql/ranges.py +1029 -0
  77. sqlalchemy/dialects/postgresql/types.py +303 -0
  78. sqlalchemy/dialects/sqlite/__init__.py +57 -0
  79. sqlalchemy/dialects/sqlite/aiosqlite.py +396 -0
  80. sqlalchemy/dialects/sqlite/base.py +2805 -0
  81. sqlalchemy/dialects/sqlite/dml.py +240 -0
  82. sqlalchemy/dialects/sqlite/json.py +92 -0
  83. sqlalchemy/dialects/sqlite/provision.py +198 -0
  84. sqlalchemy/dialects/sqlite/pysqlcipher.py +155 -0
  85. sqlalchemy/dialects/sqlite/pysqlite.py +756 -0
  86. sqlalchemy/dialects/type_migration_guidelines.txt +145 -0
  87. sqlalchemy/engine/__init__.py +62 -0
  88. sqlalchemy/engine/_py_processors.py +136 -0
  89. sqlalchemy/engine/_py_row.py +128 -0
  90. sqlalchemy/engine/_py_util.py +74 -0
  91. sqlalchemy/engine/base.py +3375 -0
  92. sqlalchemy/engine/characteristics.py +155 -0
  93. sqlalchemy/engine/create.py +875 -0
  94. sqlalchemy/engine/cursor.py +2181 -0
  95. sqlalchemy/engine/default.py +2365 -0
  96. sqlalchemy/engine/events.py +951 -0
  97. sqlalchemy/engine/interfaces.py +3403 -0
  98. sqlalchemy/engine/mock.py +131 -0
  99. sqlalchemy/engine/processors.py +61 -0
  100. sqlalchemy/engine/reflection.py +2098 -0
  101. sqlalchemy/engine/result.py +2382 -0
  102. sqlalchemy/engine/row.py +401 -0
  103. sqlalchemy/engine/strategies.py +19 -0
  104. sqlalchemy/engine/url.py +910 -0
  105. sqlalchemy/engine/util.py +167 -0
  106. sqlalchemy/event/__init__.py +25 -0
  107. sqlalchemy/event/api.py +225 -0
  108. sqlalchemy/event/attr.py +655 -0
  109. sqlalchemy/event/base.py +470 -0
  110. sqlalchemy/event/legacy.py +246 -0
  111. sqlalchemy/event/registry.py +386 -0
  112. sqlalchemy/events.py +17 -0
  113. sqlalchemy/exc.py +830 -0
  114. sqlalchemy/ext/__init__.py +11 -0
  115. sqlalchemy/ext/associationproxy.py +2013 -0
  116. sqlalchemy/ext/asyncio/__init__.py +25 -0
  117. sqlalchemy/ext/asyncio/base.py +279 -0
  118. sqlalchemy/ext/asyncio/engine.py +1466 -0
  119. sqlalchemy/ext/asyncio/exc.py +21 -0
  120. sqlalchemy/ext/asyncio/result.py +961 -0
  121. sqlalchemy/ext/asyncio/scoping.py +1614 -0
  122. sqlalchemy/ext/asyncio/session.py +1936 -0
  123. sqlalchemy/ext/automap.py +1691 -0
  124. sqlalchemy/ext/baked.py +574 -0
  125. sqlalchemy/ext/compiler.py +570 -0
  126. sqlalchemy/ext/declarative/__init__.py +65 -0
  127. sqlalchemy/ext/declarative/extensions.py +548 -0
  128. sqlalchemy/ext/horizontal_shard.py +481 -0
  129. sqlalchemy/ext/hybrid.py +1514 -0
  130. sqlalchemy/ext/indexable.py +341 -0
  131. sqlalchemy/ext/instrumentation.py +450 -0
  132. sqlalchemy/ext/mutable.py +1073 -0
  133. sqlalchemy/ext/mypy/__init__.py +6 -0
  134. sqlalchemy/ext/mypy/apply.py +320 -0
  135. sqlalchemy/ext/mypy/decl_class.py +515 -0
  136. sqlalchemy/ext/mypy/infer.py +590 -0
  137. sqlalchemy/ext/mypy/names.py +335 -0
  138. sqlalchemy/ext/mypy/plugin.py +303 -0
  139. sqlalchemy/ext/mypy/util.py +357 -0
  140. sqlalchemy/ext/orderinglist.py +416 -0
  141. sqlalchemy/ext/serializer.py +181 -0
  142. sqlalchemy/future/__init__.py +16 -0
  143. sqlalchemy/future/engine.py +15 -0
  144. sqlalchemy/inspection.py +174 -0
  145. sqlalchemy/log.py +288 -0
  146. sqlalchemy/orm/__init__.py +170 -0
  147. sqlalchemy/orm/_orm_constructors.py +2571 -0
  148. sqlalchemy/orm/_typing.py +179 -0
  149. sqlalchemy/orm/attributes.py +2835 -0
  150. sqlalchemy/orm/base.py +973 -0
  151. sqlalchemy/orm/bulk_persistence.py +2123 -0
  152. sqlalchemy/orm/clsregistry.py +571 -0
  153. sqlalchemy/orm/collections.py +1620 -0
  154. sqlalchemy/orm/context.py +3268 -0
  155. sqlalchemy/orm/decl_api.py +1883 -0
  156. sqlalchemy/orm/decl_base.py +2190 -0
  157. sqlalchemy/orm/dependency.py +1304 -0
  158. sqlalchemy/orm/descriptor_props.py +1076 -0
  159. sqlalchemy/orm/dynamic.py +300 -0
  160. sqlalchemy/orm/evaluator.py +379 -0
  161. sqlalchemy/orm/events.py +3261 -0
  162. sqlalchemy/orm/exc.py +228 -0
  163. sqlalchemy/orm/identity.py +302 -0
  164. sqlalchemy/orm/instrumentation.py +754 -0
  165. sqlalchemy/orm/interfaces.py +1474 -0
  166. sqlalchemy/orm/loading.py +1682 -0
  167. sqlalchemy/orm/mapped_collection.py +557 -0
  168. sqlalchemy/orm/mapper.py +4432 -0
  169. sqlalchemy/orm/path_registry.py +811 -0
  170. sqlalchemy/orm/persistence.py +1782 -0
  171. sqlalchemy/orm/properties.py +886 -0
  172. sqlalchemy/orm/query.py +3396 -0
  173. sqlalchemy/orm/relationships.py +3500 -0
  174. sqlalchemy/orm/scoping.py +2165 -0
  175. sqlalchemy/orm/session.py +5301 -0
  176. sqlalchemy/orm/state.py +1143 -0
  177. sqlalchemy/orm/state_changes.py +198 -0
  178. sqlalchemy/orm/strategies.py +3473 -0
  179. sqlalchemy/orm/strategy_options.py +2569 -0
  180. sqlalchemy/orm/sync.py +164 -0
  181. sqlalchemy/orm/unitofwork.py +796 -0
  182. sqlalchemy/orm/util.py +2424 -0
  183. sqlalchemy/orm/writeonly.py +678 -0
  184. sqlalchemy/pool/__init__.py +44 -0
  185. sqlalchemy/pool/base.py +1515 -0
  186. sqlalchemy/pool/events.py +370 -0
  187. sqlalchemy/pool/impl.py +581 -0
  188. sqlalchemy/py.typed +0 -0
  189. sqlalchemy/schema.py +70 -0
  190. sqlalchemy/sql/__init__.py +145 -0
  191. sqlalchemy/sql/_dml_constructors.py +140 -0
  192. sqlalchemy/sql/_elements_constructors.py +1850 -0
  193. sqlalchemy/sql/_orm_types.py +20 -0
  194. sqlalchemy/sql/_py_util.py +75 -0
  195. sqlalchemy/sql/_selectable_constructors.py +635 -0
  196. sqlalchemy/sql/_typing.py +460 -0
  197. sqlalchemy/sql/annotation.py +585 -0
  198. sqlalchemy/sql/base.py +2185 -0
  199. sqlalchemy/sql/cache_key.py +1057 -0
  200. sqlalchemy/sql/coercions.py +1405 -0
  201. sqlalchemy/sql/compiler.py +7818 -0
  202. sqlalchemy/sql/crud.py +1669 -0
  203. sqlalchemy/sql/ddl.py +1378 -0
  204. sqlalchemy/sql/default_comparator.py +552 -0
  205. sqlalchemy/sql/dml.py +1817 -0
  206. sqlalchemy/sql/elements.py +5499 -0
  207. sqlalchemy/sql/events.py +455 -0
  208. sqlalchemy/sql/expression.py +162 -0
  209. sqlalchemy/sql/functions.py +2055 -0
  210. sqlalchemy/sql/lambdas.py +1449 -0
  211. sqlalchemy/sql/naming.py +212 -0
  212. sqlalchemy/sql/operators.py +2579 -0
  213. sqlalchemy/sql/roles.py +323 -0
  214. sqlalchemy/sql/schema.py +6158 -0
  215. sqlalchemy/sql/selectable.py +7004 -0
  216. sqlalchemy/sql/sqltypes.py +3827 -0
  217. sqlalchemy/sql/traversals.py +1024 -0
  218. sqlalchemy/sql/type_api.py +2339 -0
  219. sqlalchemy/sql/util.py +1486 -0
  220. sqlalchemy/sql/visitors.py +1165 -0
  221. sqlalchemy/testing/__init__.py +96 -0
  222. sqlalchemy/testing/assertions.py +989 -0
  223. sqlalchemy/testing/assertsql.py +516 -0
  224. sqlalchemy/testing/asyncio.py +135 -0
  225. sqlalchemy/testing/config.py +427 -0
  226. sqlalchemy/testing/engines.py +472 -0
  227. sqlalchemy/testing/entities.py +117 -0
  228. sqlalchemy/testing/exclusions.py +435 -0
  229. sqlalchemy/testing/fixtures/__init__.py +28 -0
  230. sqlalchemy/testing/fixtures/base.py +366 -0
  231. sqlalchemy/testing/fixtures/mypy.py +312 -0
  232. sqlalchemy/testing/fixtures/orm.py +227 -0
  233. sqlalchemy/testing/fixtures/sql.py +503 -0
  234. sqlalchemy/testing/pickleable.py +155 -0
  235. sqlalchemy/testing/plugin/__init__.py +6 -0
  236. sqlalchemy/testing/plugin/bootstrap.py +51 -0
  237. sqlalchemy/testing/plugin/plugin_base.py +779 -0
  238. sqlalchemy/testing/plugin/pytestplugin.py +868 -0
  239. sqlalchemy/testing/profiling.py +324 -0
  240. sqlalchemy/testing/provision.py +496 -0
  241. sqlalchemy/testing/requirements.py +1818 -0
  242. sqlalchemy/testing/schema.py +224 -0
  243. sqlalchemy/testing/suite/__init__.py +19 -0
  244. sqlalchemy/testing/suite/test_cte.py +211 -0
  245. sqlalchemy/testing/suite/test_ddl.py +389 -0
  246. sqlalchemy/testing/suite/test_deprecations.py +153 -0
  247. sqlalchemy/testing/suite/test_dialect.py +740 -0
  248. sqlalchemy/testing/suite/test_insert.py +630 -0
  249. sqlalchemy/testing/suite/test_reflection.py +3225 -0
  250. sqlalchemy/testing/suite/test_results.py +502 -0
  251. sqlalchemy/testing/suite/test_rowcount.py +258 -0
  252. sqlalchemy/testing/suite/test_select.py +1999 -0
  253. sqlalchemy/testing/suite/test_sequence.py +317 -0
  254. sqlalchemy/testing/suite/test_types.py +2141 -0
  255. sqlalchemy/testing/suite/test_unicode_ddl.py +189 -0
  256. sqlalchemy/testing/suite/test_update_delete.py +139 -0
  257. sqlalchemy/testing/util.py +537 -0
  258. sqlalchemy/testing/warnings.py +52 -0
  259. sqlalchemy/types.py +76 -0
  260. sqlalchemy/util/__init__.py +160 -0
  261. sqlalchemy/util/_collections.py +715 -0
  262. sqlalchemy/util/_concurrency_py3k.py +288 -0
  263. sqlalchemy/util/_has_cy.py +40 -0
  264. sqlalchemy/util/_py_collections.py +541 -0
  265. sqlalchemy/util/compat.py +301 -0
  266. sqlalchemy/util/concurrency.py +108 -0
  267. sqlalchemy/util/deprecations.py +401 -0
  268. sqlalchemy/util/langhelpers.py +2218 -0
  269. sqlalchemy/util/preloaded.py +150 -0
  270. sqlalchemy/util/queue.py +322 -0
  271. sqlalchemy/util/tool_support.py +201 -0
  272. sqlalchemy/util/topological.py +120 -0
  273. sqlalchemy/util/typing.py +629 -0
@@ -0,0 +1,3225 @@
1
+ # testing/suite/test_reflection.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
+
9
+ import contextlib
10
+ import operator
11
+ import re
12
+
13
+ import sqlalchemy as sa
14
+ from .. import config
15
+ from .. import engines
16
+ from .. import eq_
17
+ from .. import expect_raises
18
+ from .. import expect_raises_message
19
+ from .. import expect_warnings
20
+ from .. import fixtures
21
+ from .. import is_
22
+ from ..provision import get_temp_table_name
23
+ from ..provision import temp_table_keyword_args
24
+ from ..schema import Column
25
+ from ..schema import Table
26
+ from ... import event
27
+ from ... import ForeignKey
28
+ from ... import func
29
+ from ... import Identity
30
+ from ... import inspect
31
+ from ... import Integer
32
+ from ... import MetaData
33
+ from ... import String
34
+ from ... import testing
35
+ from ... import types as sql_types
36
+ from ...engine import Inspector
37
+ from ...engine import ObjectKind
38
+ from ...engine import ObjectScope
39
+ from ...exc import NoSuchTableError
40
+ from ...exc import UnreflectableTableError
41
+ from ...schema import DDL
42
+ from ...schema import Index
43
+ from ...sql.elements import quoted_name
44
+ from ...sql.schema import BLANK_SCHEMA
45
+ from ...testing import ComparesIndexes
46
+ from ...testing import ComparesTables
47
+ from ...testing import is_false
48
+ from ...testing import is_true
49
+ from ...testing import mock
50
+
51
+
52
+ metadata, users = None, None
53
+
54
+
55
+ class OneConnectionTablesTest(fixtures.TablesTest):
56
+ @classmethod
57
+ def setup_bind(cls):
58
+ # TODO: when temp tables are subject to server reset,
59
+ # this will also have to disable that server reset from
60
+ # happening
61
+ if config.requirements.independent_connections.enabled:
62
+ from sqlalchemy import pool
63
+
64
+ return engines.testing_engine(
65
+ options=dict(poolclass=pool.StaticPool, scope="class"),
66
+ )
67
+ else:
68
+ return config.db
69
+
70
+
71
+ class HasTableTest(OneConnectionTablesTest):
72
+ __backend__ = True
73
+
74
+ @classmethod
75
+ def define_tables(cls, metadata):
76
+ Table(
77
+ "test_table",
78
+ metadata,
79
+ Column("id", Integer, primary_key=True),
80
+ Column("data", String(50)),
81
+ )
82
+ if testing.requires.schemas.enabled:
83
+ Table(
84
+ "test_table_s",
85
+ metadata,
86
+ Column("id", Integer, primary_key=True),
87
+ Column("data", String(50)),
88
+ schema=config.test_schema,
89
+ )
90
+
91
+ if testing.requires.view_reflection:
92
+ cls.define_views(metadata)
93
+ if testing.requires.has_temp_table.enabled:
94
+ cls.define_temp_tables(metadata)
95
+
96
+ @classmethod
97
+ def define_views(cls, metadata):
98
+ query = "CREATE VIEW vv AS SELECT id, data FROM test_table"
99
+
100
+ event.listen(metadata, "after_create", DDL(query))
101
+ event.listen(metadata, "before_drop", DDL("DROP VIEW vv"))
102
+
103
+ if testing.requires.schemas.enabled:
104
+ query = (
105
+ "CREATE VIEW %s.vv AS SELECT id, data FROM %s.test_table_s"
106
+ % (
107
+ config.test_schema,
108
+ config.test_schema,
109
+ )
110
+ )
111
+ event.listen(metadata, "after_create", DDL(query))
112
+ event.listen(
113
+ metadata,
114
+ "before_drop",
115
+ DDL("DROP VIEW %s.vv" % (config.test_schema)),
116
+ )
117
+
118
+ @classmethod
119
+ def temp_table_name(cls):
120
+ return get_temp_table_name(
121
+ config, config.db, f"user_tmp_{config.ident}"
122
+ )
123
+
124
+ @classmethod
125
+ def define_temp_tables(cls, metadata):
126
+ kw = temp_table_keyword_args(config, config.db)
127
+ table_name = cls.temp_table_name()
128
+ user_tmp = Table(
129
+ table_name,
130
+ metadata,
131
+ Column("id", sa.INT, primary_key=True),
132
+ Column("name", sa.VARCHAR(50)),
133
+ **kw,
134
+ )
135
+ if (
136
+ testing.requires.view_reflection.enabled
137
+ and testing.requires.temporary_views.enabled
138
+ ):
139
+ event.listen(
140
+ user_tmp,
141
+ "after_create",
142
+ DDL(
143
+ "create temporary view user_tmp_v as "
144
+ "select * from user_tmp_%s" % config.ident
145
+ ),
146
+ )
147
+ event.listen(user_tmp, "before_drop", DDL("drop view user_tmp_v"))
148
+
149
+ def test_has_table(self):
150
+ with config.db.begin() as conn:
151
+ is_true(config.db.dialect.has_table(conn, "test_table"))
152
+ is_false(config.db.dialect.has_table(conn, "test_table_s"))
153
+ is_false(config.db.dialect.has_table(conn, "nonexistent_table"))
154
+
155
+ def test_has_table_cache(self, metadata):
156
+ insp = inspect(config.db)
157
+ is_true(insp.has_table("test_table"))
158
+ nt = Table("new_table", metadata, Column("col", Integer))
159
+ is_false(insp.has_table("new_table"))
160
+ nt.create(config.db)
161
+ try:
162
+ is_false(insp.has_table("new_table"))
163
+ insp.clear_cache()
164
+ is_true(insp.has_table("new_table"))
165
+ finally:
166
+ nt.drop(config.db)
167
+
168
+ @testing.requires.schemas
169
+ def test_has_table_schema(self):
170
+ with config.db.begin() as conn:
171
+ is_false(
172
+ config.db.dialect.has_table(
173
+ conn, "test_table", schema=config.test_schema
174
+ )
175
+ )
176
+ is_true(
177
+ config.db.dialect.has_table(
178
+ conn, "test_table_s", schema=config.test_schema
179
+ )
180
+ )
181
+ is_false(
182
+ config.db.dialect.has_table(
183
+ conn, "nonexistent_table", schema=config.test_schema
184
+ )
185
+ )
186
+
187
+ @testing.requires.schemas
188
+ def test_has_table_nonexistent_schema(self):
189
+ with config.db.begin() as conn:
190
+ is_false(
191
+ config.db.dialect.has_table(
192
+ conn, "test_table", schema="nonexistent_schema"
193
+ )
194
+ )
195
+
196
+ @testing.requires.views
197
+ def test_has_table_view(self, connection):
198
+ insp = inspect(connection)
199
+ is_true(insp.has_table("vv"))
200
+
201
+ @testing.requires.has_temp_table
202
+ def test_has_table_temp_table(self, connection):
203
+ insp = inspect(connection)
204
+ temp_table_name = self.temp_table_name()
205
+ is_true(insp.has_table(temp_table_name))
206
+
207
+ @testing.requires.has_temp_table
208
+ @testing.requires.view_reflection
209
+ @testing.requires.temporary_views
210
+ def test_has_table_temp_view(self, connection):
211
+ insp = inspect(connection)
212
+ is_true(insp.has_table("user_tmp_v"))
213
+
214
+ @testing.requires.views
215
+ @testing.requires.schemas
216
+ def test_has_table_view_schema(self, connection):
217
+ insp = inspect(connection)
218
+ is_true(insp.has_table("vv", config.test_schema))
219
+
220
+
221
+ class HasIndexTest(fixtures.TablesTest):
222
+ __backend__ = True
223
+
224
+ @classmethod
225
+ def define_tables(cls, metadata):
226
+ tt = Table(
227
+ "test_table",
228
+ metadata,
229
+ Column("id", Integer, primary_key=True),
230
+ Column("data", String(50)),
231
+ Column("data2", String(50)),
232
+ )
233
+ Index("my_idx", tt.c.data)
234
+
235
+ if testing.requires.schemas.enabled:
236
+ tt = Table(
237
+ "test_table",
238
+ metadata,
239
+ Column("id", Integer, primary_key=True),
240
+ Column("data", String(50)),
241
+ schema=config.test_schema,
242
+ )
243
+ Index("my_idx_s", tt.c.data)
244
+
245
+ kind = testing.combinations("dialect", "inspector", argnames="kind")
246
+
247
+ def _has_index(self, kind, conn):
248
+ if kind == "dialect":
249
+ return lambda *a, **k: config.db.dialect.has_index(conn, *a, **k)
250
+ else:
251
+ return inspect(conn).has_index
252
+
253
+ @kind
254
+ def test_has_index(self, kind, connection, metadata):
255
+ meth = self._has_index(kind, connection)
256
+ assert meth("test_table", "my_idx")
257
+ assert not meth("test_table", "my_idx_s")
258
+ assert not meth("nonexistent_table", "my_idx")
259
+ assert not meth("test_table", "nonexistent_idx")
260
+
261
+ assert not meth("test_table", "my_idx_2")
262
+ assert not meth("test_table_2", "my_idx_3")
263
+ idx = Index("my_idx_2", self.tables.test_table.c.data2)
264
+ tbl = Table(
265
+ "test_table_2",
266
+ metadata,
267
+ Column("foo", Integer),
268
+ Index("my_idx_3", "foo"),
269
+ )
270
+ idx.create(connection)
271
+ tbl.create(connection)
272
+ try:
273
+ if kind == "inspector":
274
+ assert not meth("test_table", "my_idx_2")
275
+ assert not meth("test_table_2", "my_idx_3")
276
+ meth.__self__.clear_cache()
277
+ assert meth("test_table", "my_idx_2") is True
278
+ assert meth("test_table_2", "my_idx_3") is True
279
+ finally:
280
+ tbl.drop(connection)
281
+ idx.drop(connection)
282
+
283
+ @testing.requires.schemas
284
+ @kind
285
+ def test_has_index_schema(self, kind, connection):
286
+ meth = self._has_index(kind, connection)
287
+ assert meth("test_table", "my_idx_s", schema=config.test_schema)
288
+ assert not meth("test_table", "my_idx", schema=config.test_schema)
289
+ assert not meth(
290
+ "nonexistent_table", "my_idx_s", schema=config.test_schema
291
+ )
292
+ assert not meth(
293
+ "test_table", "nonexistent_idx_s", schema=config.test_schema
294
+ )
295
+
296
+
297
+ class BizarroCharacterFKResolutionTest(fixtures.TestBase):
298
+ """tests for #10275"""
299
+
300
+ __backend__ = True
301
+
302
+ @testing.combinations(
303
+ ("id",), ("(3)",), ("col%p",), ("[brack]",), argnames="columnname"
304
+ )
305
+ @testing.variation("use_composite", [True, False])
306
+ @testing.combinations(
307
+ ("plain",),
308
+ ("(2)",),
309
+ ("per % cent",),
310
+ ("[brackets]",),
311
+ argnames="tablename",
312
+ )
313
+ def test_fk_ref(
314
+ self, connection, metadata, use_composite, tablename, columnname
315
+ ):
316
+ tt = Table(
317
+ tablename,
318
+ metadata,
319
+ Column(columnname, Integer, key="id", primary_key=True),
320
+ test_needs_fk=True,
321
+ )
322
+ if use_composite:
323
+ tt.append_column(Column("id2", Integer, primary_key=True))
324
+
325
+ if use_composite:
326
+ Table(
327
+ "other",
328
+ metadata,
329
+ Column("id", Integer, primary_key=True),
330
+ Column("ref", Integer),
331
+ Column("ref2", Integer),
332
+ sa.ForeignKeyConstraint(["ref", "ref2"], [tt.c.id, tt.c.id2]),
333
+ test_needs_fk=True,
334
+ )
335
+ else:
336
+ Table(
337
+ "other",
338
+ metadata,
339
+ Column("id", Integer, primary_key=True),
340
+ Column("ref", ForeignKey(tt.c.id)),
341
+ test_needs_fk=True,
342
+ )
343
+
344
+ metadata.create_all(connection)
345
+
346
+ m2 = MetaData()
347
+
348
+ o2 = Table("other", m2, autoload_with=connection)
349
+ t1 = m2.tables[tablename]
350
+
351
+ assert o2.c.ref.references(t1.c[0])
352
+ if use_composite:
353
+ assert o2.c.ref2.references(t1.c[1])
354
+
355
+
356
+ class QuotedNameArgumentTest(fixtures.TablesTest):
357
+ run_create_tables = "once"
358
+ __backend__ = True
359
+
360
+ @classmethod
361
+ def define_tables(cls, metadata):
362
+ Table(
363
+ "quote ' one",
364
+ metadata,
365
+ Column("id", Integer),
366
+ Column("name", String(50)),
367
+ Column("data", String(50)),
368
+ Column("related_id", Integer),
369
+ sa.PrimaryKeyConstraint("id", name="pk quote ' one"),
370
+ sa.Index("ix quote ' one", "name"),
371
+ sa.UniqueConstraint(
372
+ "data",
373
+ name="uq quote' one",
374
+ ),
375
+ sa.ForeignKeyConstraint(
376
+ ["id"], ["related.id"], name="fk quote ' one"
377
+ ),
378
+ sa.CheckConstraint("name != 'foo'", name="ck quote ' one"),
379
+ comment=r"""quote ' one comment""",
380
+ test_needs_fk=True,
381
+ )
382
+
383
+ if testing.requires.symbol_names_w_double_quote.enabled:
384
+ Table(
385
+ 'quote " two',
386
+ metadata,
387
+ Column("id", Integer),
388
+ Column("name", String(50)),
389
+ Column("data", String(50)),
390
+ Column("related_id", Integer),
391
+ sa.PrimaryKeyConstraint("id", name='pk quote " two'),
392
+ sa.Index('ix quote " two', "name"),
393
+ sa.UniqueConstraint(
394
+ "data",
395
+ name='uq quote" two',
396
+ ),
397
+ sa.ForeignKeyConstraint(
398
+ ["id"], ["related.id"], name='fk quote " two'
399
+ ),
400
+ sa.CheckConstraint("name != 'foo'", name='ck quote " two '),
401
+ comment=r"""quote " two comment""",
402
+ test_needs_fk=True,
403
+ )
404
+
405
+ Table(
406
+ "related",
407
+ metadata,
408
+ Column("id", Integer, primary_key=True),
409
+ Column("related", Integer),
410
+ test_needs_fk=True,
411
+ )
412
+
413
+ if testing.requires.view_column_reflection.enabled:
414
+ if testing.requires.symbol_names_w_double_quote.enabled:
415
+ names = [
416
+ "quote ' one",
417
+ 'quote " two',
418
+ ]
419
+ else:
420
+ names = [
421
+ "quote ' one",
422
+ ]
423
+ for name in names:
424
+ query = "CREATE VIEW %s AS SELECT * FROM %s" % (
425
+ config.db.dialect.identifier_preparer.quote(
426
+ "view %s" % name
427
+ ),
428
+ config.db.dialect.identifier_preparer.quote(name),
429
+ )
430
+
431
+ event.listen(metadata, "after_create", DDL(query))
432
+ event.listen(
433
+ metadata,
434
+ "before_drop",
435
+ DDL(
436
+ "DROP VIEW %s"
437
+ % config.db.dialect.identifier_preparer.quote(
438
+ "view %s" % name
439
+ )
440
+ ),
441
+ )
442
+
443
+ def quote_fixtures(fn):
444
+ return testing.combinations(
445
+ ("quote ' one",),
446
+ ('quote " two', testing.requires.symbol_names_w_double_quote),
447
+ )(fn)
448
+
449
+ @quote_fixtures
450
+ def test_get_table_options(self, name):
451
+ insp = inspect(config.db)
452
+
453
+ if testing.requires.reflect_table_options.enabled:
454
+ res = insp.get_table_options(name)
455
+ is_true(isinstance(res, dict))
456
+ else:
457
+ with expect_raises(NotImplementedError):
458
+ res = insp.get_table_options(name)
459
+
460
+ @quote_fixtures
461
+ @testing.requires.view_column_reflection
462
+ def test_get_view_definition(self, name):
463
+ insp = inspect(config.db)
464
+ assert insp.get_view_definition("view %s" % name)
465
+
466
+ @quote_fixtures
467
+ def test_get_columns(self, name):
468
+ insp = inspect(config.db)
469
+ assert insp.get_columns(name)
470
+
471
+ @quote_fixtures
472
+ def test_get_pk_constraint(self, name):
473
+ insp = inspect(config.db)
474
+ assert insp.get_pk_constraint(name)
475
+
476
+ @quote_fixtures
477
+ def test_get_foreign_keys(self, name):
478
+ insp = inspect(config.db)
479
+ assert insp.get_foreign_keys(name)
480
+
481
+ @quote_fixtures
482
+ def test_get_indexes(self, name):
483
+ insp = inspect(config.db)
484
+ assert insp.get_indexes(name)
485
+
486
+ @quote_fixtures
487
+ @testing.requires.unique_constraint_reflection
488
+ def test_get_unique_constraints(self, name):
489
+ insp = inspect(config.db)
490
+ assert insp.get_unique_constraints(name)
491
+
492
+ @quote_fixtures
493
+ @testing.requires.comment_reflection
494
+ def test_get_table_comment(self, name):
495
+ insp = inspect(config.db)
496
+ assert insp.get_table_comment(name)
497
+
498
+ @quote_fixtures
499
+ @testing.requires.check_constraint_reflection
500
+ def test_get_check_constraints(self, name):
501
+ insp = inspect(config.db)
502
+ assert insp.get_check_constraints(name)
503
+
504
+
505
+ def _multi_combination(fn):
506
+ schema = testing.combinations(
507
+ None,
508
+ (
509
+ lambda: config.test_schema,
510
+ testing.requires.schemas,
511
+ ),
512
+ argnames="schema",
513
+ )
514
+ scope = testing.combinations(
515
+ ObjectScope.DEFAULT,
516
+ ObjectScope.TEMPORARY,
517
+ ObjectScope.ANY,
518
+ argnames="scope",
519
+ )
520
+ kind = testing.combinations(
521
+ ObjectKind.TABLE,
522
+ ObjectKind.VIEW,
523
+ ObjectKind.MATERIALIZED_VIEW,
524
+ ObjectKind.ANY,
525
+ ObjectKind.ANY_VIEW,
526
+ ObjectKind.TABLE | ObjectKind.VIEW,
527
+ ObjectKind.TABLE | ObjectKind.MATERIALIZED_VIEW,
528
+ argnames="kind",
529
+ )
530
+ filter_names = testing.combinations(True, False, argnames="use_filter")
531
+
532
+ return schema(scope(kind(filter_names(fn))))
533
+
534
+
535
+ class ComponentReflectionTest(ComparesTables, OneConnectionTablesTest):
536
+ run_inserts = run_deletes = None
537
+
538
+ __backend__ = True
539
+
540
+ @classmethod
541
+ def define_tables(cls, metadata):
542
+ cls.define_reflected_tables(metadata, None)
543
+ if testing.requires.schemas.enabled:
544
+ cls.define_reflected_tables(metadata, testing.config.test_schema)
545
+
546
+ @classmethod
547
+ def define_reflected_tables(cls, metadata, schema):
548
+ if schema:
549
+ schema_prefix = schema + "."
550
+ else:
551
+ schema_prefix = ""
552
+
553
+ if testing.requires.self_referential_foreign_keys.enabled:
554
+ parent_id_args = (
555
+ ForeignKey(
556
+ "%susers.user_id" % schema_prefix, name="user_id_fk"
557
+ ),
558
+ )
559
+ else:
560
+ parent_id_args = ()
561
+ users = Table(
562
+ "users",
563
+ metadata,
564
+ Column("user_id", sa.INT, primary_key=True),
565
+ Column("test1", sa.CHAR(5), nullable=False),
566
+ Column("test2", sa.Float(), nullable=False),
567
+ Column("parent_user_id", sa.Integer, *parent_id_args),
568
+ sa.CheckConstraint(
569
+ "test2 > 0",
570
+ name="zz_test2_gt_zero",
571
+ comment="users check constraint",
572
+ ),
573
+ sa.CheckConstraint("test2 <= 1000"),
574
+ schema=schema,
575
+ test_needs_fk=True,
576
+ )
577
+
578
+ Table(
579
+ "dingalings",
580
+ metadata,
581
+ Column("dingaling_id", sa.Integer, primary_key=True),
582
+ Column(
583
+ "address_id",
584
+ sa.Integer,
585
+ ForeignKey(
586
+ "%semail_addresses.address_id" % schema_prefix,
587
+ name="zz_email_add_id_fg",
588
+ comment="di fk comment",
589
+ ),
590
+ ),
591
+ Column(
592
+ "id_user",
593
+ sa.Integer,
594
+ ForeignKey("%susers.user_id" % schema_prefix),
595
+ ),
596
+ Column("data", sa.String(30), unique=True),
597
+ sa.CheckConstraint(
598
+ "address_id > 0 AND address_id < 1000",
599
+ name="address_id_gt_zero",
600
+ ),
601
+ sa.UniqueConstraint(
602
+ "address_id",
603
+ "dingaling_id",
604
+ name="zz_dingalings_multiple",
605
+ comment="di unique comment",
606
+ ),
607
+ schema=schema,
608
+ test_needs_fk=True,
609
+ )
610
+ Table(
611
+ "email_addresses",
612
+ metadata,
613
+ Column("address_id", sa.Integer),
614
+ Column("remote_user_id", sa.Integer, ForeignKey(users.c.user_id)),
615
+ Column("email_address", sa.String(20), index=True),
616
+ sa.PrimaryKeyConstraint(
617
+ "address_id", name="email_ad_pk", comment="ea pk comment"
618
+ ),
619
+ schema=schema,
620
+ test_needs_fk=True,
621
+ )
622
+ Table(
623
+ "comment_test",
624
+ metadata,
625
+ Column("id", sa.Integer, primary_key=True, comment="id comment"),
626
+ Column("data", sa.String(20), comment="data % comment"),
627
+ Column(
628
+ "d2",
629
+ sa.String(20),
630
+ comment=r"""Comment types type speedily ' " \ '' Fun!""",
631
+ ),
632
+ Column("d3", sa.String(42), comment="Comment\nwith\rescapes"),
633
+ schema=schema,
634
+ comment=r"""the test % ' " \ table comment""",
635
+ )
636
+ Table(
637
+ "no_constraints",
638
+ metadata,
639
+ Column("data", sa.String(20)),
640
+ schema=schema,
641
+ comment="no\nconstraints\rhas\fescaped\vcomment",
642
+ )
643
+
644
+ if testing.requires.cross_schema_fk_reflection.enabled:
645
+ if schema is None:
646
+ Table(
647
+ "local_table",
648
+ metadata,
649
+ Column("id", sa.Integer, primary_key=True),
650
+ Column("data", sa.String(20)),
651
+ Column(
652
+ "remote_id",
653
+ ForeignKey(
654
+ "%s.remote_table_2.id" % testing.config.test_schema
655
+ ),
656
+ ),
657
+ test_needs_fk=True,
658
+ schema=config.db.dialect.default_schema_name,
659
+ )
660
+ else:
661
+ Table(
662
+ "remote_table",
663
+ metadata,
664
+ Column("id", sa.Integer, primary_key=True),
665
+ Column(
666
+ "local_id",
667
+ ForeignKey(
668
+ "%s.local_table.id"
669
+ % config.db.dialect.default_schema_name
670
+ ),
671
+ ),
672
+ Column("data", sa.String(20)),
673
+ schema=schema,
674
+ test_needs_fk=True,
675
+ )
676
+ Table(
677
+ "remote_table_2",
678
+ metadata,
679
+ Column("id", sa.Integer, primary_key=True),
680
+ Column("data", sa.String(20)),
681
+ schema=schema,
682
+ test_needs_fk=True,
683
+ )
684
+
685
+ if testing.requires.index_reflection.enabled:
686
+ Index("users_t_idx", users.c.test1, users.c.test2, unique=True)
687
+ Index(
688
+ "users_all_idx", users.c.user_id, users.c.test2, users.c.test1
689
+ )
690
+
691
+ if not schema:
692
+ # test_needs_fk is at the moment to force MySQL InnoDB
693
+ noncol_idx_test_nopk = Table(
694
+ "noncol_idx_test_nopk",
695
+ metadata,
696
+ Column("q", sa.String(5)),
697
+ test_needs_fk=True,
698
+ )
699
+
700
+ noncol_idx_test_pk = Table(
701
+ "noncol_idx_test_pk",
702
+ metadata,
703
+ Column("id", sa.Integer, primary_key=True),
704
+ Column("q", sa.String(5)),
705
+ test_needs_fk=True,
706
+ )
707
+
708
+ if (
709
+ testing.requires.indexes_with_ascdesc.enabled
710
+ and testing.requires.reflect_indexes_with_ascdesc.enabled
711
+ ):
712
+ Index("noncol_idx_nopk", noncol_idx_test_nopk.c.q.desc())
713
+ Index("noncol_idx_pk", noncol_idx_test_pk.c.q.desc())
714
+
715
+ if testing.requires.view_column_reflection.enabled:
716
+ cls.define_views(metadata, schema)
717
+ if not schema and testing.requires.temp_table_reflection.enabled:
718
+ cls.define_temp_tables(metadata)
719
+
720
+ @classmethod
721
+ def temp_table_name(cls):
722
+ return get_temp_table_name(
723
+ config, config.db, f"user_tmp_{config.ident}"
724
+ )
725
+
726
+ @classmethod
727
+ def define_temp_tables(cls, metadata):
728
+ kw = temp_table_keyword_args(config, config.db)
729
+ table_name = cls.temp_table_name()
730
+ user_tmp = Table(
731
+ table_name,
732
+ metadata,
733
+ Column("id", sa.INT, primary_key=True),
734
+ Column("name", sa.VARCHAR(50)),
735
+ Column("foo", sa.INT),
736
+ # disambiguate temp table unique constraint names. this is
737
+ # pretty arbitrary for a generic dialect however we are doing
738
+ # it to suit SQL Server which will produce name conflicts for
739
+ # unique constraints created against temp tables in different
740
+ # databases.
741
+ # https://www.arbinada.com/en/node/1645
742
+ sa.UniqueConstraint("name", name=f"user_tmp_uq_{config.ident}"),
743
+ sa.Index("user_tmp_ix", "foo"),
744
+ **kw,
745
+ )
746
+ if (
747
+ testing.requires.view_reflection.enabled
748
+ and testing.requires.temporary_views.enabled
749
+ ):
750
+ event.listen(
751
+ user_tmp,
752
+ "after_create",
753
+ DDL(
754
+ "create temporary view user_tmp_v as "
755
+ "select * from user_tmp_%s" % config.ident
756
+ ),
757
+ )
758
+ event.listen(user_tmp, "before_drop", DDL("drop view user_tmp_v"))
759
+
760
+ @classmethod
761
+ def define_views(cls, metadata, schema):
762
+ if testing.requires.materialized_views.enabled:
763
+ materialized = {"dingalings"}
764
+ else:
765
+ materialized = set()
766
+ for table_name in ("users", "email_addresses", "dingalings"):
767
+ fullname = table_name
768
+ if schema:
769
+ fullname = f"{schema}.{table_name}"
770
+ view_name = fullname + "_v"
771
+ prefix = "MATERIALIZED " if table_name in materialized else ""
772
+ query = (
773
+ f"CREATE {prefix}VIEW {view_name} AS SELECT * FROM {fullname}"
774
+ )
775
+
776
+ event.listen(metadata, "after_create", DDL(query))
777
+ if table_name in materialized:
778
+ index_name = "mat_index"
779
+ if schema and testing.against("oracle"):
780
+ index_name = f"{schema}.{index_name}"
781
+ idx = f"CREATE INDEX {index_name} ON {view_name}(data)"
782
+ event.listen(metadata, "after_create", DDL(idx))
783
+ event.listen(
784
+ metadata, "before_drop", DDL(f"DROP {prefix}VIEW {view_name}")
785
+ )
786
+
787
+ def _resolve_kind(self, kind, tables, views, materialized):
788
+ res = {}
789
+ if ObjectKind.TABLE in kind:
790
+ res.update(tables)
791
+ if ObjectKind.VIEW in kind:
792
+ res.update(views)
793
+ if ObjectKind.MATERIALIZED_VIEW in kind:
794
+ res.update(materialized)
795
+ return res
796
+
797
+ def _resolve_views(self, views, materialized):
798
+ if not testing.requires.view_column_reflection.enabled:
799
+ materialized.clear()
800
+ views.clear()
801
+ elif not testing.requires.materialized_views.enabled:
802
+ views.update(materialized)
803
+ materialized.clear()
804
+
805
+ def _resolve_names(self, schema, scope, filter_names, values):
806
+ scope_filter = lambda _: True # noqa: E731
807
+ if scope is ObjectScope.DEFAULT:
808
+ scope_filter = lambda k: "tmp" not in k[1] # noqa: E731
809
+ if scope is ObjectScope.TEMPORARY:
810
+ scope_filter = lambda k: "tmp" in k[1] # noqa: E731
811
+
812
+ removed = {
813
+ None: {"remote_table", "remote_table_2"},
814
+ testing.config.test_schema: {
815
+ "local_table",
816
+ "noncol_idx_test_nopk",
817
+ "noncol_idx_test_pk",
818
+ "user_tmp_v",
819
+ self.temp_table_name(),
820
+ },
821
+ }
822
+ if not testing.requires.cross_schema_fk_reflection.enabled:
823
+ removed[None].add("local_table")
824
+ removed[testing.config.test_schema].update(
825
+ ["remote_table", "remote_table_2"]
826
+ )
827
+ if not testing.requires.index_reflection.enabled:
828
+ removed[None].update(
829
+ ["noncol_idx_test_nopk", "noncol_idx_test_pk"]
830
+ )
831
+ if (
832
+ not testing.requires.temp_table_reflection.enabled
833
+ or not testing.requires.temp_table_names.enabled
834
+ ):
835
+ removed[None].update(["user_tmp_v", self.temp_table_name()])
836
+ if not testing.requires.temporary_views.enabled:
837
+ removed[None].update(["user_tmp_v"])
838
+
839
+ res = {
840
+ k: v
841
+ for k, v in values.items()
842
+ if scope_filter(k)
843
+ and k[1] not in removed[schema]
844
+ and (not filter_names or k[1] in filter_names)
845
+ }
846
+ return res
847
+
848
+ def exp_options(
849
+ self,
850
+ schema=None,
851
+ scope=ObjectScope.ANY,
852
+ kind=ObjectKind.ANY,
853
+ filter_names=None,
854
+ ):
855
+ materialized = {(schema, "dingalings_v"): mock.ANY}
856
+ views = {
857
+ (schema, "email_addresses_v"): mock.ANY,
858
+ (schema, "users_v"): mock.ANY,
859
+ (schema, "user_tmp_v"): mock.ANY,
860
+ }
861
+ self._resolve_views(views, materialized)
862
+ tables = {
863
+ (schema, "users"): mock.ANY,
864
+ (schema, "dingalings"): mock.ANY,
865
+ (schema, "email_addresses"): mock.ANY,
866
+ (schema, "comment_test"): mock.ANY,
867
+ (schema, "no_constraints"): mock.ANY,
868
+ (schema, "local_table"): mock.ANY,
869
+ (schema, "remote_table"): mock.ANY,
870
+ (schema, "remote_table_2"): mock.ANY,
871
+ (schema, "noncol_idx_test_nopk"): mock.ANY,
872
+ (schema, "noncol_idx_test_pk"): mock.ANY,
873
+ (schema, self.temp_table_name()): mock.ANY,
874
+ }
875
+ res = self._resolve_kind(kind, tables, views, materialized)
876
+ res = self._resolve_names(schema, scope, filter_names, res)
877
+ return res
878
+
879
+ def exp_comments(
880
+ self,
881
+ schema=None,
882
+ scope=ObjectScope.ANY,
883
+ kind=ObjectKind.ANY,
884
+ filter_names=None,
885
+ ):
886
+ empty = {"text": None}
887
+ materialized = {(schema, "dingalings_v"): empty}
888
+ views = {
889
+ (schema, "email_addresses_v"): empty,
890
+ (schema, "users_v"): empty,
891
+ (schema, "user_tmp_v"): empty,
892
+ }
893
+ self._resolve_views(views, materialized)
894
+ tables = {
895
+ (schema, "users"): empty,
896
+ (schema, "dingalings"): empty,
897
+ (schema, "email_addresses"): empty,
898
+ (schema, "comment_test"): {
899
+ "text": r"""the test % ' " \ table comment"""
900
+ },
901
+ (schema, "no_constraints"): {
902
+ "text": "no\nconstraints\rhas\fescaped\vcomment"
903
+ },
904
+ (schema, "local_table"): empty,
905
+ (schema, "remote_table"): empty,
906
+ (schema, "remote_table_2"): empty,
907
+ (schema, "noncol_idx_test_nopk"): empty,
908
+ (schema, "noncol_idx_test_pk"): empty,
909
+ (schema, self.temp_table_name()): empty,
910
+ }
911
+ res = self._resolve_kind(kind, tables, views, materialized)
912
+ res = self._resolve_names(schema, scope, filter_names, res)
913
+ return res
914
+
915
+ def exp_columns(
916
+ self,
917
+ schema=None,
918
+ scope=ObjectScope.ANY,
919
+ kind=ObjectKind.ANY,
920
+ filter_names=None,
921
+ ):
922
+ def col(
923
+ name, auto=False, default=mock.ANY, comment=None, nullable=True
924
+ ):
925
+ res = {
926
+ "name": name,
927
+ "autoincrement": auto,
928
+ "type": mock.ANY,
929
+ "default": default,
930
+ "comment": comment,
931
+ "nullable": nullable,
932
+ }
933
+ if auto == "omit":
934
+ res.pop("autoincrement")
935
+ return res
936
+
937
+ def pk(name, **kw):
938
+ kw = {"auto": True, "default": mock.ANY, "nullable": False, **kw}
939
+ return col(name, **kw)
940
+
941
+ materialized = {
942
+ (schema, "dingalings_v"): [
943
+ col("dingaling_id", auto="omit", nullable=mock.ANY),
944
+ col("address_id"),
945
+ col("id_user"),
946
+ col("data"),
947
+ ]
948
+ }
949
+ views = {
950
+ (schema, "email_addresses_v"): [
951
+ col("address_id", auto="omit", nullable=mock.ANY),
952
+ col("remote_user_id"),
953
+ col("email_address"),
954
+ ],
955
+ (schema, "users_v"): [
956
+ col("user_id", auto="omit", nullable=mock.ANY),
957
+ col("test1", nullable=mock.ANY),
958
+ col("test2", nullable=mock.ANY),
959
+ col("parent_user_id"),
960
+ ],
961
+ (schema, "user_tmp_v"): [
962
+ col("id", auto="omit", nullable=mock.ANY),
963
+ col("name"),
964
+ col("foo"),
965
+ ],
966
+ }
967
+ self._resolve_views(views, materialized)
968
+ tables = {
969
+ (schema, "users"): [
970
+ pk("user_id"),
971
+ col("test1", nullable=False),
972
+ col("test2", nullable=False),
973
+ col("parent_user_id"),
974
+ ],
975
+ (schema, "dingalings"): [
976
+ pk("dingaling_id"),
977
+ col("address_id"),
978
+ col("id_user"),
979
+ col("data"),
980
+ ],
981
+ (schema, "email_addresses"): [
982
+ pk("address_id"),
983
+ col("remote_user_id"),
984
+ col("email_address"),
985
+ ],
986
+ (schema, "comment_test"): [
987
+ pk("id", comment="id comment"),
988
+ col("data", comment="data % comment"),
989
+ col(
990
+ "d2",
991
+ comment=r"""Comment types type speedily ' " \ '' Fun!""",
992
+ ),
993
+ col("d3", comment="Comment\nwith\rescapes"),
994
+ ],
995
+ (schema, "no_constraints"): [col("data")],
996
+ (schema, "local_table"): [pk("id"), col("data"), col("remote_id")],
997
+ (schema, "remote_table"): [pk("id"), col("local_id"), col("data")],
998
+ (schema, "remote_table_2"): [pk("id"), col("data")],
999
+ (schema, "noncol_idx_test_nopk"): [col("q")],
1000
+ (schema, "noncol_idx_test_pk"): [pk("id"), col("q")],
1001
+ (schema, self.temp_table_name()): [
1002
+ pk("id"),
1003
+ col("name"),
1004
+ col("foo"),
1005
+ ],
1006
+ }
1007
+ res = self._resolve_kind(kind, tables, views, materialized)
1008
+ res = self._resolve_names(schema, scope, filter_names, res)
1009
+ return res
1010
+
1011
+ @property
1012
+ def _required_column_keys(self):
1013
+ return {"name", "type", "nullable", "default"}
1014
+
1015
+ def exp_pks(
1016
+ self,
1017
+ schema=None,
1018
+ scope=ObjectScope.ANY,
1019
+ kind=ObjectKind.ANY,
1020
+ filter_names=None,
1021
+ ):
1022
+ def pk(*cols, name=mock.ANY, comment=None):
1023
+ return {
1024
+ "constrained_columns": list(cols),
1025
+ "name": name,
1026
+ "comment": comment,
1027
+ }
1028
+
1029
+ empty = pk(name=None)
1030
+ if testing.requires.materialized_views_reflect_pk.enabled:
1031
+ materialized = {(schema, "dingalings_v"): pk("dingaling_id")}
1032
+ else:
1033
+ materialized = {(schema, "dingalings_v"): empty}
1034
+ views = {
1035
+ (schema, "email_addresses_v"): empty,
1036
+ (schema, "users_v"): empty,
1037
+ (schema, "user_tmp_v"): empty,
1038
+ }
1039
+ self._resolve_views(views, materialized)
1040
+ tables = {
1041
+ (schema, "users"): pk("user_id"),
1042
+ (schema, "dingalings"): pk("dingaling_id"),
1043
+ (schema, "email_addresses"): pk(
1044
+ "address_id", name="email_ad_pk", comment="ea pk comment"
1045
+ ),
1046
+ (schema, "comment_test"): pk("id"),
1047
+ (schema, "no_constraints"): empty,
1048
+ (schema, "local_table"): pk("id"),
1049
+ (schema, "remote_table"): pk("id"),
1050
+ (schema, "remote_table_2"): pk("id"),
1051
+ (schema, "noncol_idx_test_nopk"): empty,
1052
+ (schema, "noncol_idx_test_pk"): pk("id"),
1053
+ (schema, self.temp_table_name()): pk("id"),
1054
+ }
1055
+ if not testing.requires.reflects_pk_names.enabled:
1056
+ for val in tables.values():
1057
+ if val["name"] is not None:
1058
+ val["name"] = mock.ANY
1059
+ res = self._resolve_kind(kind, tables, views, materialized)
1060
+ res = self._resolve_names(schema, scope, filter_names, res)
1061
+ return res
1062
+
1063
+ @property
1064
+ def _required_pk_keys(self):
1065
+ return {"name", "constrained_columns"}
1066
+
1067
+ def exp_fks(
1068
+ self,
1069
+ schema=None,
1070
+ scope=ObjectScope.ANY,
1071
+ kind=ObjectKind.ANY,
1072
+ filter_names=None,
1073
+ ):
1074
+ class tt:
1075
+ def __eq__(self, other):
1076
+ return (
1077
+ other is None
1078
+ or config.db.dialect.default_schema_name == other
1079
+ )
1080
+
1081
+ def fk(
1082
+ cols,
1083
+ ref_col,
1084
+ ref_table,
1085
+ ref_schema=schema,
1086
+ name=mock.ANY,
1087
+ comment=None,
1088
+ ):
1089
+ return {
1090
+ "constrained_columns": cols,
1091
+ "referred_columns": ref_col,
1092
+ "name": name,
1093
+ "options": mock.ANY,
1094
+ "referred_schema": (
1095
+ ref_schema if ref_schema is not None else tt()
1096
+ ),
1097
+ "referred_table": ref_table,
1098
+ "comment": comment,
1099
+ }
1100
+
1101
+ materialized = {(schema, "dingalings_v"): []}
1102
+ views = {
1103
+ (schema, "email_addresses_v"): [],
1104
+ (schema, "users_v"): [],
1105
+ (schema, "user_tmp_v"): [],
1106
+ }
1107
+ self._resolve_views(views, materialized)
1108
+ tables = {
1109
+ (schema, "users"): [
1110
+ fk(["parent_user_id"], ["user_id"], "users", name="user_id_fk")
1111
+ ],
1112
+ (schema, "dingalings"): [
1113
+ fk(["id_user"], ["user_id"], "users"),
1114
+ fk(
1115
+ ["address_id"],
1116
+ ["address_id"],
1117
+ "email_addresses",
1118
+ name="zz_email_add_id_fg",
1119
+ comment="di fk comment",
1120
+ ),
1121
+ ],
1122
+ (schema, "email_addresses"): [
1123
+ fk(["remote_user_id"], ["user_id"], "users")
1124
+ ],
1125
+ (schema, "comment_test"): [],
1126
+ (schema, "no_constraints"): [],
1127
+ (schema, "local_table"): [
1128
+ fk(
1129
+ ["remote_id"],
1130
+ ["id"],
1131
+ "remote_table_2",
1132
+ ref_schema=config.test_schema,
1133
+ )
1134
+ ],
1135
+ (schema, "remote_table"): [
1136
+ fk(["local_id"], ["id"], "local_table", ref_schema=None)
1137
+ ],
1138
+ (schema, "remote_table_2"): [],
1139
+ (schema, "noncol_idx_test_nopk"): [],
1140
+ (schema, "noncol_idx_test_pk"): [],
1141
+ (schema, self.temp_table_name()): [],
1142
+ }
1143
+ if not testing.requires.self_referential_foreign_keys.enabled:
1144
+ tables[(schema, "users")].clear()
1145
+ if not testing.requires.named_constraints.enabled:
1146
+ for vals in tables.values():
1147
+ for val in vals:
1148
+ if val["name"] is not mock.ANY:
1149
+ val["name"] = mock.ANY
1150
+
1151
+ res = self._resolve_kind(kind, tables, views, materialized)
1152
+ res = self._resolve_names(schema, scope, filter_names, res)
1153
+ return res
1154
+
1155
+ @property
1156
+ def _required_fk_keys(self):
1157
+ return {
1158
+ "name",
1159
+ "constrained_columns",
1160
+ "referred_schema",
1161
+ "referred_table",
1162
+ "referred_columns",
1163
+ }
1164
+
1165
+ def exp_indexes(
1166
+ self,
1167
+ schema=None,
1168
+ scope=ObjectScope.ANY,
1169
+ kind=ObjectKind.ANY,
1170
+ filter_names=None,
1171
+ ):
1172
+ def idx(
1173
+ *cols,
1174
+ name,
1175
+ unique=False,
1176
+ column_sorting=None,
1177
+ duplicates=False,
1178
+ fk=False,
1179
+ ):
1180
+ fk_req = testing.requires.foreign_keys_reflect_as_index
1181
+ dup_req = testing.requires.unique_constraints_reflect_as_index
1182
+ sorting_expression = (
1183
+ testing.requires.reflect_indexes_with_ascdesc_as_expression
1184
+ )
1185
+
1186
+ if (fk and not fk_req.enabled) or (
1187
+ duplicates and not dup_req.enabled
1188
+ ):
1189
+ return ()
1190
+ res = {
1191
+ "unique": unique,
1192
+ "column_names": list(cols),
1193
+ "name": name,
1194
+ "dialect_options": mock.ANY,
1195
+ "include_columns": [],
1196
+ }
1197
+ if column_sorting:
1198
+ res["column_sorting"] = column_sorting
1199
+ if sorting_expression.enabled:
1200
+ res["expressions"] = orig = res["column_names"]
1201
+ res["column_names"] = [
1202
+ None if c in column_sorting else c for c in orig
1203
+ ]
1204
+
1205
+ if duplicates:
1206
+ res["duplicates_constraint"] = name
1207
+ return [res]
1208
+
1209
+ materialized = {(schema, "dingalings_v"): []}
1210
+ views = {
1211
+ (schema, "email_addresses_v"): [],
1212
+ (schema, "users_v"): [],
1213
+ (schema, "user_tmp_v"): [],
1214
+ }
1215
+ self._resolve_views(views, materialized)
1216
+ if materialized:
1217
+ materialized[(schema, "dingalings_v")].extend(
1218
+ idx("data", name="mat_index")
1219
+ )
1220
+ tables = {
1221
+ (schema, "users"): [
1222
+ *idx("parent_user_id", name="user_id_fk", fk=True),
1223
+ *idx("user_id", "test2", "test1", name="users_all_idx"),
1224
+ *idx("test1", "test2", name="users_t_idx", unique=True),
1225
+ ],
1226
+ (schema, "dingalings"): [
1227
+ *idx("data", name=mock.ANY, unique=True, duplicates=True),
1228
+ *idx("id_user", name=mock.ANY, fk=True),
1229
+ *idx(
1230
+ "address_id",
1231
+ "dingaling_id",
1232
+ name="zz_dingalings_multiple",
1233
+ unique=True,
1234
+ duplicates=True,
1235
+ ),
1236
+ ],
1237
+ (schema, "email_addresses"): [
1238
+ *idx("email_address", name=mock.ANY),
1239
+ *idx("remote_user_id", name=mock.ANY, fk=True),
1240
+ ],
1241
+ (schema, "comment_test"): [],
1242
+ (schema, "no_constraints"): [],
1243
+ (schema, "local_table"): [
1244
+ *idx("remote_id", name=mock.ANY, fk=True)
1245
+ ],
1246
+ (schema, "remote_table"): [
1247
+ *idx("local_id", name=mock.ANY, fk=True)
1248
+ ],
1249
+ (schema, "remote_table_2"): [],
1250
+ (schema, "noncol_idx_test_nopk"): [
1251
+ *idx(
1252
+ "q",
1253
+ name="noncol_idx_nopk",
1254
+ column_sorting={"q": ("desc",)},
1255
+ )
1256
+ ],
1257
+ (schema, "noncol_idx_test_pk"): [
1258
+ *idx(
1259
+ "q", name="noncol_idx_pk", column_sorting={"q": ("desc",)}
1260
+ )
1261
+ ],
1262
+ (schema, self.temp_table_name()): [
1263
+ *idx("foo", name="user_tmp_ix"),
1264
+ *idx(
1265
+ "name",
1266
+ name=f"user_tmp_uq_{config.ident}",
1267
+ duplicates=True,
1268
+ unique=True,
1269
+ ),
1270
+ ],
1271
+ }
1272
+ if (
1273
+ not testing.requires.indexes_with_ascdesc.enabled
1274
+ or not testing.requires.reflect_indexes_with_ascdesc.enabled
1275
+ ):
1276
+ tables[(schema, "noncol_idx_test_nopk")].clear()
1277
+ tables[(schema, "noncol_idx_test_pk")].clear()
1278
+ res = self._resolve_kind(kind, tables, views, materialized)
1279
+ res = self._resolve_names(schema, scope, filter_names, res)
1280
+ return res
1281
+
1282
+ @property
1283
+ def _required_index_keys(self):
1284
+ return {"name", "column_names", "unique"}
1285
+
1286
+ def exp_ucs(
1287
+ self,
1288
+ schema=None,
1289
+ scope=ObjectScope.ANY,
1290
+ kind=ObjectKind.ANY,
1291
+ filter_names=None,
1292
+ all_=False,
1293
+ ):
1294
+ def uc(
1295
+ *cols, name, duplicates_index=None, is_index=False, comment=None
1296
+ ):
1297
+ req = testing.requires.unique_index_reflect_as_unique_constraints
1298
+ if is_index and not req.enabled:
1299
+ return ()
1300
+ res = {
1301
+ "column_names": list(cols),
1302
+ "name": name,
1303
+ "comment": comment,
1304
+ }
1305
+ if duplicates_index:
1306
+ res["duplicates_index"] = duplicates_index
1307
+ return [res]
1308
+
1309
+ materialized = {(schema, "dingalings_v"): []}
1310
+ views = {
1311
+ (schema, "email_addresses_v"): [],
1312
+ (schema, "users_v"): [],
1313
+ (schema, "user_tmp_v"): [],
1314
+ }
1315
+ self._resolve_views(views, materialized)
1316
+ tables = {
1317
+ (schema, "users"): [
1318
+ *uc(
1319
+ "test1",
1320
+ "test2",
1321
+ name="users_t_idx",
1322
+ duplicates_index="users_t_idx",
1323
+ is_index=True,
1324
+ )
1325
+ ],
1326
+ (schema, "dingalings"): [
1327
+ *uc("data", name=mock.ANY, duplicates_index=mock.ANY),
1328
+ *uc(
1329
+ "address_id",
1330
+ "dingaling_id",
1331
+ name="zz_dingalings_multiple",
1332
+ duplicates_index="zz_dingalings_multiple",
1333
+ comment="di unique comment",
1334
+ ),
1335
+ ],
1336
+ (schema, "email_addresses"): [],
1337
+ (schema, "comment_test"): [],
1338
+ (schema, "no_constraints"): [],
1339
+ (schema, "local_table"): [],
1340
+ (schema, "remote_table"): [],
1341
+ (schema, "remote_table_2"): [],
1342
+ (schema, "noncol_idx_test_nopk"): [],
1343
+ (schema, "noncol_idx_test_pk"): [],
1344
+ (schema, self.temp_table_name()): [
1345
+ *uc("name", name=f"user_tmp_uq_{config.ident}")
1346
+ ],
1347
+ }
1348
+ if all_:
1349
+ return {**materialized, **views, **tables}
1350
+ else:
1351
+ res = self._resolve_kind(kind, tables, views, materialized)
1352
+ res = self._resolve_names(schema, scope, filter_names, res)
1353
+ return res
1354
+
1355
+ @property
1356
+ def _required_unique_cst_keys(self):
1357
+ return {"name", "column_names"}
1358
+
1359
+ def exp_ccs(
1360
+ self,
1361
+ schema=None,
1362
+ scope=ObjectScope.ANY,
1363
+ kind=ObjectKind.ANY,
1364
+ filter_names=None,
1365
+ ):
1366
+ class tt(str):
1367
+ def __eq__(self, other):
1368
+ res = (
1369
+ other.lower()
1370
+ .replace("(", "")
1371
+ .replace(")", "")
1372
+ .replace("`", "")
1373
+ )
1374
+ return self in res
1375
+
1376
+ def cc(text, name, comment=None):
1377
+ return {"sqltext": tt(text), "name": name, "comment": comment}
1378
+
1379
+ # print({1: "test2 > (0)::double precision"} == {1: tt("test2 > 0")})
1380
+ # assert 0
1381
+ materialized = {(schema, "dingalings_v"): []}
1382
+ views = {
1383
+ (schema, "email_addresses_v"): [],
1384
+ (schema, "users_v"): [],
1385
+ (schema, "user_tmp_v"): [],
1386
+ }
1387
+ self._resolve_views(views, materialized)
1388
+ tables = {
1389
+ (schema, "users"): [
1390
+ cc("test2 <= 1000", mock.ANY),
1391
+ cc(
1392
+ "test2 > 0",
1393
+ "zz_test2_gt_zero",
1394
+ comment="users check constraint",
1395
+ ),
1396
+ ],
1397
+ (schema, "dingalings"): [
1398
+ cc(
1399
+ "address_id > 0 and address_id < 1000",
1400
+ name="address_id_gt_zero",
1401
+ ),
1402
+ ],
1403
+ (schema, "email_addresses"): [],
1404
+ (schema, "comment_test"): [],
1405
+ (schema, "no_constraints"): [],
1406
+ (schema, "local_table"): [],
1407
+ (schema, "remote_table"): [],
1408
+ (schema, "remote_table_2"): [],
1409
+ (schema, "noncol_idx_test_nopk"): [],
1410
+ (schema, "noncol_idx_test_pk"): [],
1411
+ (schema, self.temp_table_name()): [],
1412
+ }
1413
+ res = self._resolve_kind(kind, tables, views, materialized)
1414
+ res = self._resolve_names(schema, scope, filter_names, res)
1415
+ return res
1416
+
1417
+ @property
1418
+ def _required_cc_keys(self):
1419
+ return {"name", "sqltext"}
1420
+
1421
+ @testing.requires.schema_reflection
1422
+ def test_get_schema_names(self, connection):
1423
+ insp = inspect(connection)
1424
+
1425
+ is_true(testing.config.test_schema in insp.get_schema_names())
1426
+
1427
+ @testing.requires.schema_reflection
1428
+ def test_has_schema(self, connection):
1429
+ insp = inspect(connection)
1430
+
1431
+ is_true(insp.has_schema(testing.config.test_schema))
1432
+ is_false(insp.has_schema("sa_fake_schema_foo"))
1433
+
1434
+ @testing.requires.schema_reflection
1435
+ def test_get_schema_names_w_translate_map(self, connection):
1436
+ """test #7300"""
1437
+
1438
+ connection = connection.execution_options(
1439
+ schema_translate_map={
1440
+ "foo": "bar",
1441
+ BLANK_SCHEMA: testing.config.test_schema,
1442
+ }
1443
+ )
1444
+ insp = inspect(connection)
1445
+
1446
+ is_true(testing.config.test_schema in insp.get_schema_names())
1447
+
1448
+ @testing.requires.schema_reflection
1449
+ def test_has_schema_w_translate_map(self, connection):
1450
+ connection = connection.execution_options(
1451
+ schema_translate_map={
1452
+ "foo": "bar",
1453
+ BLANK_SCHEMA: testing.config.test_schema,
1454
+ }
1455
+ )
1456
+ insp = inspect(connection)
1457
+
1458
+ is_true(insp.has_schema(testing.config.test_schema))
1459
+ is_false(insp.has_schema("sa_fake_schema_foo"))
1460
+
1461
+ @testing.requires.schema_reflection
1462
+ @testing.requires.schema_create_delete
1463
+ def test_schema_cache(self, connection):
1464
+ insp = inspect(connection)
1465
+
1466
+ is_false("foo_bar" in insp.get_schema_names())
1467
+ is_false(insp.has_schema("foo_bar"))
1468
+ connection.execute(DDL("CREATE SCHEMA foo_bar"))
1469
+ try:
1470
+ is_false("foo_bar" in insp.get_schema_names())
1471
+ is_false(insp.has_schema("foo_bar"))
1472
+ insp.clear_cache()
1473
+ is_true("foo_bar" in insp.get_schema_names())
1474
+ is_true(insp.has_schema("foo_bar"))
1475
+ finally:
1476
+ connection.execute(DDL("DROP SCHEMA foo_bar"))
1477
+
1478
+ @testing.requires.schema_reflection
1479
+ def test_dialect_initialize(self):
1480
+ engine = engines.testing_engine()
1481
+ inspect(engine)
1482
+ assert hasattr(engine.dialect, "default_schema_name")
1483
+
1484
+ @testing.requires.schema_reflection
1485
+ def test_get_default_schema_name(self, connection):
1486
+ insp = inspect(connection)
1487
+ eq_(insp.default_schema_name, connection.dialect.default_schema_name)
1488
+
1489
+ @testing.combinations(
1490
+ None,
1491
+ ("foreign_key", testing.requires.foreign_key_constraint_reflection),
1492
+ argnames="order_by",
1493
+ )
1494
+ @testing.combinations(
1495
+ (True, testing.requires.schemas), False, argnames="use_schema"
1496
+ )
1497
+ def test_get_table_names(self, connection, order_by, use_schema):
1498
+ if use_schema:
1499
+ schema = config.test_schema
1500
+ else:
1501
+ schema = None
1502
+
1503
+ _ignore_tables = {
1504
+ "comment_test",
1505
+ "noncol_idx_test_pk",
1506
+ "noncol_idx_test_nopk",
1507
+ "local_table",
1508
+ "remote_table",
1509
+ "remote_table_2",
1510
+ "no_constraints",
1511
+ }
1512
+
1513
+ insp = inspect(connection)
1514
+
1515
+ if order_by:
1516
+ tables = [
1517
+ rec[0]
1518
+ for rec in insp.get_sorted_table_and_fkc_names(schema)
1519
+ if rec[0]
1520
+ ]
1521
+ else:
1522
+ tables = insp.get_table_names(schema)
1523
+ table_names = [t for t in tables if t not in _ignore_tables]
1524
+
1525
+ if order_by == "foreign_key":
1526
+ answer = ["users", "email_addresses", "dingalings"]
1527
+ eq_(table_names, answer)
1528
+ else:
1529
+ answer = ["dingalings", "email_addresses", "users"]
1530
+ eq_(sorted(table_names), answer)
1531
+
1532
+ @testing.combinations(
1533
+ (True, testing.requires.schemas), False, argnames="use_schema"
1534
+ )
1535
+ def test_get_view_names(self, connection, use_schema):
1536
+ insp = inspect(connection)
1537
+ if use_schema:
1538
+ schema = config.test_schema
1539
+ else:
1540
+ schema = None
1541
+ table_names = insp.get_view_names(schema)
1542
+ if testing.requires.materialized_views.enabled:
1543
+ eq_(sorted(table_names), ["email_addresses_v", "users_v"])
1544
+ eq_(insp.get_materialized_view_names(schema), ["dingalings_v"])
1545
+ else:
1546
+ answer = ["dingalings_v", "email_addresses_v", "users_v"]
1547
+ eq_(sorted(table_names), answer)
1548
+
1549
+ @testing.requires.temp_table_names
1550
+ def test_get_temp_table_names(self, connection):
1551
+ insp = inspect(connection)
1552
+ temp_table_names = insp.get_temp_table_names()
1553
+ eq_(sorted(temp_table_names), [f"user_tmp_{config.ident}"])
1554
+
1555
+ @testing.requires.view_reflection
1556
+ @testing.requires.temporary_views
1557
+ def test_get_temp_view_names(self, connection):
1558
+ insp = inspect(connection)
1559
+ temp_table_names = insp.get_temp_view_names()
1560
+ eq_(sorted(temp_table_names), ["user_tmp_v"])
1561
+
1562
+ @testing.requires.comment_reflection
1563
+ def test_get_comments(self, connection):
1564
+ self._test_get_comments(connection)
1565
+
1566
+ @testing.requires.comment_reflection
1567
+ @testing.requires.schemas
1568
+ def test_get_comments_with_schema(self, connection):
1569
+ self._test_get_comments(connection, testing.config.test_schema)
1570
+
1571
+ def _test_get_comments(self, connection, schema=None):
1572
+ insp = inspect(connection)
1573
+ exp = self.exp_comments(schema=schema)
1574
+ eq_(
1575
+ insp.get_table_comment("comment_test", schema=schema),
1576
+ exp[(schema, "comment_test")],
1577
+ )
1578
+
1579
+ eq_(
1580
+ insp.get_table_comment("users", schema=schema),
1581
+ exp[(schema, "users")],
1582
+ )
1583
+
1584
+ eq_(
1585
+ insp.get_table_comment("comment_test", schema=schema),
1586
+ exp[(schema, "comment_test")],
1587
+ )
1588
+
1589
+ no_cst = self.tables.no_constraints.name
1590
+ eq_(
1591
+ insp.get_table_comment(no_cst, schema=schema),
1592
+ exp[(schema, no_cst)],
1593
+ )
1594
+
1595
+ @testing.combinations(
1596
+ (False, False),
1597
+ (False, True, testing.requires.schemas),
1598
+ (True, False, testing.requires.view_reflection),
1599
+ (
1600
+ True,
1601
+ True,
1602
+ testing.requires.schemas + testing.requires.view_reflection,
1603
+ ),
1604
+ argnames="use_views,use_schema",
1605
+ )
1606
+ def test_get_columns(self, connection, use_views, use_schema):
1607
+ if use_schema:
1608
+ schema = config.test_schema
1609
+ else:
1610
+ schema = None
1611
+
1612
+ users, addresses = (self.tables.users, self.tables.email_addresses)
1613
+ if use_views:
1614
+ table_names = ["users_v", "email_addresses_v", "dingalings_v"]
1615
+ else:
1616
+ table_names = ["users", "email_addresses"]
1617
+
1618
+ insp = inspect(connection)
1619
+ for table_name, table in zip(table_names, (users, addresses)):
1620
+ schema_name = schema
1621
+ cols = insp.get_columns(table_name, schema=schema_name)
1622
+ is_true(len(cols) > 0, len(cols))
1623
+
1624
+ # should be in order
1625
+
1626
+ for i, col in enumerate(table.columns):
1627
+ eq_(col.name, cols[i]["name"])
1628
+ ctype = cols[i]["type"].__class__
1629
+ ctype_def = col.type
1630
+ if isinstance(ctype_def, sa.types.TypeEngine):
1631
+ ctype_def = ctype_def.__class__
1632
+
1633
+ # Oracle returns Date for DateTime.
1634
+
1635
+ if testing.against("oracle") and ctype_def in (
1636
+ sql_types.Date,
1637
+ sql_types.DateTime,
1638
+ ):
1639
+ ctype_def = sql_types.Date
1640
+
1641
+ # assert that the desired type and return type share
1642
+ # a base within one of the generic types.
1643
+
1644
+ is_true(
1645
+ len(
1646
+ set(ctype.__mro__)
1647
+ .intersection(ctype_def.__mro__)
1648
+ .intersection(
1649
+ [
1650
+ sql_types.Integer,
1651
+ sql_types.Numeric,
1652
+ sql_types.DateTime,
1653
+ sql_types.Date,
1654
+ sql_types.Time,
1655
+ sql_types.String,
1656
+ sql_types._Binary,
1657
+ ]
1658
+ )
1659
+ )
1660
+ > 0,
1661
+ "%s(%s), %s(%s)"
1662
+ % (col.name, col.type, cols[i]["name"], ctype),
1663
+ )
1664
+
1665
+ if not col.primary_key:
1666
+ assert cols[i]["default"] is None
1667
+
1668
+ # The case of a table with no column
1669
+ # is tested below in TableNoColumnsTest
1670
+
1671
+ @testing.requires.temp_table_reflection
1672
+ def test_reflect_table_temp_table(self, connection):
1673
+ table_name = self.temp_table_name()
1674
+ user_tmp = self.tables[table_name]
1675
+
1676
+ reflected_user_tmp = Table(
1677
+ table_name, MetaData(), autoload_with=connection
1678
+ )
1679
+ self.assert_tables_equal(
1680
+ user_tmp, reflected_user_tmp, strict_constraints=False
1681
+ )
1682
+
1683
+ @testing.requires.temp_table_reflection
1684
+ def test_get_temp_table_columns(self, connection):
1685
+ table_name = self.temp_table_name()
1686
+ user_tmp = self.tables[table_name]
1687
+ insp = inspect(connection)
1688
+ cols = insp.get_columns(table_name)
1689
+ is_true(len(cols) > 0, len(cols))
1690
+
1691
+ for i, col in enumerate(user_tmp.columns):
1692
+ eq_(col.name, cols[i]["name"])
1693
+
1694
+ @testing.requires.temp_table_reflection
1695
+ @testing.requires.view_column_reflection
1696
+ @testing.requires.temporary_views
1697
+ def test_get_temp_view_columns(self, connection):
1698
+ insp = inspect(connection)
1699
+ cols = insp.get_columns("user_tmp_v")
1700
+ eq_([col["name"] for col in cols], ["id", "name", "foo"])
1701
+
1702
+ @testing.combinations(
1703
+ (False,), (True, testing.requires.schemas), argnames="use_schema"
1704
+ )
1705
+ @testing.requires.primary_key_constraint_reflection
1706
+ def test_get_pk_constraint(self, connection, use_schema):
1707
+ if use_schema:
1708
+ schema = testing.config.test_schema
1709
+ else:
1710
+ schema = None
1711
+
1712
+ users, addresses = self.tables.users, self.tables.email_addresses
1713
+ insp = inspect(connection)
1714
+ exp = self.exp_pks(schema=schema)
1715
+
1716
+ users_cons = insp.get_pk_constraint(users.name, schema=schema)
1717
+ self._check_list(
1718
+ [users_cons], [exp[(schema, users.name)]], self._required_pk_keys
1719
+ )
1720
+
1721
+ addr_cons = insp.get_pk_constraint(addresses.name, schema=schema)
1722
+ exp_cols = exp[(schema, addresses.name)]["constrained_columns"]
1723
+ eq_(addr_cons["constrained_columns"], exp_cols)
1724
+
1725
+ with testing.requires.reflects_pk_names.fail_if():
1726
+ eq_(addr_cons["name"], "email_ad_pk")
1727
+
1728
+ no_cst = self.tables.no_constraints.name
1729
+ self._check_list(
1730
+ [insp.get_pk_constraint(no_cst, schema=schema)],
1731
+ [exp[(schema, no_cst)]],
1732
+ self._required_pk_keys,
1733
+ )
1734
+
1735
+ @testing.combinations(
1736
+ (False,), (True, testing.requires.schemas), argnames="use_schema"
1737
+ )
1738
+ @testing.requires.foreign_key_constraint_reflection
1739
+ def test_get_foreign_keys(self, connection, use_schema):
1740
+ if use_schema:
1741
+ schema = config.test_schema
1742
+ else:
1743
+ schema = None
1744
+
1745
+ users, addresses = (self.tables.users, self.tables.email_addresses)
1746
+ insp = inspect(connection)
1747
+ expected_schema = schema
1748
+ # users
1749
+
1750
+ if testing.requires.self_referential_foreign_keys.enabled:
1751
+ users_fkeys = insp.get_foreign_keys(users.name, schema=schema)
1752
+ fkey1 = users_fkeys[0]
1753
+
1754
+ with testing.requires.named_constraints.fail_if():
1755
+ eq_(fkey1["name"], "user_id_fk")
1756
+
1757
+ eq_(fkey1["referred_schema"], expected_schema)
1758
+ eq_(fkey1["referred_table"], users.name)
1759
+ eq_(fkey1["referred_columns"], ["user_id"])
1760
+ eq_(fkey1["constrained_columns"], ["parent_user_id"])
1761
+
1762
+ # addresses
1763
+ addr_fkeys = insp.get_foreign_keys(addresses.name, schema=schema)
1764
+ fkey1 = addr_fkeys[0]
1765
+
1766
+ with testing.requires.implicitly_named_constraints.fail_if():
1767
+ is_true(fkey1["name"] is not None)
1768
+
1769
+ eq_(fkey1["referred_schema"], expected_schema)
1770
+ eq_(fkey1["referred_table"], users.name)
1771
+ eq_(fkey1["referred_columns"], ["user_id"])
1772
+ eq_(fkey1["constrained_columns"], ["remote_user_id"])
1773
+
1774
+ no_cst = self.tables.no_constraints.name
1775
+ eq_(insp.get_foreign_keys(no_cst, schema=schema), [])
1776
+
1777
+ @testing.requires.cross_schema_fk_reflection
1778
+ @testing.requires.schemas
1779
+ def test_get_inter_schema_foreign_keys(self, connection):
1780
+ local_table, remote_table, remote_table_2 = self.tables(
1781
+ "%s.local_table" % connection.dialect.default_schema_name,
1782
+ "%s.remote_table" % testing.config.test_schema,
1783
+ "%s.remote_table_2" % testing.config.test_schema,
1784
+ )
1785
+
1786
+ insp = inspect(connection)
1787
+
1788
+ local_fkeys = insp.get_foreign_keys(local_table.name)
1789
+ eq_(len(local_fkeys), 1)
1790
+
1791
+ fkey1 = local_fkeys[0]
1792
+ eq_(fkey1["referred_schema"], testing.config.test_schema)
1793
+ eq_(fkey1["referred_table"], remote_table_2.name)
1794
+ eq_(fkey1["referred_columns"], ["id"])
1795
+ eq_(fkey1["constrained_columns"], ["remote_id"])
1796
+
1797
+ remote_fkeys = insp.get_foreign_keys(
1798
+ remote_table.name, schema=testing.config.test_schema
1799
+ )
1800
+ eq_(len(remote_fkeys), 1)
1801
+
1802
+ fkey2 = remote_fkeys[0]
1803
+
1804
+ is_true(
1805
+ fkey2["referred_schema"]
1806
+ in (
1807
+ None,
1808
+ connection.dialect.default_schema_name,
1809
+ )
1810
+ )
1811
+ eq_(fkey2["referred_table"], local_table.name)
1812
+ eq_(fkey2["referred_columns"], ["id"])
1813
+ eq_(fkey2["constrained_columns"], ["local_id"])
1814
+
1815
+ @testing.combinations(
1816
+ (False,), (True, testing.requires.schemas), argnames="use_schema"
1817
+ )
1818
+ @testing.requires.index_reflection
1819
+ def test_get_indexes(self, connection, use_schema):
1820
+ if use_schema:
1821
+ schema = config.test_schema
1822
+ else:
1823
+ schema = None
1824
+
1825
+ # The database may decide to create indexes for foreign keys, etc.
1826
+ # so there may be more indexes than expected.
1827
+ insp = inspect(connection)
1828
+ indexes = insp.get_indexes("users", schema=schema)
1829
+ exp = self.exp_indexes(schema=schema)
1830
+ self._check_list(
1831
+ indexes, exp[(schema, "users")], self._required_index_keys
1832
+ )
1833
+
1834
+ no_cst = self.tables.no_constraints.name
1835
+ self._check_list(
1836
+ insp.get_indexes(no_cst, schema=schema),
1837
+ exp[(schema, no_cst)],
1838
+ self._required_index_keys,
1839
+ )
1840
+
1841
+ @testing.combinations(
1842
+ ("noncol_idx_test_nopk", "noncol_idx_nopk"),
1843
+ ("noncol_idx_test_pk", "noncol_idx_pk"),
1844
+ argnames="tname,ixname",
1845
+ )
1846
+ @testing.requires.index_reflection
1847
+ @testing.requires.indexes_with_ascdesc
1848
+ @testing.requires.reflect_indexes_with_ascdesc
1849
+ def test_get_noncol_index(self, connection, tname, ixname):
1850
+ insp = inspect(connection)
1851
+ indexes = insp.get_indexes(tname)
1852
+ # reflecting an index that has "x DESC" in it as the column.
1853
+ # the DB may or may not give us "x", but make sure we get the index
1854
+ # back, it has a name, it's connected to the table.
1855
+ expected_indexes = self.exp_indexes()[(None, tname)]
1856
+ self._check_list(indexes, expected_indexes, self._required_index_keys)
1857
+
1858
+ t = Table(tname, MetaData(), autoload_with=connection)
1859
+ eq_(len(t.indexes), 1)
1860
+ is_(list(t.indexes)[0].table, t)
1861
+ eq_(list(t.indexes)[0].name, ixname)
1862
+
1863
+ @testing.requires.temp_table_reflection
1864
+ @testing.requires.unique_constraint_reflection
1865
+ def test_get_temp_table_unique_constraints(self, connection):
1866
+ insp = inspect(connection)
1867
+ name = self.temp_table_name()
1868
+ reflected = insp.get_unique_constraints(name)
1869
+ exp = self.exp_ucs(all_=True)[(None, name)]
1870
+ self._check_list(reflected, exp, self._required_index_keys)
1871
+
1872
+ @testing.requires.temp_table_reflect_indexes
1873
+ def test_get_temp_table_indexes(self, connection):
1874
+ insp = inspect(connection)
1875
+ table_name = self.temp_table_name()
1876
+ indexes = insp.get_indexes(table_name)
1877
+ for ind in indexes:
1878
+ ind.pop("dialect_options", None)
1879
+ expected = [
1880
+ {"unique": False, "column_names": ["foo"], "name": "user_tmp_ix"}
1881
+ ]
1882
+ if testing.requires.index_reflects_included_columns.enabled:
1883
+ expected[0]["include_columns"] = []
1884
+ eq_(
1885
+ [idx for idx in indexes if idx["name"] == "user_tmp_ix"],
1886
+ expected,
1887
+ )
1888
+
1889
+ @testing.combinations(
1890
+ (True, testing.requires.schemas), (False,), argnames="use_schema"
1891
+ )
1892
+ @testing.requires.unique_constraint_reflection
1893
+ def test_get_unique_constraints(self, metadata, connection, use_schema):
1894
+ # SQLite dialect needs to parse the names of the constraints
1895
+ # separately from what it gets from PRAGMA index_list(), and
1896
+ # then matches them up. so same set of column_names in two
1897
+ # constraints will confuse it. Perhaps we should no longer
1898
+ # bother with index_list() here since we have the whole
1899
+ # CREATE TABLE?
1900
+
1901
+ if use_schema:
1902
+ schema = config.test_schema
1903
+ else:
1904
+ schema = None
1905
+ uniques = sorted(
1906
+ [
1907
+ {"name": "unique_a", "column_names": ["a"]},
1908
+ {"name": "unique_a_b_c", "column_names": ["a", "b", "c"]},
1909
+ {"name": "unique_c_a_b", "column_names": ["c", "a", "b"]},
1910
+ {"name": "unique_asc_key", "column_names": ["asc", "key"]},
1911
+ {"name": "i.have.dots", "column_names": ["b"]},
1912
+ {"name": "i have spaces", "column_names": ["c"]},
1913
+ ],
1914
+ key=operator.itemgetter("name"),
1915
+ )
1916
+ table = Table(
1917
+ "testtbl",
1918
+ metadata,
1919
+ Column("a", sa.String(20)),
1920
+ Column("b", sa.String(30)),
1921
+ Column("c", sa.Integer),
1922
+ # reserved identifiers
1923
+ Column("asc", sa.String(30)),
1924
+ Column("key", sa.String(30)),
1925
+ schema=schema,
1926
+ )
1927
+ for uc in uniques:
1928
+ table.append_constraint(
1929
+ sa.UniqueConstraint(*uc["column_names"], name=uc["name"])
1930
+ )
1931
+ table.create(connection)
1932
+
1933
+ insp = inspect(connection)
1934
+ reflected = sorted(
1935
+ insp.get_unique_constraints("testtbl", schema=schema),
1936
+ key=operator.itemgetter("name"),
1937
+ )
1938
+
1939
+ names_that_duplicate_index = set()
1940
+
1941
+ eq_(len(uniques), len(reflected))
1942
+
1943
+ for orig, refl in zip(uniques, reflected):
1944
+ # Different dialects handle duplicate index and constraints
1945
+ # differently, so ignore this flag
1946
+ dupe = refl.pop("duplicates_index", None)
1947
+ if dupe:
1948
+ names_that_duplicate_index.add(dupe)
1949
+ eq_(refl.pop("comment", None), None)
1950
+ eq_(orig, refl)
1951
+
1952
+ reflected_metadata = MetaData()
1953
+ reflected = Table(
1954
+ "testtbl",
1955
+ reflected_metadata,
1956
+ autoload_with=connection,
1957
+ schema=schema,
1958
+ )
1959
+
1960
+ # test "deduplicates for index" logic. MySQL and Oracle
1961
+ # "unique constraints" are actually unique indexes (with possible
1962
+ # exception of a unique that is a dupe of another one in the case
1963
+ # of Oracle). make sure # they aren't duplicated.
1964
+ idx_names = {idx.name for idx in reflected.indexes}
1965
+ uq_names = {
1966
+ uq.name
1967
+ for uq in reflected.constraints
1968
+ if isinstance(uq, sa.UniqueConstraint)
1969
+ }.difference(["unique_c_a_b"])
1970
+
1971
+ assert not idx_names.intersection(uq_names)
1972
+ if names_that_duplicate_index:
1973
+ eq_(names_that_duplicate_index, idx_names)
1974
+ eq_(uq_names, set())
1975
+
1976
+ no_cst = self.tables.no_constraints.name
1977
+ eq_(insp.get_unique_constraints(no_cst, schema=schema), [])
1978
+
1979
+ @testing.requires.view_reflection
1980
+ @testing.combinations(
1981
+ (False,), (True, testing.requires.schemas), argnames="use_schema"
1982
+ )
1983
+ def test_get_view_definition(self, connection, use_schema):
1984
+ if use_schema:
1985
+ schema = config.test_schema
1986
+ else:
1987
+ schema = None
1988
+ insp = inspect(connection)
1989
+ for view in ["users_v", "email_addresses_v", "dingalings_v"]:
1990
+ v = insp.get_view_definition(view, schema=schema)
1991
+ is_true(bool(v))
1992
+
1993
+ @testing.requires.view_reflection
1994
+ def test_get_view_definition_does_not_exist(self, connection):
1995
+ insp = inspect(connection)
1996
+ with expect_raises(NoSuchTableError):
1997
+ insp.get_view_definition("view_does_not_exist")
1998
+ with expect_raises(NoSuchTableError):
1999
+ insp.get_view_definition("users") # a table
2000
+
2001
+ @testing.requires.table_reflection
2002
+ def test_autoincrement_col(self, connection):
2003
+ """test that 'autoincrement' is reflected according to sqla's policy.
2004
+
2005
+ Don't mark this test as unsupported for any backend !
2006
+
2007
+ (technically it fails with MySQL InnoDB since "id" comes before "id2")
2008
+
2009
+ A backend is better off not returning "autoincrement" at all,
2010
+ instead of potentially returning "False" for an auto-incrementing
2011
+ primary key column.
2012
+
2013
+ """
2014
+
2015
+ insp = inspect(connection)
2016
+
2017
+ for tname, cname in [
2018
+ ("users", "user_id"),
2019
+ ("email_addresses", "address_id"),
2020
+ ("dingalings", "dingaling_id"),
2021
+ ]:
2022
+ cols = insp.get_columns(tname)
2023
+ id_ = {c["name"]: c for c in cols}[cname]
2024
+ assert id_.get("autoincrement", True)
2025
+
2026
+ @testing.combinations(
2027
+ (True, testing.requires.schemas), (False,), argnames="use_schema"
2028
+ )
2029
+ def test_get_table_options(self, use_schema):
2030
+ insp = inspect(config.db)
2031
+ schema = config.test_schema if use_schema else None
2032
+
2033
+ if testing.requires.reflect_table_options.enabled:
2034
+ res = insp.get_table_options("users", schema=schema)
2035
+ is_true(isinstance(res, dict))
2036
+ # NOTE: can't really create a table with no option
2037
+ res = insp.get_table_options("no_constraints", schema=schema)
2038
+ is_true(isinstance(res, dict))
2039
+ else:
2040
+ with expect_raises(NotImplementedError):
2041
+ res = insp.get_table_options("users", schema=schema)
2042
+
2043
+ @testing.combinations((True, testing.requires.schemas), False)
2044
+ def test_multi_get_table_options(self, use_schema):
2045
+ insp = inspect(config.db)
2046
+ if testing.requires.reflect_table_options.enabled:
2047
+ schema = config.test_schema if use_schema else None
2048
+ res = insp.get_multi_table_options(schema=schema)
2049
+
2050
+ exp = {
2051
+ (schema, table): insp.get_table_options(table, schema=schema)
2052
+ for table in insp.get_table_names(schema=schema)
2053
+ }
2054
+ eq_(res, exp)
2055
+ else:
2056
+ with expect_raises(NotImplementedError):
2057
+ res = insp.get_multi_table_options()
2058
+
2059
+ @testing.fixture
2060
+ def get_multi_exp(self, connection):
2061
+ def provide_fixture(
2062
+ schema, scope, kind, use_filter, single_reflect_fn, exp_method
2063
+ ):
2064
+ insp = inspect(connection)
2065
+ # call the reflection function at least once to avoid
2066
+ # "Unexpected success" errors if the result is actually empty
2067
+ # and NotImplementedError is not raised
2068
+ single_reflect_fn(insp, "email_addresses")
2069
+ kw = {"scope": scope, "kind": kind}
2070
+ if schema:
2071
+ schema = schema()
2072
+
2073
+ filter_names = []
2074
+
2075
+ if ObjectKind.TABLE in kind:
2076
+ filter_names.extend(
2077
+ ["comment_test", "users", "does-not-exist"]
2078
+ )
2079
+ if ObjectKind.VIEW in kind:
2080
+ filter_names.extend(["email_addresses_v", "does-not-exist"])
2081
+ if ObjectKind.MATERIALIZED_VIEW in kind:
2082
+ filter_names.extend(["dingalings_v", "does-not-exist"])
2083
+
2084
+ if schema:
2085
+ kw["schema"] = schema
2086
+ if use_filter:
2087
+ kw["filter_names"] = filter_names
2088
+
2089
+ exp = exp_method(
2090
+ schema=schema,
2091
+ scope=scope,
2092
+ kind=kind,
2093
+ filter_names=kw.get("filter_names"),
2094
+ )
2095
+ kws = [kw]
2096
+ if scope == ObjectScope.DEFAULT:
2097
+ nkw = kw.copy()
2098
+ nkw.pop("scope")
2099
+ kws.append(nkw)
2100
+ if kind == ObjectKind.TABLE:
2101
+ nkw = kw.copy()
2102
+ nkw.pop("kind")
2103
+ kws.append(nkw)
2104
+
2105
+ return inspect(connection), kws, exp
2106
+
2107
+ return provide_fixture
2108
+
2109
+ @testing.requires.reflect_table_options
2110
+ @_multi_combination
2111
+ def test_multi_get_table_options_tables(
2112
+ self, get_multi_exp, schema, scope, kind, use_filter
2113
+ ):
2114
+ insp, kws, exp = get_multi_exp(
2115
+ schema,
2116
+ scope,
2117
+ kind,
2118
+ use_filter,
2119
+ Inspector.get_table_options,
2120
+ self.exp_options,
2121
+ )
2122
+ for kw in kws:
2123
+ insp.clear_cache()
2124
+ result = insp.get_multi_table_options(**kw)
2125
+ eq_(result, exp)
2126
+
2127
+ @testing.requires.comment_reflection
2128
+ @_multi_combination
2129
+ def test_get_multi_table_comment(
2130
+ self, get_multi_exp, schema, scope, kind, use_filter
2131
+ ):
2132
+ insp, kws, exp = get_multi_exp(
2133
+ schema,
2134
+ scope,
2135
+ kind,
2136
+ use_filter,
2137
+ Inspector.get_table_comment,
2138
+ self.exp_comments,
2139
+ )
2140
+ for kw in kws:
2141
+ insp.clear_cache()
2142
+ eq_(insp.get_multi_table_comment(**kw), exp)
2143
+
2144
+ def _check_expressions(self, result, exp, err_msg):
2145
+ def _clean(text: str):
2146
+ return re.sub(r"['\" ]", "", text).lower()
2147
+
2148
+ if isinstance(exp, dict):
2149
+ eq_({_clean(e): v for e, v in result.items()}, exp, err_msg)
2150
+ else:
2151
+ eq_([_clean(e) for e in result], exp, err_msg)
2152
+
2153
+ def _check_list(self, result, exp, req_keys=None, msg=None):
2154
+ if req_keys is None:
2155
+ eq_(result, exp, msg)
2156
+ else:
2157
+ eq_(len(result), len(exp), msg)
2158
+ for r, e in zip(result, exp):
2159
+ for k in set(r) | set(e):
2160
+ if k in req_keys or (k in r and k in e):
2161
+ err_msg = f"{msg} - {k} - {r}"
2162
+ if k in ("expressions", "column_sorting"):
2163
+ self._check_expressions(r[k], e[k], err_msg)
2164
+ else:
2165
+ eq_(r[k], e[k], err_msg)
2166
+
2167
+ def _check_table_dict(self, result, exp, req_keys=None, make_lists=False):
2168
+ eq_(set(result.keys()), set(exp.keys()))
2169
+ for k in result:
2170
+ r, e = result[k], exp[k]
2171
+ if make_lists:
2172
+ r, e = [r], [e]
2173
+ self._check_list(r, e, req_keys, k)
2174
+
2175
+ @_multi_combination
2176
+ def test_get_multi_columns(
2177
+ self, get_multi_exp, schema, scope, kind, use_filter
2178
+ ):
2179
+ insp, kws, exp = get_multi_exp(
2180
+ schema,
2181
+ scope,
2182
+ kind,
2183
+ use_filter,
2184
+ Inspector.get_columns,
2185
+ self.exp_columns,
2186
+ )
2187
+
2188
+ for kw in kws:
2189
+ insp.clear_cache()
2190
+ result = insp.get_multi_columns(**kw)
2191
+ self._check_table_dict(result, exp, self._required_column_keys)
2192
+
2193
+ @testing.requires.primary_key_constraint_reflection
2194
+ @_multi_combination
2195
+ def test_get_multi_pk_constraint(
2196
+ self, get_multi_exp, schema, scope, kind, use_filter
2197
+ ):
2198
+ insp, kws, exp = get_multi_exp(
2199
+ schema,
2200
+ scope,
2201
+ kind,
2202
+ use_filter,
2203
+ Inspector.get_pk_constraint,
2204
+ self.exp_pks,
2205
+ )
2206
+ for kw in kws:
2207
+ insp.clear_cache()
2208
+ result = insp.get_multi_pk_constraint(**kw)
2209
+ self._check_table_dict(
2210
+ result, exp, self._required_pk_keys, make_lists=True
2211
+ )
2212
+
2213
+ def _adjust_sort(self, result, expected, key):
2214
+ if not testing.requires.implicitly_named_constraints.enabled:
2215
+ for obj in [result, expected]:
2216
+ for val in obj.values():
2217
+ if len(val) > 1 and any(
2218
+ v.get("name") in (None, mock.ANY) for v in val
2219
+ ):
2220
+ val.sort(key=key)
2221
+
2222
+ @testing.requires.foreign_key_constraint_reflection
2223
+ @_multi_combination
2224
+ def test_get_multi_foreign_keys(
2225
+ self, get_multi_exp, schema, scope, kind, use_filter
2226
+ ):
2227
+ insp, kws, exp = get_multi_exp(
2228
+ schema,
2229
+ scope,
2230
+ kind,
2231
+ use_filter,
2232
+ Inspector.get_foreign_keys,
2233
+ self.exp_fks,
2234
+ )
2235
+ for kw in kws:
2236
+ insp.clear_cache()
2237
+ result = insp.get_multi_foreign_keys(**kw)
2238
+ self._adjust_sort(
2239
+ result, exp, lambda d: tuple(d["constrained_columns"])
2240
+ )
2241
+ self._check_table_dict(result, exp, self._required_fk_keys)
2242
+
2243
+ @testing.requires.index_reflection
2244
+ @_multi_combination
2245
+ def test_get_multi_indexes(
2246
+ self, get_multi_exp, schema, scope, kind, use_filter
2247
+ ):
2248
+ insp, kws, exp = get_multi_exp(
2249
+ schema,
2250
+ scope,
2251
+ kind,
2252
+ use_filter,
2253
+ Inspector.get_indexes,
2254
+ self.exp_indexes,
2255
+ )
2256
+ for kw in kws:
2257
+ insp.clear_cache()
2258
+ result = insp.get_multi_indexes(**kw)
2259
+ self._check_table_dict(result, exp, self._required_index_keys)
2260
+
2261
+ @testing.requires.unique_constraint_reflection
2262
+ @_multi_combination
2263
+ def test_get_multi_unique_constraints(
2264
+ self, get_multi_exp, schema, scope, kind, use_filter
2265
+ ):
2266
+ insp, kws, exp = get_multi_exp(
2267
+ schema,
2268
+ scope,
2269
+ kind,
2270
+ use_filter,
2271
+ Inspector.get_unique_constraints,
2272
+ self.exp_ucs,
2273
+ )
2274
+ for kw in kws:
2275
+ insp.clear_cache()
2276
+ result = insp.get_multi_unique_constraints(**kw)
2277
+ self._adjust_sort(result, exp, lambda d: tuple(d["column_names"]))
2278
+ self._check_table_dict(result, exp, self._required_unique_cst_keys)
2279
+
2280
+ @testing.requires.check_constraint_reflection
2281
+ @_multi_combination
2282
+ def test_get_multi_check_constraints(
2283
+ self, get_multi_exp, schema, scope, kind, use_filter
2284
+ ):
2285
+ insp, kws, exp = get_multi_exp(
2286
+ schema,
2287
+ scope,
2288
+ kind,
2289
+ use_filter,
2290
+ Inspector.get_check_constraints,
2291
+ self.exp_ccs,
2292
+ )
2293
+ for kw in kws:
2294
+ insp.clear_cache()
2295
+ result = insp.get_multi_check_constraints(**kw)
2296
+ self._adjust_sort(result, exp, lambda d: tuple(d["sqltext"]))
2297
+ self._check_table_dict(result, exp, self._required_cc_keys)
2298
+
2299
+ @testing.combinations(
2300
+ ("get_table_options", testing.requires.reflect_table_options),
2301
+ "get_columns",
2302
+ (
2303
+ "get_pk_constraint",
2304
+ testing.requires.primary_key_constraint_reflection,
2305
+ ),
2306
+ (
2307
+ "get_foreign_keys",
2308
+ testing.requires.foreign_key_constraint_reflection,
2309
+ ),
2310
+ ("get_indexes", testing.requires.index_reflection),
2311
+ (
2312
+ "get_unique_constraints",
2313
+ testing.requires.unique_constraint_reflection,
2314
+ ),
2315
+ (
2316
+ "get_check_constraints",
2317
+ testing.requires.check_constraint_reflection,
2318
+ ),
2319
+ ("get_table_comment", testing.requires.comment_reflection),
2320
+ argnames="method",
2321
+ )
2322
+ def test_not_existing_table(self, method, connection):
2323
+ insp = inspect(connection)
2324
+ meth = getattr(insp, method)
2325
+ with expect_raises(NoSuchTableError):
2326
+ meth("table_does_not_exists")
2327
+
2328
+ def test_unreflectable(self, connection):
2329
+ mc = Inspector.get_multi_columns
2330
+
2331
+ def patched(*a, **k):
2332
+ ur = k.setdefault("unreflectable", {})
2333
+ ur[(None, "some_table")] = UnreflectableTableError("err")
2334
+ return mc(*a, **k)
2335
+
2336
+ with mock.patch.object(Inspector, "get_multi_columns", patched):
2337
+ with expect_raises_message(UnreflectableTableError, "err"):
2338
+ inspect(connection).reflect_table(
2339
+ Table("some_table", MetaData()), None
2340
+ )
2341
+
2342
+ @testing.combinations(True, False, argnames="use_schema")
2343
+ @testing.combinations(
2344
+ (True, testing.requires.views), False, argnames="views"
2345
+ )
2346
+ def test_metadata(self, connection, use_schema, views):
2347
+ m = MetaData()
2348
+ schema = config.test_schema if use_schema else None
2349
+ m.reflect(connection, schema=schema, views=views, resolve_fks=False)
2350
+
2351
+ insp = inspect(connection)
2352
+ tables = insp.get_table_names(schema)
2353
+ if views:
2354
+ tables += insp.get_view_names(schema)
2355
+ try:
2356
+ tables += insp.get_materialized_view_names(schema)
2357
+ except NotImplementedError:
2358
+ pass
2359
+ if schema:
2360
+ tables = [f"{schema}.{t}" for t in tables]
2361
+ eq_(sorted(m.tables), sorted(tables))
2362
+
2363
+ @testing.requires.comment_reflection
2364
+ def test_comments_unicode(self, connection, metadata):
2365
+ Table(
2366
+ "unicode_comments",
2367
+ metadata,
2368
+ Column("unicode", Integer, comment="é試蛇ẟΩ"),
2369
+ Column("emoji", Integer, comment="☁️✨"),
2370
+ comment="試蛇ẟΩ✨",
2371
+ )
2372
+
2373
+ metadata.create_all(connection)
2374
+
2375
+ insp = inspect(connection)
2376
+ tc = insp.get_table_comment("unicode_comments")
2377
+ eq_(tc, {"text": "試蛇ẟΩ✨"})
2378
+
2379
+ cols = insp.get_columns("unicode_comments")
2380
+ value = {c["name"]: c["comment"] for c in cols}
2381
+ exp = {"unicode": "é試蛇ẟΩ", "emoji": "☁️✨"}
2382
+ eq_(value, exp)
2383
+
2384
+ @testing.requires.comment_reflection_full_unicode
2385
+ def test_comments_unicode_full(self, connection, metadata):
2386
+ Table(
2387
+ "unicode_comments",
2388
+ metadata,
2389
+ Column("emoji", Integer, comment="🐍🧙🝝🧙‍♂️🧙‍♀️"),
2390
+ comment="🎩🁰🝑🤷‍♀️🤷‍♂️",
2391
+ )
2392
+
2393
+ metadata.create_all(connection)
2394
+
2395
+ insp = inspect(connection)
2396
+ tc = insp.get_table_comment("unicode_comments")
2397
+ eq_(tc, {"text": "🎩🁰🝑🤷‍♀️🤷‍♂️"})
2398
+ c = insp.get_columns("unicode_comments")[0]
2399
+ eq_({c["name"]: c["comment"]}, {"emoji": "🐍🧙🝝🧙‍♂️🧙‍♀️"})
2400
+
2401
+
2402
+ class TableNoColumnsTest(fixtures.TestBase):
2403
+ __requires__ = ("reflect_tables_no_columns",)
2404
+ __backend__ = True
2405
+
2406
+ @testing.fixture
2407
+ def table_no_columns(self, connection, metadata):
2408
+ Table("empty", metadata)
2409
+ metadata.create_all(connection)
2410
+
2411
+ @testing.fixture
2412
+ def view_no_columns(self, connection, metadata):
2413
+ Table("empty", metadata)
2414
+ event.listen(
2415
+ metadata,
2416
+ "after_create",
2417
+ DDL("CREATE VIEW empty_v AS SELECT * FROM empty"),
2418
+ )
2419
+
2420
+ # for transactional DDL the transaction is rolled back before this
2421
+ # drop statement is invoked
2422
+ event.listen(
2423
+ metadata, "before_drop", DDL("DROP VIEW IF EXISTS empty_v")
2424
+ )
2425
+ metadata.create_all(connection)
2426
+
2427
+ def test_reflect_table_no_columns(self, connection, table_no_columns):
2428
+ t2 = Table("empty", MetaData(), autoload_with=connection)
2429
+ eq_(list(t2.c), [])
2430
+
2431
+ def test_get_columns_table_no_columns(self, connection, table_no_columns):
2432
+ insp = inspect(connection)
2433
+ eq_(insp.get_columns("empty"), [])
2434
+ multi = insp.get_multi_columns()
2435
+ eq_(multi, {(None, "empty"): []})
2436
+
2437
+ def test_reflect_incl_table_no_columns(self, connection, table_no_columns):
2438
+ m = MetaData()
2439
+ m.reflect(connection)
2440
+ assert set(m.tables).intersection(["empty"])
2441
+
2442
+ @testing.requires.views
2443
+ def test_reflect_view_no_columns(self, connection, view_no_columns):
2444
+ t2 = Table("empty_v", MetaData(), autoload_with=connection)
2445
+ eq_(list(t2.c), [])
2446
+
2447
+ @testing.requires.views
2448
+ def test_get_columns_view_no_columns(self, connection, view_no_columns):
2449
+ insp = inspect(connection)
2450
+ eq_(insp.get_columns("empty_v"), [])
2451
+ multi = insp.get_multi_columns(kind=ObjectKind.VIEW)
2452
+ eq_(multi, {(None, "empty_v"): []})
2453
+
2454
+
2455
+ class ComponentReflectionTestExtra(ComparesIndexes, fixtures.TestBase):
2456
+ __backend__ = True
2457
+
2458
+ @testing.fixture(params=[True, False])
2459
+ def use_schema_fixture(self, request):
2460
+ if request.param:
2461
+ return config.test_schema
2462
+ else:
2463
+ return None
2464
+
2465
+ @testing.fixture()
2466
+ def inspect_for_table(self, metadata, connection, use_schema_fixture):
2467
+ @contextlib.contextmanager
2468
+ def go(tablename):
2469
+ yield use_schema_fixture, inspect(connection)
2470
+
2471
+ metadata.create_all(connection)
2472
+
2473
+ return go
2474
+
2475
+ def ck_eq(self, reflected, expected):
2476
+ # trying to minimize effect of quoting, parenthesis, etc.
2477
+ # may need to add more to this as new dialects get CHECK
2478
+ # constraint reflection support
2479
+ def normalize(sqltext):
2480
+ return " ".join(
2481
+ re.findall(r"and|\d|=|a|b|c|or|<|>", sqltext.lower(), re.I)
2482
+ )
2483
+
2484
+ reflected = sorted(
2485
+ [
2486
+ {"name": item["name"], "sqltext": normalize(item["sqltext"])}
2487
+ for item in reflected
2488
+ ],
2489
+ key=lambda item: (item["sqltext"]),
2490
+ )
2491
+
2492
+ expected = sorted(
2493
+ expected,
2494
+ key=lambda item: (item["sqltext"]),
2495
+ )
2496
+ eq_(reflected, expected)
2497
+
2498
+ @testing.requires.check_constraint_reflection
2499
+ def test_check_constraint_no_constraint(self, metadata, inspect_for_table):
2500
+ with inspect_for_table("no_constraints") as (schema, inspector):
2501
+ Table(
2502
+ "no_constraints",
2503
+ metadata,
2504
+ Column("data", sa.String(20)),
2505
+ schema=schema,
2506
+ )
2507
+
2508
+ self.ck_eq(
2509
+ inspector.get_check_constraints("no_constraints", schema=schema),
2510
+ [],
2511
+ )
2512
+
2513
+ @testing.requires.inline_check_constraint_reflection
2514
+ @testing.combinations(
2515
+ "my_inline", "MyInline", None, argnames="constraint_name"
2516
+ )
2517
+ def test_check_constraint_inline(
2518
+ self, metadata, inspect_for_table, constraint_name
2519
+ ):
2520
+
2521
+ with inspect_for_table("sa_cc") as (schema, inspector):
2522
+ Table(
2523
+ "sa_cc",
2524
+ metadata,
2525
+ Column("id", Integer(), primary_key=True),
2526
+ Column(
2527
+ "a",
2528
+ Integer(),
2529
+ sa.CheckConstraint(
2530
+ "a > 1 AND a < 5", name=constraint_name
2531
+ ),
2532
+ ),
2533
+ Column("data", String(50)),
2534
+ schema=schema,
2535
+ )
2536
+
2537
+ reflected = inspector.get_check_constraints("sa_cc", schema=schema)
2538
+
2539
+ self.ck_eq(
2540
+ reflected,
2541
+ [
2542
+ {
2543
+ "name": constraint_name or mock.ANY,
2544
+ "sqltext": "a > 1 and a < 5",
2545
+ },
2546
+ ],
2547
+ )
2548
+
2549
+ @testing.requires.check_constraint_reflection
2550
+ @testing.combinations(
2551
+ "my_ck_const", "MyCkConst", None, argnames="constraint_name"
2552
+ )
2553
+ def test_check_constraint_standalone(
2554
+ self, metadata, inspect_for_table, constraint_name
2555
+ ):
2556
+ with inspect_for_table("sa_cc") as (schema, inspector):
2557
+ Table(
2558
+ "sa_cc",
2559
+ metadata,
2560
+ Column("a", Integer()),
2561
+ sa.CheckConstraint(
2562
+ "a = 1 OR (a > 2 AND a < 5)", name=constraint_name
2563
+ ),
2564
+ schema=schema,
2565
+ )
2566
+
2567
+ reflected = inspector.get_check_constraints("sa_cc", schema=schema)
2568
+
2569
+ self.ck_eq(
2570
+ reflected,
2571
+ [
2572
+ {
2573
+ "name": constraint_name or mock.ANY,
2574
+ "sqltext": "a = 1 or a > 2 and a < 5",
2575
+ },
2576
+ ],
2577
+ )
2578
+
2579
+ @testing.requires.inline_check_constraint_reflection
2580
+ def test_check_constraint_mixed(self, metadata, inspect_for_table):
2581
+ with inspect_for_table("sa_cc") as (schema, inspector):
2582
+ Table(
2583
+ "sa_cc",
2584
+ metadata,
2585
+ Column("id", Integer(), primary_key=True),
2586
+ Column("a", Integer(), sa.CheckConstraint("a > 1 AND a < 5")),
2587
+ Column(
2588
+ "b",
2589
+ Integer(),
2590
+ sa.CheckConstraint("b > 1 AND b < 5", name="my_inline"),
2591
+ ),
2592
+ Column("c", Integer()),
2593
+ Column("data", String(50)),
2594
+ sa.UniqueConstraint("data", name="some_uq"),
2595
+ sa.CheckConstraint("c > 1 AND c < 5", name="cc1"),
2596
+ sa.UniqueConstraint("c", name="some_c_uq"),
2597
+ schema=schema,
2598
+ )
2599
+
2600
+ reflected = inspector.get_check_constraints("sa_cc", schema=schema)
2601
+
2602
+ self.ck_eq(
2603
+ reflected,
2604
+ [
2605
+ {"name": "cc1", "sqltext": "c > 1 and c < 5"},
2606
+ {"name": "my_inline", "sqltext": "b > 1 and b < 5"},
2607
+ {"name": mock.ANY, "sqltext": "a > 1 and a < 5"},
2608
+ ],
2609
+ )
2610
+
2611
+ @testing.requires.indexes_with_expressions
2612
+ def test_reflect_expression_based_indexes(self, metadata, connection):
2613
+ t = Table(
2614
+ "t",
2615
+ metadata,
2616
+ Column("x", String(30)),
2617
+ Column("y", String(30)),
2618
+ Column("z", String(30)),
2619
+ )
2620
+
2621
+ Index("t_idx", func.lower(t.c.x), t.c.z, func.lower(t.c.y))
2622
+ long_str = "long string " * 100
2623
+ Index("t_idx_long", func.coalesce(t.c.x, long_str))
2624
+ Index("t_idx_2", t.c.x)
2625
+
2626
+ metadata.create_all(connection)
2627
+
2628
+ insp = inspect(connection)
2629
+
2630
+ expected = [
2631
+ {
2632
+ "name": "t_idx_2",
2633
+ "column_names": ["x"],
2634
+ "unique": False,
2635
+ "dialect_options": {},
2636
+ }
2637
+ ]
2638
+
2639
+ def completeIndex(entry):
2640
+ if testing.requires.index_reflects_included_columns.enabled:
2641
+ entry["include_columns"] = []
2642
+ entry["dialect_options"] = {
2643
+ f"{connection.engine.name}_include": []
2644
+ }
2645
+ else:
2646
+ entry.setdefault("dialect_options", {})
2647
+
2648
+ completeIndex(expected[0])
2649
+
2650
+ class lower_index_str(str):
2651
+ def __eq__(self, other):
2652
+ ol = other.lower()
2653
+ # test that lower and x or y are in the string
2654
+ return "lower" in ol and ("x" in ol or "y" in ol)
2655
+
2656
+ class coalesce_index_str(str):
2657
+ def __eq__(self, other):
2658
+ # test that coalesce and the string is in other
2659
+ return "coalesce" in other.lower() and long_str in other
2660
+
2661
+ if testing.requires.reflect_indexes_with_expressions.enabled:
2662
+ expr_index = {
2663
+ "name": "t_idx",
2664
+ "column_names": [None, "z", None],
2665
+ "expressions": [
2666
+ lower_index_str("lower(x)"),
2667
+ "z",
2668
+ lower_index_str("lower(y)"),
2669
+ ],
2670
+ "unique": False,
2671
+ }
2672
+ completeIndex(expr_index)
2673
+ expected.insert(0, expr_index)
2674
+
2675
+ expr_index_long = {
2676
+ "name": "t_idx_long",
2677
+ "column_names": [None],
2678
+ "expressions": [
2679
+ coalesce_index_str(f"coalesce(x, '{long_str}')")
2680
+ ],
2681
+ "unique": False,
2682
+ }
2683
+ completeIndex(expr_index_long)
2684
+ expected.append(expr_index_long)
2685
+
2686
+ eq_(insp.get_indexes("t"), expected)
2687
+ m2 = MetaData()
2688
+ t2 = Table("t", m2, autoload_with=connection)
2689
+ else:
2690
+ with expect_warnings(
2691
+ "Skipped unsupported reflection of expression-based "
2692
+ "index t_idx"
2693
+ ):
2694
+ eq_(insp.get_indexes("t"), expected)
2695
+ m2 = MetaData()
2696
+ t2 = Table("t", m2, autoload_with=connection)
2697
+
2698
+ self.compare_table_index_with_expected(
2699
+ t2, expected, connection.engine.name
2700
+ )
2701
+
2702
+ @testing.requires.index_reflects_included_columns
2703
+ def test_reflect_covering_index(self, metadata, connection):
2704
+ t = Table(
2705
+ "t",
2706
+ metadata,
2707
+ Column("x", String(30)),
2708
+ Column("y", String(30)),
2709
+ )
2710
+ idx = Index("t_idx", t.c.x)
2711
+ idx.dialect_options[connection.engine.name]["include"] = ["y"]
2712
+
2713
+ metadata.create_all(connection)
2714
+
2715
+ insp = inspect(connection)
2716
+
2717
+ get_indexes = insp.get_indexes("t")
2718
+ eq_(
2719
+ get_indexes,
2720
+ [
2721
+ {
2722
+ "name": "t_idx",
2723
+ "column_names": ["x"],
2724
+ "include_columns": ["y"],
2725
+ "unique": False,
2726
+ "dialect_options": mock.ANY,
2727
+ }
2728
+ ],
2729
+ )
2730
+ eq_(
2731
+ get_indexes[0]["dialect_options"][
2732
+ "%s_include" % connection.engine.name
2733
+ ],
2734
+ ["y"],
2735
+ )
2736
+
2737
+ t2 = Table("t", MetaData(), autoload_with=connection)
2738
+ eq_(
2739
+ list(t2.indexes)[0].dialect_options[connection.engine.name][
2740
+ "include"
2741
+ ],
2742
+ ["y"],
2743
+ )
2744
+
2745
+ def _type_round_trip(self, connection, metadata, *types):
2746
+ t = Table(
2747
+ "t",
2748
+ metadata,
2749
+ *[Column("t%d" % i, type_) for i, type_ in enumerate(types)],
2750
+ )
2751
+ t.create(connection)
2752
+
2753
+ return [c["type"] for c in inspect(connection).get_columns("t")]
2754
+
2755
+ @testing.requires.table_reflection
2756
+ def test_numeric_reflection(self, connection, metadata):
2757
+ for typ in self._type_round_trip(
2758
+ connection, metadata, sql_types.Numeric(18, 5)
2759
+ ):
2760
+ assert isinstance(typ, sql_types.Numeric)
2761
+ eq_(typ.precision, 18)
2762
+ eq_(typ.scale, 5)
2763
+
2764
+ @testing.requires.table_reflection
2765
+ def test_varchar_reflection(self, connection, metadata):
2766
+ typ = self._type_round_trip(
2767
+ connection, metadata, sql_types.String(52)
2768
+ )[0]
2769
+ assert isinstance(typ, sql_types.String)
2770
+ eq_(typ.length, 52)
2771
+
2772
+ @testing.requires.table_reflection
2773
+ def test_nullable_reflection(self, connection, metadata):
2774
+ t = Table(
2775
+ "t",
2776
+ metadata,
2777
+ Column("a", Integer, nullable=True),
2778
+ Column("b", Integer, nullable=False),
2779
+ )
2780
+ t.create(connection)
2781
+ eq_(
2782
+ {
2783
+ col["name"]: col["nullable"]
2784
+ for col in inspect(connection).get_columns("t")
2785
+ },
2786
+ {"a": True, "b": False},
2787
+ )
2788
+
2789
+ @testing.combinations(
2790
+ (
2791
+ None,
2792
+ "CASCADE",
2793
+ None,
2794
+ testing.requires.foreign_key_constraint_option_reflection_ondelete,
2795
+ ),
2796
+ (
2797
+ None,
2798
+ None,
2799
+ "SET NULL",
2800
+ testing.requires.foreign_key_constraint_option_reflection_onupdate,
2801
+ ),
2802
+ (
2803
+ {},
2804
+ None,
2805
+ "NO ACTION",
2806
+ testing.requires.foreign_key_constraint_option_reflection_onupdate,
2807
+ ),
2808
+ (
2809
+ {},
2810
+ "NO ACTION",
2811
+ None,
2812
+ testing.requires.fk_constraint_option_reflection_ondelete_noaction,
2813
+ ),
2814
+ (
2815
+ None,
2816
+ None,
2817
+ "RESTRICT",
2818
+ testing.requires.fk_constraint_option_reflection_onupdate_restrict,
2819
+ ),
2820
+ (
2821
+ None,
2822
+ "RESTRICT",
2823
+ None,
2824
+ testing.requires.fk_constraint_option_reflection_ondelete_restrict,
2825
+ ),
2826
+ argnames="expected,ondelete,onupdate",
2827
+ )
2828
+ def test_get_foreign_key_options(
2829
+ self, connection, metadata, expected, ondelete, onupdate
2830
+ ):
2831
+ options = {}
2832
+ if ondelete:
2833
+ options["ondelete"] = ondelete
2834
+ if onupdate:
2835
+ options["onupdate"] = onupdate
2836
+
2837
+ if expected is None:
2838
+ expected = options
2839
+
2840
+ Table(
2841
+ "x",
2842
+ metadata,
2843
+ Column("id", Integer, primary_key=True),
2844
+ test_needs_fk=True,
2845
+ )
2846
+
2847
+ Table(
2848
+ "table",
2849
+ metadata,
2850
+ Column("id", Integer, primary_key=True),
2851
+ Column("x_id", Integer, ForeignKey("x.id", name="xid")),
2852
+ Column("test", String(10)),
2853
+ test_needs_fk=True,
2854
+ )
2855
+
2856
+ Table(
2857
+ "user",
2858
+ metadata,
2859
+ Column("id", Integer, primary_key=True),
2860
+ Column("name", String(50), nullable=False),
2861
+ Column("tid", Integer),
2862
+ sa.ForeignKeyConstraint(
2863
+ ["tid"], ["table.id"], name="myfk", **options
2864
+ ),
2865
+ test_needs_fk=True,
2866
+ )
2867
+
2868
+ metadata.create_all(connection)
2869
+
2870
+ insp = inspect(connection)
2871
+
2872
+ # test 'options' is always present for a backend
2873
+ # that can reflect these, since alembic looks for this
2874
+ opts = insp.get_foreign_keys("table")[0]["options"]
2875
+
2876
+ eq_({k: opts[k] for k in opts if opts[k]}, {})
2877
+
2878
+ opts = insp.get_foreign_keys("user")[0]["options"]
2879
+ eq_(opts, expected)
2880
+ # eq_(dict((k, opts[k]) for k in opts if opts[k]), expected)
2881
+
2882
+
2883
+ class NormalizedNameTest(fixtures.TablesTest):
2884
+ __requires__ = ("denormalized_names",)
2885
+ __backend__ = True
2886
+
2887
+ @classmethod
2888
+ def define_tables(cls, metadata):
2889
+ Table(
2890
+ quoted_name("t1", quote=True),
2891
+ metadata,
2892
+ Column("id", Integer, primary_key=True),
2893
+ )
2894
+ Table(
2895
+ quoted_name("t2", quote=True),
2896
+ metadata,
2897
+ Column("id", Integer, primary_key=True),
2898
+ Column("t1id", ForeignKey("t1.id")),
2899
+ )
2900
+
2901
+ def test_reflect_lowercase_forced_tables(self):
2902
+ m2 = MetaData()
2903
+ t2_ref = Table(
2904
+ quoted_name("t2", quote=True), m2, autoload_with=config.db
2905
+ )
2906
+ t1_ref = m2.tables["t1"]
2907
+ assert t2_ref.c.t1id.references(t1_ref.c.id)
2908
+
2909
+ m3 = MetaData()
2910
+ m3.reflect(
2911
+ config.db, only=lambda name, m: name.lower() in ("t1", "t2")
2912
+ )
2913
+ assert m3.tables["t2"].c.t1id.references(m3.tables["t1"].c.id)
2914
+
2915
+ def test_get_table_names(self):
2916
+ tablenames = [
2917
+ t
2918
+ for t in inspect(config.db).get_table_names()
2919
+ if t.lower() in ("t1", "t2")
2920
+ ]
2921
+
2922
+ eq_(tablenames[0].upper(), tablenames[0].lower())
2923
+ eq_(tablenames[1].upper(), tablenames[1].lower())
2924
+
2925
+
2926
+ class ComputedReflectionTest(fixtures.ComputedReflectionFixtureTest):
2927
+ def test_computed_col_default_not_set(self):
2928
+ insp = inspect(config.db)
2929
+
2930
+ cols = insp.get_columns("computed_default_table")
2931
+ col_data = {c["name"]: c for c in cols}
2932
+ is_true("42" in col_data["with_default"]["default"])
2933
+ is_(col_data["normal"]["default"], None)
2934
+ is_(col_data["computed_col"]["default"], None)
2935
+
2936
+ def test_get_column_returns_computed(self):
2937
+ insp = inspect(config.db)
2938
+
2939
+ cols = insp.get_columns("computed_default_table")
2940
+ data = {c["name"]: c for c in cols}
2941
+ for key in ("id", "normal", "with_default"):
2942
+ is_true("computed" not in data[key])
2943
+ compData = data["computed_col"]
2944
+ is_true("computed" in compData)
2945
+ is_true("sqltext" in compData["computed"])
2946
+ eq_(self.normalize(compData["computed"]["sqltext"]), "normal+42")
2947
+ eq_(
2948
+ "persisted" in compData["computed"],
2949
+ testing.requires.computed_columns_reflect_persisted.enabled,
2950
+ )
2951
+ if testing.requires.computed_columns_reflect_persisted.enabled:
2952
+ eq_(
2953
+ compData["computed"]["persisted"],
2954
+ testing.requires.computed_columns_default_persisted.enabled,
2955
+ )
2956
+
2957
+ def check_column(self, data, column, sqltext, persisted):
2958
+ is_true("computed" in data[column])
2959
+ compData = data[column]["computed"]
2960
+ eq_(self.normalize(compData["sqltext"]), sqltext)
2961
+ if testing.requires.computed_columns_reflect_persisted.enabled:
2962
+ is_true("persisted" in compData)
2963
+ is_(compData["persisted"], persisted)
2964
+
2965
+ def test_get_column_returns_persisted(self):
2966
+ insp = inspect(config.db)
2967
+
2968
+ cols = insp.get_columns("computed_column_table")
2969
+ data = {c["name"]: c for c in cols}
2970
+
2971
+ self.check_column(
2972
+ data,
2973
+ "computed_no_flag",
2974
+ "normal+42",
2975
+ testing.requires.computed_columns_default_persisted.enabled,
2976
+ )
2977
+ if testing.requires.computed_columns_virtual.enabled:
2978
+ self.check_column(
2979
+ data,
2980
+ "computed_virtual",
2981
+ "normal+2",
2982
+ False,
2983
+ )
2984
+ if testing.requires.computed_columns_stored.enabled:
2985
+ self.check_column(
2986
+ data,
2987
+ "computed_stored",
2988
+ "normal-42",
2989
+ True,
2990
+ )
2991
+
2992
+ @testing.requires.schemas
2993
+ def test_get_column_returns_persisted_with_schema(self):
2994
+ insp = inspect(config.db)
2995
+
2996
+ cols = insp.get_columns(
2997
+ "computed_column_table", schema=config.test_schema
2998
+ )
2999
+ data = {c["name"]: c for c in cols}
3000
+
3001
+ self.check_column(
3002
+ data,
3003
+ "computed_no_flag",
3004
+ "normal/42",
3005
+ testing.requires.computed_columns_default_persisted.enabled,
3006
+ )
3007
+ if testing.requires.computed_columns_virtual.enabled:
3008
+ self.check_column(
3009
+ data,
3010
+ "computed_virtual",
3011
+ "normal/2",
3012
+ False,
3013
+ )
3014
+ if testing.requires.computed_columns_stored.enabled:
3015
+ self.check_column(
3016
+ data,
3017
+ "computed_stored",
3018
+ "normal*42",
3019
+ True,
3020
+ )
3021
+
3022
+
3023
+ class IdentityReflectionTest(fixtures.TablesTest):
3024
+ run_inserts = run_deletes = None
3025
+
3026
+ __backend__ = True
3027
+ __requires__ = ("identity_columns", "table_reflection")
3028
+
3029
+ @classmethod
3030
+ def define_tables(cls, metadata):
3031
+ Table(
3032
+ "t1",
3033
+ metadata,
3034
+ Column("normal", Integer),
3035
+ Column("id1", Integer, Identity()),
3036
+ )
3037
+ Table(
3038
+ "t2",
3039
+ metadata,
3040
+ Column(
3041
+ "id2",
3042
+ Integer,
3043
+ Identity(
3044
+ always=True,
3045
+ start=2,
3046
+ increment=3,
3047
+ minvalue=-2,
3048
+ maxvalue=42,
3049
+ cycle=True,
3050
+ cache=4,
3051
+ ),
3052
+ ),
3053
+ )
3054
+ if testing.requires.schemas.enabled:
3055
+ Table(
3056
+ "t1",
3057
+ metadata,
3058
+ Column("normal", Integer),
3059
+ Column("id1", Integer, Identity(always=True, start=20)),
3060
+ schema=config.test_schema,
3061
+ )
3062
+
3063
+ def check(self, value, exp, approx):
3064
+ if testing.requires.identity_columns_standard.enabled:
3065
+ common_keys = (
3066
+ "always",
3067
+ "start",
3068
+ "increment",
3069
+ "minvalue",
3070
+ "maxvalue",
3071
+ "cycle",
3072
+ "cache",
3073
+ )
3074
+ for k in list(value):
3075
+ if k not in common_keys:
3076
+ value.pop(k)
3077
+ if approx:
3078
+ eq_(len(value), len(exp))
3079
+ for k in value:
3080
+ if k == "minvalue":
3081
+ is_true(value[k] <= exp[k])
3082
+ elif k in {"maxvalue", "cache"}:
3083
+ is_true(value[k] >= exp[k])
3084
+ else:
3085
+ eq_(value[k], exp[k], k)
3086
+ else:
3087
+ eq_(value, exp)
3088
+ else:
3089
+ eq_(value["start"], exp["start"])
3090
+ eq_(value["increment"], exp["increment"])
3091
+
3092
+ def test_reflect_identity(self):
3093
+ insp = inspect(config.db)
3094
+
3095
+ cols = insp.get_columns("t1") + insp.get_columns("t2")
3096
+ for col in cols:
3097
+ if col["name"] == "normal":
3098
+ is_false("identity" in col)
3099
+ elif col["name"] == "id1":
3100
+ if "autoincrement" in col:
3101
+ is_true(col["autoincrement"])
3102
+ eq_(col["default"], None)
3103
+ is_true("identity" in col)
3104
+ self.check(
3105
+ col["identity"],
3106
+ dict(
3107
+ always=False,
3108
+ start=1,
3109
+ increment=1,
3110
+ minvalue=1,
3111
+ maxvalue=2147483647,
3112
+ cycle=False,
3113
+ cache=1,
3114
+ ),
3115
+ approx=True,
3116
+ )
3117
+ elif col["name"] == "id2":
3118
+ if "autoincrement" in col:
3119
+ is_true(col["autoincrement"])
3120
+ eq_(col["default"], None)
3121
+ is_true("identity" in col)
3122
+ self.check(
3123
+ col["identity"],
3124
+ dict(
3125
+ always=True,
3126
+ start=2,
3127
+ increment=3,
3128
+ minvalue=-2,
3129
+ maxvalue=42,
3130
+ cycle=True,
3131
+ cache=4,
3132
+ ),
3133
+ approx=False,
3134
+ )
3135
+
3136
+ @testing.requires.schemas
3137
+ def test_reflect_identity_schema(self):
3138
+ insp = inspect(config.db)
3139
+
3140
+ cols = insp.get_columns("t1", schema=config.test_schema)
3141
+ for col in cols:
3142
+ if col["name"] == "normal":
3143
+ is_false("identity" in col)
3144
+ elif col["name"] == "id1":
3145
+ if "autoincrement" in col:
3146
+ is_true(col["autoincrement"])
3147
+ eq_(col["default"], None)
3148
+ is_true("identity" in col)
3149
+ self.check(
3150
+ col["identity"],
3151
+ dict(
3152
+ always=True,
3153
+ start=20,
3154
+ increment=1,
3155
+ minvalue=1,
3156
+ maxvalue=2147483647,
3157
+ cycle=False,
3158
+ cache=1,
3159
+ ),
3160
+ approx=True,
3161
+ )
3162
+
3163
+
3164
+ class CompositeKeyReflectionTest(fixtures.TablesTest):
3165
+ __backend__ = True
3166
+
3167
+ @classmethod
3168
+ def define_tables(cls, metadata):
3169
+ tb1 = Table(
3170
+ "tb1",
3171
+ metadata,
3172
+ Column("id", Integer),
3173
+ Column("attr", Integer),
3174
+ Column("name", sql_types.VARCHAR(20)),
3175
+ sa.PrimaryKeyConstraint("name", "id", "attr", name="pk_tb1"),
3176
+ schema=None,
3177
+ test_needs_fk=True,
3178
+ )
3179
+ Table(
3180
+ "tb2",
3181
+ metadata,
3182
+ Column("id", Integer, primary_key=True),
3183
+ Column("pid", Integer),
3184
+ Column("pattr", Integer),
3185
+ Column("pname", sql_types.VARCHAR(20)),
3186
+ sa.ForeignKeyConstraint(
3187
+ ["pname", "pid", "pattr"],
3188
+ [tb1.c.name, tb1.c.id, tb1.c.attr],
3189
+ name="fk_tb1_name_id_attr",
3190
+ ),
3191
+ schema=None,
3192
+ test_needs_fk=True,
3193
+ )
3194
+
3195
+ @testing.requires.primary_key_constraint_reflection
3196
+ def test_pk_column_order(self, connection):
3197
+ # test for issue #5661
3198
+ insp = inspect(connection)
3199
+ primary_key = insp.get_pk_constraint(self.tables.tb1.name)
3200
+ eq_(primary_key.get("constrained_columns"), ["name", "id", "attr"])
3201
+
3202
+ @testing.requires.foreign_key_constraint_reflection
3203
+ def test_fk_column_order(self, connection):
3204
+ # test for issue #5661
3205
+ insp = inspect(connection)
3206
+ foreign_keys = insp.get_foreign_keys(self.tables.tb2.name)
3207
+ eq_(len(foreign_keys), 1)
3208
+ fkey1 = foreign_keys[0]
3209
+ eq_(fkey1.get("referred_columns"), ["name", "id", "attr"])
3210
+ eq_(fkey1.get("constrained_columns"), ["pname", "pid", "pattr"])
3211
+
3212
+
3213
+ __all__ = (
3214
+ "ComponentReflectionTest",
3215
+ "ComponentReflectionTestExtra",
3216
+ "TableNoColumnsTest",
3217
+ "QuotedNameArgumentTest",
3218
+ "BizarroCharacterFKResolutionTest",
3219
+ "HasTableTest",
3220
+ "HasIndexTest",
3221
+ "NormalizedNameTest",
3222
+ "ComputedReflectionTest",
3223
+ "IdentityReflectionTest",
3224
+ "CompositeKeyReflectionTest",
3225
+ )