test_reflection.py 104 KB

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