PageRenderTime 76ms CodeModel.GetById 38ms RepoModel.GetById 0ms app.codeStats 0ms

/web/installer/python/Lib/site-packages/sqlalchemy-0.5.8-py2.6.egg/sqlalchemy/engine/default.py

https://github.com/dpodhola/wwscc
Python | 375 lines | 212 code | 38 blank | 125 comment | 37 complexity | 007a9739f78c1fe35a4ea40f8c6d78d3 MD5 | raw file
  1. # engine/default.py
  2. # Copyright (C) 2005, 2006, 2007, 2008, 2009 Michael Bayer mike_mp@zzzcomputing.com
  3. #
  4. # This module is part of SQLAlchemy and is released under
  5. # the MIT License: http://www.opensource.org/licenses/mit-license.php
  6. """Default implementations of per-dialect sqlalchemy.engine classes.
  7. These are semi-private implementation classes which are only of importance
  8. to database dialect authors; dialects will usually use the classes here
  9. as the base class for their own corresponding classes.
  10. """
  11. import re, random
  12. from sqlalchemy.engine import base
  13. from sqlalchemy.sql import compiler, expression
  14. from sqlalchemy import exc
  15. AUTOCOMMIT_REGEXP = re.compile(r'\s*(?:UPDATE|INSERT|CREATE|DELETE|DROP|ALTER)',
  16. re.I | re.UNICODE)
  17. class DefaultDialect(base.Dialect):
  18. """Default implementation of Dialect"""
  19. name = 'default'
  20. schemagenerator = compiler.SchemaGenerator
  21. schemadropper = compiler.SchemaDropper
  22. statement_compiler = compiler.DefaultCompiler
  23. preparer = compiler.IdentifierPreparer
  24. defaultrunner = base.DefaultRunner
  25. supports_alter = True
  26. supports_unicode_statements = False
  27. max_identifier_length = 9999
  28. supports_sane_rowcount = True
  29. supports_sane_multi_rowcount = True
  30. preexecute_pk_sequences = False
  31. supports_pk_autoincrement = True
  32. dbapi_type_map = {}
  33. default_paramstyle = 'named'
  34. supports_default_values = False
  35. supports_empty_insert = True
  36. def __init__(self, convert_unicode=False, assert_unicode=False,
  37. encoding='utf-8', paramstyle=None, dbapi=None,
  38. label_length=None, **kwargs):
  39. self.convert_unicode = convert_unicode
  40. self.assert_unicode = assert_unicode
  41. self.encoding = encoding
  42. self.positional = False
  43. self._ischema = None
  44. self.dbapi = dbapi
  45. if paramstyle is not None:
  46. self.paramstyle = paramstyle
  47. elif self.dbapi is not None:
  48. self.paramstyle = self.dbapi.paramstyle
  49. else:
  50. self.paramstyle = self.default_paramstyle
  51. self.positional = self.paramstyle in ('qmark', 'format', 'numeric')
  52. self.identifier_preparer = self.preparer(self)
  53. if label_length and label_length > self.max_identifier_length:
  54. raise exc.ArgumentError("Label length of %d is greater than this dialect's maximum identifier length of %d" % (label_length, self.max_identifier_length))
  55. self.label_length = label_length
  56. self.description_encoding = getattr(self, 'description_encoding', encoding)
  57. def type_descriptor(self, typeobj):
  58. """Provide a database-specific ``TypeEngine`` object, given
  59. the generic object which comes from the types module.
  60. Subclasses will usually use the ``adapt_type()`` method in the
  61. types module to make this job easy."""
  62. if type(typeobj) is type:
  63. typeobj = typeobj()
  64. return typeobj
  65. def validate_identifier(self, ident):
  66. if len(ident) > self.max_identifier_length:
  67. raise exc.IdentifierError("Identifier '%s' exceeds maximum length of %d characters" % (ident, self.max_identifier_length))
  68. def do_begin(self, connection):
  69. """Implementations might want to put logic here for turning
  70. autocommit on/off, etc.
  71. """
  72. pass
  73. def do_rollback(self, connection):
  74. """Implementations might want to put logic here for turning
  75. autocommit on/off, etc.
  76. """
  77. connection.rollback()
  78. def do_commit(self, connection):
  79. """Implementations might want to put logic here for turning
  80. autocommit on/off, etc.
  81. """
  82. connection.commit()
  83. def create_xid(self):
  84. """Create a random two-phase transaction ID.
  85. This id will be passed to do_begin_twophase(), do_rollback_twophase(),
  86. do_commit_twophase(). Its format is unspecified."""
  87. return "_sa_%032x" % random.randint(0, 2 ** 128)
  88. def do_savepoint(self, connection, name):
  89. connection.execute(expression.SavepointClause(name))
  90. def do_rollback_to_savepoint(self, connection, name):
  91. connection.execute(expression.RollbackToSavepointClause(name))
  92. def do_release_savepoint(self, connection, name):
  93. connection.execute(expression.ReleaseSavepointClause(name))
  94. def do_executemany(self, cursor, statement, parameters, context=None):
  95. cursor.executemany(statement, parameters)
  96. def do_execute(self, cursor, statement, parameters, context=None):
  97. cursor.execute(statement, parameters)
  98. def is_disconnect(self, e):
  99. return False
  100. class DefaultExecutionContext(base.ExecutionContext):
  101. def __init__(self, dialect, connection, compiled=None, statement=None, parameters=None):
  102. self.dialect = dialect
  103. self._connection = self.root_connection = connection
  104. self.compiled = compiled
  105. self.engine = connection.engine
  106. if compiled is not None:
  107. # compiled clauseelement. process bind params, process table defaults,
  108. # track collections used by ResultProxy to target and process results
  109. if not compiled.can_execute:
  110. raise exc.ArgumentError("Not an executable clause: %s" % compiled)
  111. self.processors = dict(
  112. (key, value) for key, value in
  113. ( (compiled.bind_names[bindparam],
  114. bindparam.bind_processor(self.dialect))
  115. for bindparam in compiled.bind_names )
  116. if value is not None)
  117. self.result_map = compiled.result_map
  118. if not dialect.supports_unicode_statements:
  119. self.statement = unicode(compiled).encode(self.dialect.encoding)
  120. else:
  121. self.statement = unicode(compiled)
  122. self.isinsert = compiled.isinsert
  123. self.isupdate = compiled.isupdate
  124. self.should_autocommit = compiled.statement._autocommit
  125. if isinstance(compiled.statement, expression._TextClause):
  126. self.should_autocommit = self.should_autocommit or self.should_autocommit_text(self.statement)
  127. if not parameters:
  128. self.compiled_parameters = [compiled.construct_params()]
  129. self.executemany = False
  130. else:
  131. self.compiled_parameters = [compiled.construct_params(m) for m in parameters]
  132. self.executemany = len(parameters) > 1
  133. self.cursor = self.create_cursor()
  134. if self.isinsert or self.isupdate:
  135. self.__process_defaults()
  136. self.parameters = self.__convert_compiled_params(self.compiled_parameters)
  137. elif statement is not None:
  138. # plain text statement.
  139. self.result_map = None
  140. self.parameters = self.__encode_param_keys(parameters)
  141. self.executemany = len(parameters) > 1
  142. if isinstance(statement, unicode) and not dialect.supports_unicode_statements:
  143. self.statement = statement.encode(self.dialect.encoding)
  144. else:
  145. self.statement = statement
  146. self.isinsert = self.isupdate = False
  147. self.cursor = self.create_cursor()
  148. self.should_autocommit = self.should_autocommit_text(statement)
  149. else:
  150. # no statement. used for standalone ColumnDefault execution.
  151. self.statement = None
  152. self.isinsert = self.isupdate = self.executemany = self.should_autocommit = False
  153. self.cursor = self.create_cursor()
  154. @property
  155. def connection(self):
  156. return self._connection._branch()
  157. def __encode_param_keys(self, params):
  158. """apply string encoding to the keys of dictionary-based bind parameters.
  159. This is only used executing textual, non-compiled SQL expressions."""
  160. if self.dialect.positional or self.dialect.supports_unicode_statements:
  161. if params:
  162. return params
  163. elif self.dialect.positional:
  164. return [()]
  165. else:
  166. return [{}]
  167. else:
  168. def proc(d):
  169. # sigh, sometimes we get positional arguments with a dialect
  170. # that doesnt specify positional (because of execute_text())
  171. if not isinstance(d, dict):
  172. return d
  173. return dict((k.encode(self.dialect.encoding), d[k]) for k in d)
  174. return [proc(d) for d in params] or [{}]
  175. def __convert_compiled_params(self, compiled_parameters):
  176. """convert the dictionary of bind parameter values into a dict or list
  177. to be sent to the DBAPI's execute() or executemany() method.
  178. """
  179. processors = self.processors
  180. parameters = []
  181. if self.dialect.positional:
  182. for compiled_params in compiled_parameters:
  183. param = []
  184. for key in self.compiled.positiontup:
  185. if key in processors:
  186. param.append(processors[key](compiled_params[key]))
  187. else:
  188. param.append(compiled_params[key])
  189. parameters.append(param)
  190. else:
  191. encode = not self.dialect.supports_unicode_statements
  192. for compiled_params in compiled_parameters:
  193. param = {}
  194. if encode:
  195. encoding = self.dialect.encoding
  196. for key in compiled_params:
  197. if key in processors:
  198. param[key.encode(encoding)] = processors[key](compiled_params[key])
  199. else:
  200. param[key.encode(encoding)] = compiled_params[key]
  201. else:
  202. for key in compiled_params:
  203. if key in processors:
  204. param[key] = processors[key](compiled_params[key])
  205. else:
  206. param[key] = compiled_params[key]
  207. parameters.append(param)
  208. return parameters
  209. def should_autocommit_text(self, statement):
  210. return AUTOCOMMIT_REGEXP.match(statement)
  211. def create_cursor(self):
  212. return self._connection.connection.cursor()
  213. def pre_exec(self):
  214. pass
  215. def post_exec(self):
  216. pass
  217. def handle_dbapi_exception(self, e):
  218. pass
  219. def get_result_proxy(self):
  220. return base.ResultProxy(self)
  221. def get_rowcount(self):
  222. if hasattr(self, '_rowcount'):
  223. return self._rowcount
  224. else:
  225. return self.cursor.rowcount
  226. def supports_sane_rowcount(self):
  227. return self.dialect.supports_sane_rowcount
  228. def supports_sane_multi_rowcount(self):
  229. return self.dialect.supports_sane_multi_rowcount
  230. def last_inserted_ids(self):
  231. return self._last_inserted_ids
  232. def last_inserted_params(self):
  233. return self._last_inserted_params
  234. def last_updated_params(self):
  235. return self._last_updated_params
  236. def lastrow_has_defaults(self):
  237. return hasattr(self, 'postfetch_cols') and len(self.postfetch_cols)
  238. def set_input_sizes(self):
  239. """Given a cursor and ClauseParameters, call the appropriate
  240. style of ``setinputsizes()`` on the cursor, using DB-API types
  241. from the bind parameter's ``TypeEngine`` objects.
  242. """
  243. types = dict(
  244. (self.compiled.bind_names[bindparam], bindparam.type)
  245. for bindparam in self.compiled.bind_names)
  246. if self.dialect.positional:
  247. inputsizes = []
  248. for key in self.compiled.positiontup:
  249. typeengine = types[key]
  250. dbtype = typeengine.dialect_impl(self.dialect).get_dbapi_type(self.dialect.dbapi)
  251. if dbtype is not None:
  252. inputsizes.append(dbtype)
  253. try:
  254. self.cursor.setinputsizes(*inputsizes)
  255. except Exception, e:
  256. self._connection._handle_dbapi_exception(e, None, None, None, self)
  257. raise
  258. else:
  259. inputsizes = {}
  260. for key in self.compiled.bind_names.values():
  261. typeengine = types[key]
  262. dbtype = typeengine.dialect_impl(self.dialect).get_dbapi_type(self.dialect.dbapi)
  263. if dbtype is not None:
  264. inputsizes[key.encode(self.dialect.encoding)] = dbtype
  265. try:
  266. self.cursor.setinputsizes(**inputsizes)
  267. except Exception, e:
  268. self._connection._handle_dbapi_exception(e, None, None, None, self)
  269. raise
  270. def __process_defaults(self):
  271. """generate default values for compiled insert/update statements,
  272. and generate last_inserted_ids() collection."""
  273. if self.executemany:
  274. if len(self.compiled.prefetch):
  275. drunner = self.dialect.defaultrunner(self)
  276. params = self.compiled_parameters
  277. for param in params:
  278. # assign each dict of params to self.compiled_parameters;
  279. # this allows user-defined default generators to access the full
  280. # set of bind params for the row
  281. self.compiled_parameters = param
  282. for c in self.compiled.prefetch:
  283. if self.isinsert:
  284. val = drunner.get_column_default(c)
  285. else:
  286. val = drunner.get_column_onupdate(c)
  287. if val is not None:
  288. param[c.key] = val
  289. self.compiled_parameters = params
  290. else:
  291. compiled_parameters = self.compiled_parameters[0]
  292. drunner = self.dialect.defaultrunner(self)
  293. for c in self.compiled.prefetch:
  294. if self.isinsert:
  295. val = drunner.get_column_default(c)
  296. else:
  297. val = drunner.get_column_onupdate(c)
  298. if val is not None:
  299. compiled_parameters[c.key] = val
  300. if self.isinsert:
  301. self._last_inserted_ids = [compiled_parameters.get(c.key, None) for c in self.compiled.statement.table.primary_key]
  302. self._last_inserted_params = compiled_parameters
  303. else:
  304. self._last_updated_params = compiled_parameters
  305. self.postfetch_cols = self.compiled.postfetch
  306. self.prefetch_cols = self.compiled.prefetch
  307. DefaultDialect.execution_ctx_cls = DefaultExecutionContext