base.py 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821
  1. # sybase/base.py
  2. # Copyright (C) 2010-2017 the SQLAlchemy authors and contributors
  3. # <see AUTHORS file>
  4. # get_select_precolumns(), limit_clause() implementation
  5. # copyright (C) 2007 Fisch Asset Management
  6. # AG http://www.fam.ch, with coding by Alexander Houben
  7. # alexander.houben@thor-solutions.ch
  8. #
  9. # This module is part of SQLAlchemy and is released under
  10. # the MIT License: http://www.opensource.org/licenses/mit-license.php
  11. """
  12. .. dialect:: sybase
  13. :name: Sybase
  14. .. note::
  15. The Sybase dialect functions on current SQLAlchemy versions
  16. but is not regularly tested, and may have many issues and
  17. caveats not currently handled.
  18. """
  19. import operator
  20. import re
  21. from sqlalchemy.sql import compiler, expression, text, bindparam
  22. from sqlalchemy.engine import default, base, reflection
  23. from sqlalchemy import types as sqltypes
  24. from sqlalchemy.sql import operators as sql_operators
  25. from sqlalchemy import schema as sa_schema
  26. from sqlalchemy import util, sql, exc
  27. from sqlalchemy.types import CHAR, VARCHAR, TIME, NCHAR, NVARCHAR,\
  28. TEXT, DATE, DATETIME, FLOAT, NUMERIC,\
  29. BIGINT, INT, INTEGER, SMALLINT, BINARY,\
  30. VARBINARY, DECIMAL, TIMESTAMP, Unicode,\
  31. UnicodeText, REAL
  32. RESERVED_WORDS = set([
  33. "add", "all", "alter", "and",
  34. "any", "as", "asc", "backup",
  35. "begin", "between", "bigint", "binary",
  36. "bit", "bottom", "break", "by",
  37. "call", "capability", "cascade", "case",
  38. "cast", "char", "char_convert", "character",
  39. "check", "checkpoint", "close", "comment",
  40. "commit", "connect", "constraint", "contains",
  41. "continue", "convert", "create", "cross",
  42. "cube", "current", "current_timestamp", "current_user",
  43. "cursor", "date", "dbspace", "deallocate",
  44. "dec", "decimal", "declare", "default",
  45. "delete", "deleting", "desc", "distinct",
  46. "do", "double", "drop", "dynamic",
  47. "else", "elseif", "encrypted", "end",
  48. "endif", "escape", "except", "exception",
  49. "exec", "execute", "existing", "exists",
  50. "externlogin", "fetch", "first", "float",
  51. "for", "force", "foreign", "forward",
  52. "from", "full", "goto", "grant",
  53. "group", "having", "holdlock", "identified",
  54. "if", "in", "index", "index_lparen",
  55. "inner", "inout", "insensitive", "insert",
  56. "inserting", "install", "instead", "int",
  57. "integer", "integrated", "intersect", "into",
  58. "iq", "is", "isolation", "join",
  59. "key", "lateral", "left", "like",
  60. "lock", "login", "long", "match",
  61. "membership", "message", "mode", "modify",
  62. "natural", "new", "no", "noholdlock",
  63. "not", "notify", "null", "numeric",
  64. "of", "off", "on", "open",
  65. "option", "options", "or", "order",
  66. "others", "out", "outer", "over",
  67. "passthrough", "precision", "prepare", "primary",
  68. "print", "privileges", "proc", "procedure",
  69. "publication", "raiserror", "readtext", "real",
  70. "reference", "references", "release", "remote",
  71. "remove", "rename", "reorganize", "resource",
  72. "restore", "restrict", "return", "revoke",
  73. "right", "rollback", "rollup", "save",
  74. "savepoint", "scroll", "select", "sensitive",
  75. "session", "set", "setuser", "share",
  76. "smallint", "some", "sqlcode", "sqlstate",
  77. "start", "stop", "subtrans", "subtransaction",
  78. "synchronize", "syntax_error", "table", "temporary",
  79. "then", "time", "timestamp", "tinyint",
  80. "to", "top", "tran", "trigger",
  81. "truncate", "tsequal", "unbounded", "union",
  82. "unique", "unknown", "unsigned", "update",
  83. "updating", "user", "using", "validate",
  84. "values", "varbinary", "varchar", "variable",
  85. "varying", "view", "wait", "waitfor",
  86. "when", "where", "while", "window",
  87. "with", "with_cube", "with_lparen", "with_rollup",
  88. "within", "work", "writetext",
  89. ])
  90. class _SybaseUnitypeMixin(object):
  91. """these types appear to return a buffer object."""
  92. def result_processor(self, dialect, coltype):
  93. def process(value):
  94. if value is not None:
  95. return str(value) # decode("ucs-2")
  96. else:
  97. return None
  98. return process
  99. class UNICHAR(_SybaseUnitypeMixin, sqltypes.Unicode):
  100. __visit_name__ = 'UNICHAR'
  101. class UNIVARCHAR(_SybaseUnitypeMixin, sqltypes.Unicode):
  102. __visit_name__ = 'UNIVARCHAR'
  103. class UNITEXT(_SybaseUnitypeMixin, sqltypes.UnicodeText):
  104. __visit_name__ = 'UNITEXT'
  105. class TINYINT(sqltypes.Integer):
  106. __visit_name__ = 'TINYINT'
  107. class BIT(sqltypes.TypeEngine):
  108. __visit_name__ = 'BIT'
  109. class MONEY(sqltypes.TypeEngine):
  110. __visit_name__ = "MONEY"
  111. class SMALLMONEY(sqltypes.TypeEngine):
  112. __visit_name__ = "SMALLMONEY"
  113. class UNIQUEIDENTIFIER(sqltypes.TypeEngine):
  114. __visit_name__ = "UNIQUEIDENTIFIER"
  115. class IMAGE(sqltypes.LargeBinary):
  116. __visit_name__ = 'IMAGE'
  117. class SybaseTypeCompiler(compiler.GenericTypeCompiler):
  118. def visit_large_binary(self, type_, **kw):
  119. return self.visit_IMAGE(type_)
  120. def visit_boolean(self, type_, **kw):
  121. return self.visit_BIT(type_)
  122. def visit_unicode(self, type_, **kw):
  123. return self.visit_NVARCHAR(type_)
  124. def visit_UNICHAR(self, type_, **kw):
  125. return "UNICHAR(%d)" % type_.length
  126. def visit_UNIVARCHAR(self, type_, **kw):
  127. return "UNIVARCHAR(%d)" % type_.length
  128. def visit_UNITEXT(self, type_, **kw):
  129. return "UNITEXT"
  130. def visit_TINYINT(self, type_, **kw):
  131. return "TINYINT"
  132. def visit_IMAGE(self, type_, **kw):
  133. return "IMAGE"
  134. def visit_BIT(self, type_, **kw):
  135. return "BIT"
  136. def visit_MONEY(self, type_, **kw):
  137. return "MONEY"
  138. def visit_SMALLMONEY(self, type_, **kw):
  139. return "SMALLMONEY"
  140. def visit_UNIQUEIDENTIFIER(self, type_, **kw):
  141. return "UNIQUEIDENTIFIER"
  142. ischema_names = {
  143. 'bigint': BIGINT,
  144. 'int': INTEGER,
  145. 'integer': INTEGER,
  146. 'smallint': SMALLINT,
  147. 'tinyint': TINYINT,
  148. 'unsigned bigint': BIGINT, # TODO: unsigned flags
  149. 'unsigned int': INTEGER, # TODO: unsigned flags
  150. 'unsigned smallint': SMALLINT, # TODO: unsigned flags
  151. 'numeric': NUMERIC,
  152. 'decimal': DECIMAL,
  153. 'dec': DECIMAL,
  154. 'float': FLOAT,
  155. 'double': NUMERIC, # TODO
  156. 'double precision': NUMERIC, # TODO
  157. 'real': REAL,
  158. 'smallmoney': SMALLMONEY,
  159. 'money': MONEY,
  160. 'smalldatetime': DATETIME,
  161. 'datetime': DATETIME,
  162. 'date': DATE,
  163. 'time': TIME,
  164. 'char': CHAR,
  165. 'character': CHAR,
  166. 'varchar': VARCHAR,
  167. 'character varying': VARCHAR,
  168. 'char varying': VARCHAR,
  169. 'unichar': UNICHAR,
  170. 'unicode character': UNIVARCHAR,
  171. 'nchar': NCHAR,
  172. 'national char': NCHAR,
  173. 'national character': NCHAR,
  174. 'nvarchar': NVARCHAR,
  175. 'nchar varying': NVARCHAR,
  176. 'national char varying': NVARCHAR,
  177. 'national character varying': NVARCHAR,
  178. 'text': TEXT,
  179. 'unitext': UNITEXT,
  180. 'binary': BINARY,
  181. 'varbinary': VARBINARY,
  182. 'image': IMAGE,
  183. 'bit': BIT,
  184. # not in documentation for ASE 15.7
  185. 'long varchar': TEXT, # TODO
  186. 'timestamp': TIMESTAMP,
  187. 'uniqueidentifier': UNIQUEIDENTIFIER,
  188. }
  189. class SybaseInspector(reflection.Inspector):
  190. def __init__(self, conn):
  191. reflection.Inspector.__init__(self, conn)
  192. def get_table_id(self, table_name, schema=None):
  193. """Return the table id from `table_name` and `schema`."""
  194. return self.dialect.get_table_id(self.bind, table_name, schema,
  195. info_cache=self.info_cache)
  196. class SybaseExecutionContext(default.DefaultExecutionContext):
  197. _enable_identity_insert = False
  198. def set_ddl_autocommit(self, connection, value):
  199. """Must be implemented by subclasses to accommodate DDL executions.
  200. "connection" is the raw unwrapped DBAPI connection. "value"
  201. is True or False. when True, the connection should be configured
  202. such that a DDL can take place subsequently. when False,
  203. a DDL has taken place and the connection should be resumed
  204. into non-autocommit mode.
  205. """
  206. raise NotImplementedError()
  207. def pre_exec(self):
  208. if self.isinsert:
  209. tbl = self.compiled.statement.table
  210. seq_column = tbl._autoincrement_column
  211. insert_has_sequence = seq_column is not None
  212. if insert_has_sequence:
  213. self._enable_identity_insert = \
  214. seq_column.key in self.compiled_parameters[0]
  215. else:
  216. self._enable_identity_insert = False
  217. if self._enable_identity_insert:
  218. self.cursor.execute(
  219. "SET IDENTITY_INSERT %s ON" %
  220. self.dialect.identifier_preparer.format_table(tbl))
  221. if self.isddl:
  222. # TODO: to enhance this, we can detect "ddl in tran" on the
  223. # database settings. this error message should be improved to
  224. # include a note about that.
  225. if not self.should_autocommit:
  226. raise exc.InvalidRequestError(
  227. "The Sybase dialect only supports "
  228. "DDL in 'autocommit' mode at this time.")
  229. self.root_connection.engine.logger.info(
  230. "AUTOCOMMIT (Assuming no Sybase 'ddl in tran')")
  231. self.set_ddl_autocommit(
  232. self.root_connection.connection.connection,
  233. True)
  234. def post_exec(self):
  235. if self.isddl:
  236. self.set_ddl_autocommit(self.root_connection, False)
  237. if self._enable_identity_insert:
  238. self.cursor.execute(
  239. "SET IDENTITY_INSERT %s OFF" %
  240. self.dialect.identifier_preparer.
  241. format_table(self.compiled.statement.table)
  242. )
  243. def get_lastrowid(self):
  244. cursor = self.create_cursor()
  245. cursor.execute("SELECT @@identity AS lastrowid")
  246. lastrowid = cursor.fetchone()[0]
  247. cursor.close()
  248. return lastrowid
  249. class SybaseSQLCompiler(compiler.SQLCompiler):
  250. ansi_bind_rules = True
  251. extract_map = util.update_copy(
  252. compiler.SQLCompiler.extract_map,
  253. {
  254. 'doy': 'dayofyear',
  255. 'dow': 'weekday',
  256. 'milliseconds': 'millisecond'
  257. })
  258. def get_select_precolumns(self, select, **kw):
  259. s = select._distinct and "DISTINCT " or ""
  260. # TODO: don't think Sybase supports
  261. # bind params for FIRST / TOP
  262. limit = select._limit
  263. if limit:
  264. # if select._limit == 1:
  265. # s += "FIRST "
  266. # else:
  267. # s += "TOP %s " % (select._limit,)
  268. s += "TOP %s " % (limit,)
  269. offset = select._offset
  270. if offset:
  271. raise NotImplementedError("Sybase ASE does not support OFFSET")
  272. return s
  273. def get_from_hint_text(self, table, text):
  274. return text
  275. def limit_clause(self, select, **kw):
  276. # Limit in sybase is after the select keyword
  277. return ""
  278. def visit_extract(self, extract, **kw):
  279. field = self.extract_map.get(extract.field, extract.field)
  280. return 'DATEPART("%s", %s)' % (
  281. field, self.process(extract.expr, **kw))
  282. def visit_now_func(self, fn, **kw):
  283. return "GETDATE()"
  284. def for_update_clause(self, select):
  285. # "FOR UPDATE" is only allowed on "DECLARE CURSOR"
  286. # which SQLAlchemy doesn't use
  287. return ''
  288. def order_by_clause(self, select, **kw):
  289. kw['literal_binds'] = True
  290. order_by = self.process(select._order_by_clause, **kw)
  291. # SybaseSQL only allows ORDER BY in subqueries if there is a LIMIT
  292. if order_by and (not self.is_subquery() or select._limit):
  293. return " ORDER BY " + order_by
  294. else:
  295. return ""
  296. class SybaseDDLCompiler(compiler.DDLCompiler):
  297. def get_column_specification(self, column, **kwargs):
  298. colspec = self.preparer.format_column(column) + " " + \
  299. self.dialect.type_compiler.process(
  300. column.type, type_expression=column)
  301. if column.table is None:
  302. raise exc.CompileError(
  303. "The Sybase dialect requires Table-bound "
  304. "columns in order to generate DDL")
  305. seq_col = column.table._autoincrement_column
  306. # install a IDENTITY Sequence if we have an implicit IDENTITY column
  307. if seq_col is column:
  308. sequence = isinstance(column.default, sa_schema.Sequence) \
  309. and column.default
  310. if sequence:
  311. start, increment = sequence.start or 1, \
  312. sequence.increment or 1
  313. else:
  314. start, increment = 1, 1
  315. if (start, increment) == (1, 1):
  316. colspec += " IDENTITY"
  317. else:
  318. # TODO: need correct syntax for this
  319. colspec += " IDENTITY(%s,%s)" % (start, increment)
  320. else:
  321. default = self.get_column_default_string(column)
  322. if default is not None:
  323. colspec += " DEFAULT " + default
  324. if column.nullable is not None:
  325. if not column.nullable or column.primary_key:
  326. colspec += " NOT NULL"
  327. else:
  328. colspec += " NULL"
  329. return colspec
  330. def visit_drop_index(self, drop):
  331. index = drop.element
  332. return "\nDROP INDEX %s.%s" % (
  333. self.preparer.quote_identifier(index.table.name),
  334. self._prepared_index_name(drop.element,
  335. include_schema=False)
  336. )
  337. class SybaseIdentifierPreparer(compiler.IdentifierPreparer):
  338. reserved_words = RESERVED_WORDS
  339. class SybaseDialect(default.DefaultDialect):
  340. name = 'sybase'
  341. supports_unicode_statements = False
  342. supports_sane_rowcount = False
  343. supports_sane_multi_rowcount = False
  344. supports_native_boolean = False
  345. supports_unicode_binds = False
  346. postfetch_lastrowid = True
  347. colspecs = {}
  348. ischema_names = ischema_names
  349. type_compiler = SybaseTypeCompiler
  350. statement_compiler = SybaseSQLCompiler
  351. ddl_compiler = SybaseDDLCompiler
  352. preparer = SybaseIdentifierPreparer
  353. inspector = SybaseInspector
  354. construct_arguments = []
  355. def _get_default_schema_name(self, connection):
  356. return connection.scalar(
  357. text("SELECT user_name() as user_name",
  358. typemap={'user_name': Unicode})
  359. )
  360. def initialize(self, connection):
  361. super(SybaseDialect, self).initialize(connection)
  362. if self.server_version_info is not None and\
  363. self.server_version_info < (15, ):
  364. self.max_identifier_length = 30
  365. else:
  366. self.max_identifier_length = 255
  367. def get_table_id(self, connection, table_name, schema=None, **kw):
  368. """Fetch the id for schema.table_name.
  369. Several reflection methods require the table id. The idea for using
  370. this method is that it can be fetched one time and cached for
  371. subsequent calls.
  372. """
  373. table_id = None
  374. if schema is None:
  375. schema = self.default_schema_name
  376. TABLEID_SQL = text("""
  377. SELECT o.id AS id
  378. FROM sysobjects o JOIN sysusers u ON o.uid=u.uid
  379. WHERE u.name = :schema_name
  380. AND o.name = :table_name
  381. AND o.type in ('U', 'V')
  382. """)
  383. if util.py2k:
  384. if isinstance(schema, unicode):
  385. schema = schema.encode("ascii")
  386. if isinstance(table_name, unicode):
  387. table_name = table_name.encode("ascii")
  388. result = connection.execute(TABLEID_SQL,
  389. schema_name=schema,
  390. table_name=table_name)
  391. table_id = result.scalar()
  392. if table_id is None:
  393. raise exc.NoSuchTableError(table_name)
  394. return table_id
  395. @reflection.cache
  396. def get_columns(self, connection, table_name, schema=None, **kw):
  397. table_id = self.get_table_id(connection, table_name, schema,
  398. info_cache=kw.get("info_cache"))
  399. COLUMN_SQL = text("""
  400. SELECT col.name AS name,
  401. t.name AS type,
  402. (col.status & 8) AS nullable,
  403. (col.status & 128) AS autoincrement,
  404. com.text AS 'default',
  405. col.prec AS precision,
  406. col.scale AS scale,
  407. col.length AS length
  408. FROM systypes t, syscolumns col LEFT OUTER JOIN syscomments com ON
  409. col.cdefault = com.id
  410. WHERE col.usertype = t.usertype
  411. AND col.id = :table_id
  412. ORDER BY col.colid
  413. """)
  414. results = connection.execute(COLUMN_SQL, table_id=table_id)
  415. columns = []
  416. for (name, type_, nullable, autoincrement, default, precision, scale,
  417. length) in results:
  418. col_info = self._get_column_info(name, type_, bool(nullable),
  419. bool(autoincrement),
  420. default, precision, scale,
  421. length)
  422. columns.append(col_info)
  423. return columns
  424. def _get_column_info(self, name, type_, nullable, autoincrement, default,
  425. precision, scale, length):
  426. coltype = self.ischema_names.get(type_, None)
  427. kwargs = {}
  428. if coltype in (NUMERIC, DECIMAL):
  429. args = (precision, scale)
  430. elif coltype == FLOAT:
  431. args = (precision,)
  432. elif coltype in (CHAR, VARCHAR, UNICHAR, UNIVARCHAR, NCHAR, NVARCHAR):
  433. args = (length,)
  434. else:
  435. args = ()
  436. if coltype:
  437. coltype = coltype(*args, **kwargs)
  438. # is this necessary
  439. # if is_array:
  440. # coltype = ARRAY(coltype)
  441. else:
  442. util.warn("Did not recognize type '%s' of column '%s'" %
  443. (type_, name))
  444. coltype = sqltypes.NULLTYPE
  445. if default:
  446. default = default.replace("DEFAULT", "").strip()
  447. default = re.sub("^'(.*)'$", lambda m: m.group(1), default)
  448. else:
  449. default = None
  450. column_info = dict(name=name, type=coltype, nullable=nullable,
  451. default=default, autoincrement=autoincrement)
  452. return column_info
  453. @reflection.cache
  454. def get_foreign_keys(self, connection, table_name, schema=None, **kw):
  455. table_id = self.get_table_id(connection, table_name, schema,
  456. info_cache=kw.get("info_cache"))
  457. table_cache = {}
  458. column_cache = {}
  459. foreign_keys = []
  460. table_cache[table_id] = {"name": table_name, "schema": schema}
  461. COLUMN_SQL = text("""
  462. SELECT c.colid AS id, c.name AS name
  463. FROM syscolumns c
  464. WHERE c.id = :table_id
  465. """)
  466. results = connection.execute(COLUMN_SQL, table_id=table_id)
  467. columns = {}
  468. for col in results:
  469. columns[col["id"]] = col["name"]
  470. column_cache[table_id] = columns
  471. REFCONSTRAINT_SQL = text("""
  472. SELECT o.name AS name, r.reftabid AS reftable_id,
  473. r.keycnt AS 'count',
  474. r.fokey1 AS fokey1, r.fokey2 AS fokey2, r.fokey3 AS fokey3,
  475. r.fokey4 AS fokey4, r.fokey5 AS fokey5, r.fokey6 AS fokey6,
  476. r.fokey7 AS fokey7, r.fokey1 AS fokey8, r.fokey9 AS fokey9,
  477. r.fokey10 AS fokey10, r.fokey11 AS fokey11, r.fokey12 AS fokey12,
  478. r.fokey13 AS fokey13, r.fokey14 AS fokey14, r.fokey15 AS fokey15,
  479. r.fokey16 AS fokey16,
  480. r.refkey1 AS refkey1, r.refkey2 AS refkey2, r.refkey3 AS refkey3,
  481. r.refkey4 AS refkey4, r.refkey5 AS refkey5, r.refkey6 AS refkey6,
  482. r.refkey7 AS refkey7, r.refkey1 AS refkey8, r.refkey9 AS refkey9,
  483. r.refkey10 AS refkey10, r.refkey11 AS refkey11,
  484. r.refkey12 AS refkey12, r.refkey13 AS refkey13,
  485. r.refkey14 AS refkey14, r.refkey15 AS refkey15,
  486. r.refkey16 AS refkey16
  487. FROM sysreferences r JOIN sysobjects o on r.tableid = o.id
  488. WHERE r.tableid = :table_id
  489. """)
  490. referential_constraints = connection.execute(
  491. REFCONSTRAINT_SQL, table_id=table_id).fetchall()
  492. REFTABLE_SQL = text("""
  493. SELECT o.name AS name, u.name AS 'schema'
  494. FROM sysobjects o JOIN sysusers u ON o.uid = u.uid
  495. WHERE o.id = :table_id
  496. """)
  497. for r in referential_constraints:
  498. reftable_id = r["reftable_id"]
  499. if reftable_id not in table_cache:
  500. c = connection.execute(REFTABLE_SQL, table_id=reftable_id)
  501. reftable = c.fetchone()
  502. c.close()
  503. table_info = {"name": reftable["name"], "schema": None}
  504. if (schema is not None or
  505. reftable["schema"] != self.default_schema_name):
  506. table_info["schema"] = reftable["schema"]
  507. table_cache[reftable_id] = table_info
  508. results = connection.execute(COLUMN_SQL, table_id=reftable_id)
  509. reftable_columns = {}
  510. for col in results:
  511. reftable_columns[col["id"]] = col["name"]
  512. column_cache[reftable_id] = reftable_columns
  513. reftable = table_cache[reftable_id]
  514. reftable_columns = column_cache[reftable_id]
  515. constrained_columns = []
  516. referred_columns = []
  517. for i in range(1, r["count"] + 1):
  518. constrained_columns.append(columns[r["fokey%i" % i]])
  519. referred_columns.append(reftable_columns[r["refkey%i" % i]])
  520. fk_info = {
  521. "constrained_columns": constrained_columns,
  522. "referred_schema": reftable["schema"],
  523. "referred_table": reftable["name"],
  524. "referred_columns": referred_columns,
  525. "name": r["name"]
  526. }
  527. foreign_keys.append(fk_info)
  528. return foreign_keys
  529. @reflection.cache
  530. def get_indexes(self, connection, table_name, schema=None, **kw):
  531. table_id = self.get_table_id(connection, table_name, schema,
  532. info_cache=kw.get("info_cache"))
  533. INDEX_SQL = text("""
  534. SELECT object_name(i.id) AS table_name,
  535. i.keycnt AS 'count',
  536. i.name AS name,
  537. (i.status & 0x2) AS 'unique',
  538. index_col(object_name(i.id), i.indid, 1) AS col_1,
  539. index_col(object_name(i.id), i.indid, 2) AS col_2,
  540. index_col(object_name(i.id), i.indid, 3) AS col_3,
  541. index_col(object_name(i.id), i.indid, 4) AS col_4,
  542. index_col(object_name(i.id), i.indid, 5) AS col_5,
  543. index_col(object_name(i.id), i.indid, 6) AS col_6,
  544. index_col(object_name(i.id), i.indid, 7) AS col_7,
  545. index_col(object_name(i.id), i.indid, 8) AS col_8,
  546. index_col(object_name(i.id), i.indid, 9) AS col_9,
  547. index_col(object_name(i.id), i.indid, 10) AS col_10,
  548. index_col(object_name(i.id), i.indid, 11) AS col_11,
  549. index_col(object_name(i.id), i.indid, 12) AS col_12,
  550. index_col(object_name(i.id), i.indid, 13) AS col_13,
  551. index_col(object_name(i.id), i.indid, 14) AS col_14,
  552. index_col(object_name(i.id), i.indid, 15) AS col_15,
  553. index_col(object_name(i.id), i.indid, 16) AS col_16
  554. FROM sysindexes i, sysobjects o
  555. WHERE o.id = i.id
  556. AND o.id = :table_id
  557. AND (i.status & 2048) = 0
  558. AND i.indid BETWEEN 1 AND 254
  559. """)
  560. results = connection.execute(INDEX_SQL, table_id=table_id)
  561. indexes = []
  562. for r in results:
  563. column_names = []
  564. for i in range(1, r["count"]):
  565. column_names.append(r["col_%i" % (i,)])
  566. index_info = {"name": r["name"],
  567. "unique": bool(r["unique"]),
  568. "column_names": column_names}
  569. indexes.append(index_info)
  570. return indexes
  571. @reflection.cache
  572. def get_pk_constraint(self, connection, table_name, schema=None, **kw):
  573. table_id = self.get_table_id(connection, table_name, schema,
  574. info_cache=kw.get("info_cache"))
  575. PK_SQL = text("""
  576. SELECT object_name(i.id) AS table_name,
  577. i.keycnt AS 'count',
  578. i.name AS name,
  579. index_col(object_name(i.id), i.indid, 1) AS pk_1,
  580. index_col(object_name(i.id), i.indid, 2) AS pk_2,
  581. index_col(object_name(i.id), i.indid, 3) AS pk_3,
  582. index_col(object_name(i.id), i.indid, 4) AS pk_4,
  583. index_col(object_name(i.id), i.indid, 5) AS pk_5,
  584. index_col(object_name(i.id), i.indid, 6) AS pk_6,
  585. index_col(object_name(i.id), i.indid, 7) AS pk_7,
  586. index_col(object_name(i.id), i.indid, 8) AS pk_8,
  587. index_col(object_name(i.id), i.indid, 9) AS pk_9,
  588. index_col(object_name(i.id), i.indid, 10) AS pk_10,
  589. index_col(object_name(i.id), i.indid, 11) AS pk_11,
  590. index_col(object_name(i.id), i.indid, 12) AS pk_12,
  591. index_col(object_name(i.id), i.indid, 13) AS pk_13,
  592. index_col(object_name(i.id), i.indid, 14) AS pk_14,
  593. index_col(object_name(i.id), i.indid, 15) AS pk_15,
  594. index_col(object_name(i.id), i.indid, 16) AS pk_16
  595. FROM sysindexes i, sysobjects o
  596. WHERE o.id = i.id
  597. AND o.id = :table_id
  598. AND (i.status & 2048) = 2048
  599. AND i.indid BETWEEN 1 AND 254
  600. """)
  601. results = connection.execute(PK_SQL, table_id=table_id)
  602. pks = results.fetchone()
  603. results.close()
  604. constrained_columns = []
  605. if pks:
  606. for i in range(1, pks["count"] + 1):
  607. constrained_columns.append(pks["pk_%i" % (i,)])
  608. return {"constrained_columns": constrained_columns,
  609. "name": pks["name"]}
  610. else:
  611. return {"constrained_columns": [], "name": None}
  612. @reflection.cache
  613. def get_schema_names(self, connection, **kw):
  614. SCHEMA_SQL = text("SELECT u.name AS name FROM sysusers u")
  615. schemas = connection.execute(SCHEMA_SQL)
  616. return [s["name"] for s in schemas]
  617. @reflection.cache
  618. def get_table_names(self, connection, schema=None, **kw):
  619. if schema is None:
  620. schema = self.default_schema_name
  621. TABLE_SQL = text("""
  622. SELECT o.name AS name
  623. FROM sysobjects o JOIN sysusers u ON o.uid = u.uid
  624. WHERE u.name = :schema_name
  625. AND o.type = 'U'
  626. """)
  627. if util.py2k:
  628. if isinstance(schema, unicode):
  629. schema = schema.encode("ascii")
  630. tables = connection.execute(TABLE_SQL, schema_name=schema)
  631. return [t["name"] for t in tables]
  632. @reflection.cache
  633. def get_view_definition(self, connection, view_name, schema=None, **kw):
  634. if schema is None:
  635. schema = self.default_schema_name
  636. VIEW_DEF_SQL = text("""
  637. SELECT c.text
  638. FROM syscomments c JOIN sysobjects o ON c.id = o.id
  639. WHERE o.name = :view_name
  640. AND o.type = 'V'
  641. """)
  642. if util.py2k:
  643. if isinstance(view_name, unicode):
  644. view_name = view_name.encode("ascii")
  645. view = connection.execute(VIEW_DEF_SQL, view_name=view_name)
  646. return view.scalar()
  647. @reflection.cache
  648. def get_view_names(self, connection, schema=None, **kw):
  649. if schema is None:
  650. schema = self.default_schema_name
  651. VIEW_SQL = text("""
  652. SELECT o.name AS name
  653. FROM sysobjects o JOIN sysusers u ON o.uid = u.uid
  654. WHERE u.name = :schema_name
  655. AND o.type = 'V'
  656. """)
  657. if util.py2k:
  658. if isinstance(schema, unicode):
  659. schema = schema.encode("ascii")
  660. views = connection.execute(VIEW_SQL, schema_name=schema)
  661. return [v["name"] for v in views]
  662. def has_table(self, connection, table_name, schema=None):
  663. try:
  664. self.get_table_id(connection, table_name, schema)
  665. except exc.NoSuchTableError:
  666. return False
  667. else:
  668. return True