reflection.py 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843
  1. # engine/reflection.py
  2. # Copyright (C) 2005-2017 the SQLAlchemy authors and contributors
  3. # <see AUTHORS file>
  4. #
  5. # This module is part of SQLAlchemy and is released under
  6. # the MIT License: http://www.opensource.org/licenses/mit-license.php
  7. """Provides an abstraction for obtaining database schema information.
  8. Usage Notes:
  9. Here are some general conventions when accessing the low level inspector
  10. methods such as get_table_names, get_columns, etc.
  11. 1. Inspector methods return lists of dicts in most cases for the following
  12. reasons:
  13. * They're both standard types that can be serialized.
  14. * Using a dict instead of a tuple allows easy expansion of attributes.
  15. * Using a list for the outer structure maintains order and is easy to work
  16. with (e.g. list comprehension [d['name'] for d in cols]).
  17. 2. Records that contain a name, such as the column name in a column record
  18. use the key 'name'. So for most return values, each record will have a
  19. 'name' attribute..
  20. """
  21. from .. import exc, sql
  22. from ..sql import schema as sa_schema
  23. from .. import util
  24. from ..sql.type_api import TypeEngine
  25. from ..util import deprecated
  26. from ..util import topological
  27. from .. import inspection
  28. from .base import Connectable
  29. @util.decorator
  30. def cache(fn, self, con, *args, **kw):
  31. info_cache = kw.get('info_cache', None)
  32. if info_cache is None:
  33. return fn(self, con, *args, **kw)
  34. key = (
  35. fn.__name__,
  36. tuple(a for a in args if isinstance(a, util.string_types)),
  37. tuple((k, v) for k, v in kw.items() if
  38. isinstance(v,
  39. util.string_types + util.int_types + (float, )
  40. )
  41. )
  42. )
  43. ret = info_cache.get(key)
  44. if ret is None:
  45. ret = fn(self, con, *args, **kw)
  46. info_cache[key] = ret
  47. return ret
  48. class Inspector(object):
  49. """Performs database schema inspection.
  50. The Inspector acts as a proxy to the reflection methods of the
  51. :class:`~sqlalchemy.engine.interfaces.Dialect`, providing a
  52. consistent interface as well as caching support for previously
  53. fetched metadata.
  54. A :class:`.Inspector` object is usually created via the
  55. :func:`.inspect` function::
  56. from sqlalchemy import inspect, create_engine
  57. engine = create_engine('...')
  58. insp = inspect(engine)
  59. The inspection method above is equivalent to using the
  60. :meth:`.Inspector.from_engine` method, i.e.::
  61. engine = create_engine('...')
  62. insp = Inspector.from_engine(engine)
  63. Where above, the :class:`~sqlalchemy.engine.interfaces.Dialect` may opt
  64. to return an :class:`.Inspector` subclass that provides additional
  65. methods specific to the dialect's target database.
  66. """
  67. def __init__(self, bind):
  68. """Initialize a new :class:`.Inspector`.
  69. :param bind: a :class:`~sqlalchemy.engine.Connectable`,
  70. which is typically an instance of
  71. :class:`~sqlalchemy.engine.Engine` or
  72. :class:`~sqlalchemy.engine.Connection`.
  73. For a dialect-specific instance of :class:`.Inspector`, see
  74. :meth:`.Inspector.from_engine`
  75. """
  76. # this might not be a connection, it could be an engine.
  77. self.bind = bind
  78. # set the engine
  79. if hasattr(bind, 'engine'):
  80. self.engine = bind.engine
  81. else:
  82. self.engine = bind
  83. if self.engine is bind:
  84. # if engine, ensure initialized
  85. bind.connect().close()
  86. self.dialect = self.engine.dialect
  87. self.info_cache = {}
  88. @classmethod
  89. def from_engine(cls, bind):
  90. """Construct a new dialect-specific Inspector object from the given
  91. engine or connection.
  92. :param bind: a :class:`~sqlalchemy.engine.Connectable`,
  93. which is typically an instance of
  94. :class:`~sqlalchemy.engine.Engine` or
  95. :class:`~sqlalchemy.engine.Connection`.
  96. This method differs from direct a direct constructor call of
  97. :class:`.Inspector` in that the
  98. :class:`~sqlalchemy.engine.interfaces.Dialect` is given a chance to
  99. provide a dialect-specific :class:`.Inspector` instance, which may
  100. provide additional methods.
  101. See the example at :class:`.Inspector`.
  102. """
  103. if hasattr(bind.dialect, 'inspector'):
  104. return bind.dialect.inspector(bind)
  105. return Inspector(bind)
  106. @inspection._inspects(Connectable)
  107. def _insp(bind):
  108. return Inspector.from_engine(bind)
  109. @property
  110. def default_schema_name(self):
  111. """Return the default schema name presented by the dialect
  112. for the current engine's database user.
  113. E.g. this is typically ``public`` for PostgreSQL and ``dbo``
  114. for SQL Server.
  115. """
  116. return self.dialect.default_schema_name
  117. def get_schema_names(self):
  118. """Return all schema names.
  119. """
  120. if hasattr(self.dialect, 'get_schema_names'):
  121. return self.dialect.get_schema_names(self.bind,
  122. info_cache=self.info_cache)
  123. return []
  124. def get_table_names(self, schema=None, order_by=None):
  125. """Return all table names in referred to within a particular schema.
  126. The names are expected to be real tables only, not views.
  127. Views are instead returned using the :meth:`.Inspector.get_view_names`
  128. method.
  129. :param schema: Schema name. If ``schema`` is left at ``None``, the
  130. database's default schema is
  131. used, else the named schema is searched. If the database does not
  132. support named schemas, behavior is undefined if ``schema`` is not
  133. passed as ``None``. For special quoting, use :class:`.quoted_name`.
  134. :param order_by: Optional, may be the string "foreign_key" to sort
  135. the result on foreign key dependencies. Does not automatically
  136. resolve cycles, and will raise :class:`.CircularDependencyError`
  137. if cycles exist.
  138. .. deprecated:: 1.0.0 - see
  139. :meth:`.Inspector.get_sorted_table_and_fkc_names` for a version
  140. of this which resolves foreign key cycles between tables
  141. automatically.
  142. .. versionchanged:: 0.8 the "foreign_key" sorting sorts tables
  143. in order of dependee to dependent; that is, in creation
  144. order, rather than in drop order. This is to maintain
  145. consistency with similar features such as
  146. :attr:`.MetaData.sorted_tables` and :func:`.util.sort_tables`.
  147. .. seealso::
  148. :meth:`.Inspector.get_sorted_table_and_fkc_names`
  149. :attr:`.MetaData.sorted_tables`
  150. """
  151. if hasattr(self.dialect, 'get_table_names'):
  152. tnames = self.dialect.get_table_names(
  153. self.bind, schema, info_cache=self.info_cache)
  154. else:
  155. tnames = self.engine.table_names(schema)
  156. if order_by == 'foreign_key':
  157. tuples = []
  158. for tname in tnames:
  159. for fkey in self.get_foreign_keys(tname, schema):
  160. if tname != fkey['referred_table']:
  161. tuples.append((fkey['referred_table'], tname))
  162. tnames = list(topological.sort(tuples, tnames))
  163. return tnames
  164. def get_sorted_table_and_fkc_names(self, schema=None):
  165. """Return dependency-sorted table and foreign key constraint names in
  166. referred to within a particular schema.
  167. This will yield 2-tuples of
  168. ``(tablename, [(tname, fkname), (tname, fkname), ...])``
  169. consisting of table names in CREATE order grouped with the foreign key
  170. constraint names that are not detected as belonging to a cycle.
  171. The final element
  172. will be ``(None, [(tname, fkname), (tname, fkname), ..])``
  173. which will consist of remaining
  174. foreign key constraint names that would require a separate CREATE
  175. step after-the-fact, based on dependencies between tables.
  176. .. versionadded:: 1.0.-
  177. .. seealso::
  178. :meth:`.Inspector.get_table_names`
  179. :func:`.sort_tables_and_constraints` - similar method which works
  180. with an already-given :class:`.MetaData`.
  181. """
  182. if hasattr(self.dialect, 'get_table_names'):
  183. tnames = self.dialect.get_table_names(
  184. self.bind, schema, info_cache=self.info_cache)
  185. else:
  186. tnames = self.engine.table_names(schema)
  187. tuples = set()
  188. remaining_fkcs = set()
  189. fknames_for_table = {}
  190. for tname in tnames:
  191. fkeys = self.get_foreign_keys(tname, schema)
  192. fknames_for_table[tname] = set(
  193. [fk['name'] for fk in fkeys]
  194. )
  195. for fkey in fkeys:
  196. if tname != fkey['referred_table']:
  197. tuples.add((fkey['referred_table'], tname))
  198. try:
  199. candidate_sort = list(topological.sort(tuples, tnames))
  200. except exc.CircularDependencyError as err:
  201. for edge in err.edges:
  202. tuples.remove(edge)
  203. remaining_fkcs.update(
  204. (edge[1], fkc)
  205. for fkc in fknames_for_table[edge[1]]
  206. )
  207. candidate_sort = list(topological.sort(tuples, tnames))
  208. return [
  209. (tname, fknames_for_table[tname].difference(remaining_fkcs))
  210. for tname in candidate_sort
  211. ] + [(None, list(remaining_fkcs))]
  212. def get_temp_table_names(self):
  213. """return a list of temporary table names for the current bind.
  214. This method is unsupported by most dialects; currently
  215. only SQLite implements it.
  216. .. versionadded:: 1.0.0
  217. """
  218. return self.dialect.get_temp_table_names(
  219. self.bind, info_cache=self.info_cache)
  220. def get_temp_view_names(self):
  221. """return a list of temporary view names for the current bind.
  222. This method is unsupported by most dialects; currently
  223. only SQLite implements it.
  224. .. versionadded:: 1.0.0
  225. """
  226. return self.dialect.get_temp_view_names(
  227. self.bind, info_cache=self.info_cache)
  228. def get_table_options(self, table_name, schema=None, **kw):
  229. """Return a dictionary of options specified when the table of the
  230. given name was created.
  231. This currently includes some options that apply to MySQL tables.
  232. :param table_name: string name of the table. For special quoting,
  233. use :class:`.quoted_name`.
  234. :param schema: string schema name; if omitted, uses the default schema
  235. of the database connection. For special quoting,
  236. use :class:`.quoted_name`.
  237. """
  238. if hasattr(self.dialect, 'get_table_options'):
  239. return self.dialect.get_table_options(
  240. self.bind, table_name, schema,
  241. info_cache=self.info_cache, **kw)
  242. return {}
  243. def get_view_names(self, schema=None):
  244. """Return all view names in `schema`.
  245. :param schema: Optional, retrieve names from a non-default schema.
  246. For special quoting, use :class:`.quoted_name`.
  247. """
  248. return self.dialect.get_view_names(self.bind, schema,
  249. info_cache=self.info_cache)
  250. def get_view_definition(self, view_name, schema=None):
  251. """Return definition for `view_name`.
  252. :param schema: Optional, retrieve names from a non-default schema.
  253. For special quoting, use :class:`.quoted_name`.
  254. """
  255. return self.dialect.get_view_definition(
  256. self.bind, view_name, schema, info_cache=self.info_cache)
  257. def get_columns(self, table_name, schema=None, **kw):
  258. """Return information about columns in `table_name`.
  259. Given a string `table_name` and an optional string `schema`, return
  260. column information as a list of dicts with these keys:
  261. * ``name`` - the column's name
  262. * ``type`` - the type of this column; an instance of
  263. :class:`~sqlalchemy.types.TypeEngine`
  264. * ``nullable`` - boolean flag if the column is NULL or NOT NULL
  265. * ``default`` - the column's server default value - this is returned
  266. as a string SQL expression.
  267. * ``attrs`` - dict containing optional column attributes
  268. :param table_name: string name of the table. For special quoting,
  269. use :class:`.quoted_name`.
  270. :param schema: string schema name; if omitted, uses the default schema
  271. of the database connection. For special quoting,
  272. use :class:`.quoted_name`.
  273. :return: list of dictionaries, each representing the definition of
  274. a database column.
  275. """
  276. col_defs = self.dialect.get_columns(self.bind, table_name, schema,
  277. info_cache=self.info_cache,
  278. **kw)
  279. for col_def in col_defs:
  280. # make this easy and only return instances for coltype
  281. coltype = col_def['type']
  282. if not isinstance(coltype, TypeEngine):
  283. col_def['type'] = coltype()
  284. return col_defs
  285. @deprecated('0.7', 'Call to deprecated method get_primary_keys.'
  286. ' Use get_pk_constraint instead.')
  287. def get_primary_keys(self, table_name, schema=None, **kw):
  288. """Return information about primary keys in `table_name`.
  289. Given a string `table_name`, and an optional string `schema`, return
  290. primary key information as a list of column names.
  291. """
  292. return self.dialect.get_pk_constraint(self.bind, table_name, schema,
  293. info_cache=self.info_cache,
  294. **kw)['constrained_columns']
  295. def get_pk_constraint(self, table_name, schema=None, **kw):
  296. """Return information about primary key constraint on `table_name`.
  297. Given a string `table_name`, and an optional string `schema`, return
  298. primary key information as a dictionary with these keys:
  299. constrained_columns
  300. a list of column names that make up the primary key
  301. name
  302. optional name of the primary key constraint.
  303. :param table_name: string name of the table. For special quoting,
  304. use :class:`.quoted_name`.
  305. :param schema: string schema name; if omitted, uses the default schema
  306. of the database connection. For special quoting,
  307. use :class:`.quoted_name`.
  308. """
  309. return self.dialect.get_pk_constraint(self.bind, table_name, schema,
  310. info_cache=self.info_cache,
  311. **kw)
  312. def get_foreign_keys(self, table_name, schema=None, **kw):
  313. """Return information about foreign_keys in `table_name`.
  314. Given a string `table_name`, and an optional string `schema`, return
  315. foreign key information as a list of dicts with these keys:
  316. constrained_columns
  317. a list of column names that make up the foreign key
  318. referred_schema
  319. the name of the referred schema
  320. referred_table
  321. the name of the referred table
  322. referred_columns
  323. a list of column names in the referred table that correspond to
  324. constrained_columns
  325. name
  326. optional name of the foreign key constraint.
  327. :param table_name: string name of the table. For special quoting,
  328. use :class:`.quoted_name`.
  329. :param schema: string schema name; if omitted, uses the default schema
  330. of the database connection. For special quoting,
  331. use :class:`.quoted_name`.
  332. """
  333. return self.dialect.get_foreign_keys(self.bind, table_name, schema,
  334. info_cache=self.info_cache,
  335. **kw)
  336. def get_indexes(self, table_name, schema=None, **kw):
  337. """Return information about indexes in `table_name`.
  338. Given a string `table_name` and an optional string `schema`, return
  339. index information as a list of dicts with these keys:
  340. name
  341. the index's name
  342. column_names
  343. list of column names in order
  344. unique
  345. boolean
  346. dialect_options
  347. dict of dialect-specific index options. May not be present
  348. for all dialects.
  349. .. versionadded:: 1.0.0
  350. :param table_name: string name of the table. For special quoting,
  351. use :class:`.quoted_name`.
  352. :param schema: string schema name; if omitted, uses the default schema
  353. of the database connection. For special quoting,
  354. use :class:`.quoted_name`.
  355. """
  356. return self.dialect.get_indexes(self.bind, table_name,
  357. schema,
  358. info_cache=self.info_cache, **kw)
  359. def get_unique_constraints(self, table_name, schema=None, **kw):
  360. """Return information about unique constraints in `table_name`.
  361. Given a string `table_name` and an optional string `schema`, return
  362. unique constraint information as a list of dicts with these keys:
  363. name
  364. the unique constraint's name
  365. column_names
  366. list of column names in order
  367. :param table_name: string name of the table. For special quoting,
  368. use :class:`.quoted_name`.
  369. :param schema: string schema name; if omitted, uses the default schema
  370. of the database connection. For special quoting,
  371. use :class:`.quoted_name`.
  372. .. versionadded:: 0.8.4
  373. """
  374. return self.dialect.get_unique_constraints(
  375. self.bind, table_name, schema, info_cache=self.info_cache, **kw)
  376. def get_check_constraints(self, table_name, schema=None, **kw):
  377. """Return information about check constraints in `table_name`.
  378. Given a string `table_name` and an optional string `schema`, return
  379. check constraint information as a list of dicts with these keys:
  380. name
  381. the check constraint's name
  382. sqltext
  383. the check constraint's SQL expression
  384. :param table_name: string name of the table. For special quoting,
  385. use :class:`.quoted_name`.
  386. :param schema: string schema name; if omitted, uses the default schema
  387. of the database connection. For special quoting,
  388. use :class:`.quoted_name`.
  389. .. versionadded:: 1.1.0
  390. """
  391. return self.dialect.get_check_constraints(
  392. self.bind, table_name, schema, info_cache=self.info_cache, **kw)
  393. def reflecttable(self, table, include_columns, exclude_columns=(),
  394. _extend_on=None):
  395. """Given a Table object, load its internal constructs based on
  396. introspection.
  397. This is the underlying method used by most dialects to produce
  398. table reflection. Direct usage is like::
  399. from sqlalchemy import create_engine, MetaData, Table
  400. from sqlalchemy.engine import reflection
  401. engine = create_engine('...')
  402. meta = MetaData()
  403. user_table = Table('user', meta)
  404. insp = Inspector.from_engine(engine)
  405. insp.reflecttable(user_table, None)
  406. :param table: a :class:`~sqlalchemy.schema.Table` instance.
  407. :param include_columns: a list of string column names to include
  408. in the reflection process. If ``None``, all columns are reflected.
  409. """
  410. if _extend_on is not None:
  411. if table in _extend_on:
  412. return
  413. else:
  414. _extend_on.add(table)
  415. dialect = self.bind.dialect
  416. schema = self.bind.schema_for_object(table)
  417. table_name = table.name
  418. # get table-level arguments that are specifically
  419. # intended for reflection, e.g. oracle_resolve_synonyms.
  420. # these are unconditionally passed to related Table
  421. # objects
  422. reflection_options = dict(
  423. (k, table.dialect_kwargs.get(k))
  424. for k in dialect.reflection_options
  425. if k in table.dialect_kwargs
  426. )
  427. # reflect table options, like mysql_engine
  428. tbl_opts = self.get_table_options(
  429. table_name, schema, **table.dialect_kwargs)
  430. if tbl_opts:
  431. # add additional kwargs to the Table if the dialect
  432. # returned them
  433. table._validate_dialect_kwargs(tbl_opts)
  434. if util.py2k:
  435. if isinstance(schema, str):
  436. schema = schema.decode(dialect.encoding)
  437. if isinstance(table_name, str):
  438. table_name = table_name.decode(dialect.encoding)
  439. found_table = False
  440. cols_by_orig_name = {}
  441. for col_d in self.get_columns(
  442. table_name, schema, **table.dialect_kwargs):
  443. found_table = True
  444. self._reflect_column(
  445. table, col_d, include_columns,
  446. exclude_columns, cols_by_orig_name)
  447. if not found_table:
  448. raise exc.NoSuchTableError(table.name)
  449. self._reflect_pk(
  450. table_name, schema, table, cols_by_orig_name, exclude_columns)
  451. self._reflect_fk(
  452. table_name, schema, table, cols_by_orig_name,
  453. exclude_columns, _extend_on, reflection_options)
  454. self._reflect_indexes(
  455. table_name, schema, table, cols_by_orig_name,
  456. include_columns, exclude_columns, reflection_options)
  457. self._reflect_unique_constraints(
  458. table_name, schema, table, cols_by_orig_name,
  459. include_columns, exclude_columns, reflection_options)
  460. self._reflect_check_constraints(
  461. table_name, schema, table, cols_by_orig_name,
  462. include_columns, exclude_columns, reflection_options)
  463. def _reflect_column(
  464. self, table, col_d, include_columns,
  465. exclude_columns, cols_by_orig_name):
  466. orig_name = col_d['name']
  467. table.dispatch.column_reflect(self, table, col_d)
  468. # fetch name again as column_reflect is allowed to
  469. # change it
  470. name = col_d['name']
  471. if (include_columns and name not in include_columns) \
  472. or (exclude_columns and name in exclude_columns):
  473. return
  474. coltype = col_d['type']
  475. col_kw = dict(
  476. (k, col_d[k])
  477. for k in ['nullable', 'autoincrement', 'quote', 'info', 'key']
  478. if k in col_d
  479. )
  480. colargs = []
  481. if col_d.get('default') is not None:
  482. default = col_d['default']
  483. if isinstance(default, sql.elements.TextClause):
  484. default = sa_schema.DefaultClause(default, _reflected=True)
  485. elif not isinstance(default, sa_schema.FetchedValue):
  486. default = sa_schema.DefaultClause(
  487. sql.text(col_d['default']), _reflected=True)
  488. colargs.append(default)
  489. if 'sequence' in col_d:
  490. self._reflect_col_sequence(col_d, colargs)
  491. cols_by_orig_name[orig_name] = col = \
  492. sa_schema.Column(name, coltype, *colargs, **col_kw)
  493. if col.key in table.primary_key:
  494. col.primary_key = True
  495. table.append_column(col)
  496. def _reflect_col_sequence(self, col_d, colargs):
  497. if 'sequence' in col_d:
  498. # TODO: mssql and sybase are using this.
  499. seq = col_d['sequence']
  500. sequence = sa_schema.Sequence(seq['name'], 1, 1)
  501. if 'start' in seq:
  502. sequence.start = seq['start']
  503. if 'increment' in seq:
  504. sequence.increment = seq['increment']
  505. colargs.append(sequence)
  506. def _reflect_pk(
  507. self, table_name, schema, table,
  508. cols_by_orig_name, exclude_columns):
  509. pk_cons = self.get_pk_constraint(
  510. table_name, schema, **table.dialect_kwargs)
  511. if pk_cons:
  512. pk_cols = [
  513. cols_by_orig_name[pk]
  514. for pk in pk_cons['constrained_columns']
  515. if pk in cols_by_orig_name and pk not in exclude_columns
  516. ]
  517. # update pk constraint name
  518. table.primary_key.name = pk_cons.get('name')
  519. # tell the PKConstraint to re-initialize
  520. # its column collection
  521. table.primary_key._reload(pk_cols)
  522. def _reflect_fk(
  523. self, table_name, schema, table, cols_by_orig_name,
  524. exclude_columns, _extend_on, reflection_options):
  525. fkeys = self.get_foreign_keys(
  526. table_name, schema, **table.dialect_kwargs)
  527. for fkey_d in fkeys:
  528. conname = fkey_d['name']
  529. # look for columns by orig name in cols_by_orig_name,
  530. # but support columns that are in-Python only as fallback
  531. constrained_columns = [
  532. cols_by_orig_name[c].key
  533. if c in cols_by_orig_name else c
  534. for c in fkey_d['constrained_columns']
  535. ]
  536. if exclude_columns and set(constrained_columns).intersection(
  537. exclude_columns):
  538. continue
  539. referred_schema = fkey_d['referred_schema']
  540. referred_table = fkey_d['referred_table']
  541. referred_columns = fkey_d['referred_columns']
  542. refspec = []
  543. if referred_schema is not None:
  544. sa_schema.Table(referred_table, table.metadata,
  545. autoload=True, schema=referred_schema,
  546. autoload_with=self.bind,
  547. _extend_on=_extend_on,
  548. **reflection_options
  549. )
  550. for column in referred_columns:
  551. refspec.append(".".join(
  552. [referred_schema, referred_table, column]))
  553. else:
  554. sa_schema.Table(referred_table, table.metadata, autoload=True,
  555. autoload_with=self.bind,
  556. schema=sa_schema.BLANK_SCHEMA,
  557. _extend_on=_extend_on,
  558. **reflection_options
  559. )
  560. for column in referred_columns:
  561. refspec.append(".".join([referred_table, column]))
  562. if 'options' in fkey_d:
  563. options = fkey_d['options']
  564. else:
  565. options = {}
  566. table.append_constraint(
  567. sa_schema.ForeignKeyConstraint(constrained_columns, refspec,
  568. conname, link_to_name=True,
  569. **options))
  570. def _reflect_indexes(
  571. self, table_name, schema, table, cols_by_orig_name,
  572. include_columns, exclude_columns, reflection_options):
  573. # Indexes
  574. indexes = self.get_indexes(table_name, schema)
  575. for index_d in indexes:
  576. name = index_d['name']
  577. columns = index_d['column_names']
  578. unique = index_d['unique']
  579. flavor = index_d.get('type', 'index')
  580. dialect_options = index_d.get('dialect_options', {})
  581. duplicates = index_d.get('duplicates_constraint')
  582. if include_columns and \
  583. not set(columns).issubset(include_columns):
  584. util.warn(
  585. "Omitting %s key for (%s), key covers omitted columns." %
  586. (flavor, ', '.join(columns)))
  587. continue
  588. if duplicates:
  589. continue
  590. # look for columns by orig name in cols_by_orig_name,
  591. # but support columns that are in-Python only as fallback
  592. idx_cols = []
  593. for c in columns:
  594. try:
  595. idx_col = cols_by_orig_name[c] \
  596. if c in cols_by_orig_name else table.c[c]
  597. except KeyError:
  598. util.warn(
  599. "%s key '%s' was not located in "
  600. "columns for table '%s'" % (
  601. flavor, c, table_name
  602. ))
  603. else:
  604. idx_cols.append(idx_col)
  605. sa_schema.Index(
  606. name, *idx_cols,
  607. **dict(list(dialect_options.items()) + [('unique', unique)])
  608. )
  609. def _reflect_unique_constraints(
  610. self, table_name, schema, table, cols_by_orig_name,
  611. include_columns, exclude_columns, reflection_options):
  612. # Unique Constraints
  613. try:
  614. constraints = self.get_unique_constraints(table_name, schema)
  615. except NotImplementedError:
  616. # optional dialect feature
  617. return
  618. for const_d in constraints:
  619. conname = const_d['name']
  620. columns = const_d['column_names']
  621. duplicates = const_d.get('duplicates_index')
  622. if include_columns and \
  623. not set(columns).issubset(include_columns):
  624. util.warn(
  625. "Omitting unique constraint key for (%s), "
  626. "key covers omitted columns." %
  627. ', '.join(columns))
  628. continue
  629. if duplicates:
  630. continue
  631. # look for columns by orig name in cols_by_orig_name,
  632. # but support columns that are in-Python only as fallback
  633. constrained_cols = []
  634. for c in columns:
  635. try:
  636. constrained_col = cols_by_orig_name[c] \
  637. if c in cols_by_orig_name else table.c[c]
  638. except KeyError:
  639. util.warn(
  640. "unique constraint key '%s' was not located in "
  641. "columns for table '%s'" % (c, table_name))
  642. else:
  643. constrained_cols.append(constrained_col)
  644. table.append_constraint(
  645. sa_schema.UniqueConstraint(*constrained_cols, name=conname))
  646. def _reflect_check_constraints(
  647. self, table_name, schema, table, cols_by_orig_name,
  648. include_columns, exclude_columns, reflection_options):
  649. try:
  650. constraints = self.get_check_constraints(table_name, schema)
  651. except NotImplementedError:
  652. # optional dialect feature
  653. return
  654. for const_d in constraints:
  655. table.append_constraint(
  656. sa_schema.CheckConstraint(**const_d))