__init__.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434
  1. # engine/__init__.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. """SQL connections, SQL execution and high-level DB-API interface.
  8. The engine package defines the basic components used to interface
  9. DB-API modules with higher-level statement construction,
  10. connection-management, execution and result contexts. The primary
  11. "entry point" class into this package is the Engine and its public
  12. constructor ``create_engine()``.
  13. This package includes:
  14. base.py
  15. Defines interface classes and some implementation classes which
  16. comprise the basic components used to interface between a DB-API,
  17. constructed and plain-text statements, connections, transactions,
  18. and results.
  19. default.py
  20. Contains default implementations of some of the components defined
  21. in base.py. All current database dialects use the classes in
  22. default.py as base classes for their own database-specific
  23. implementations.
  24. strategies.py
  25. The mechanics of constructing ``Engine`` objects are represented
  26. here. Defines the ``EngineStrategy`` class which represents how
  27. to go from arguments specified to the ``create_engine()``
  28. function, to a fully constructed ``Engine``, including
  29. initialization of connection pooling, dialects, and specific
  30. subclasses of ``Engine``.
  31. threadlocal.py
  32. The ``TLEngine`` class is defined here, which is a subclass of
  33. the generic ``Engine`` and tracks ``Connection`` and
  34. ``Transaction`` objects against the identity of the current
  35. thread. This allows certain programming patterns based around
  36. the concept of a "thread-local connection" to be possible.
  37. The ``TLEngine`` is created by using the "threadlocal" engine
  38. strategy in conjunction with the ``create_engine()`` function.
  39. url.py
  40. Defines the ``URL`` class which represents the individual
  41. components of a string URL passed to ``create_engine()``. Also
  42. defines a basic module-loading strategy for the dialect specifier
  43. within a URL.
  44. """
  45. from .interfaces import (
  46. Connectable,
  47. CreateEnginePlugin,
  48. Dialect,
  49. ExecutionContext,
  50. ExceptionContext,
  51. # backwards compat
  52. Compiled,
  53. TypeCompiler
  54. )
  55. from .base import (
  56. Connection,
  57. Engine,
  58. NestedTransaction,
  59. RootTransaction,
  60. Transaction,
  61. TwoPhaseTransaction,
  62. )
  63. from .result import (
  64. BaseRowProxy,
  65. BufferedColumnResultProxy,
  66. BufferedColumnRow,
  67. BufferedRowResultProxy,
  68. FullyBufferedResultProxy,
  69. ResultProxy,
  70. RowProxy,
  71. )
  72. from .util import (
  73. connection_memoize
  74. )
  75. from . import util, strategies
  76. # backwards compat
  77. from ..sql import ddl
  78. default_strategy = 'plain'
  79. def create_engine(*args, **kwargs):
  80. """Create a new :class:`.Engine` instance.
  81. The standard calling form is to send the URL as the
  82. first positional argument, usually a string
  83. that indicates database dialect and connection arguments::
  84. engine = create_engine("postgresql://scott:tiger@localhost/test")
  85. Additional keyword arguments may then follow it which
  86. establish various options on the resulting :class:`.Engine`
  87. and its underlying :class:`.Dialect` and :class:`.Pool`
  88. constructs::
  89. engine = create_engine("mysql://scott:tiger@hostname/dbname",
  90. encoding='latin1', echo=True)
  91. The string form of the URL is
  92. ``dialect[+driver]://user:password@host/dbname[?key=value..]``, where
  93. ``dialect`` is a database name such as ``mysql``, ``oracle``,
  94. ``postgresql``, etc., and ``driver`` the name of a DBAPI, such as
  95. ``psycopg2``, ``pyodbc``, ``cx_oracle``, etc. Alternatively,
  96. the URL can be an instance of :class:`~sqlalchemy.engine.url.URL`.
  97. ``**kwargs`` takes a wide variety of options which are routed
  98. towards their appropriate components. Arguments may be specific to
  99. the :class:`.Engine`, the underlying :class:`.Dialect`, as well as the
  100. :class:`.Pool`. Specific dialects also accept keyword arguments that
  101. are unique to that dialect. Here, we describe the parameters
  102. that are common to most :func:`.create_engine()` usage.
  103. Once established, the newly resulting :class:`.Engine` will
  104. request a connection from the underlying :class:`.Pool` once
  105. :meth:`.Engine.connect` is called, or a method which depends on it
  106. such as :meth:`.Engine.execute` is invoked. The :class:`.Pool` in turn
  107. will establish the first actual DBAPI connection when this request
  108. is received. The :func:`.create_engine` call itself does **not**
  109. establish any actual DBAPI connections directly.
  110. .. seealso::
  111. :doc:`/core/engines`
  112. :doc:`/dialects/index`
  113. :ref:`connections_toplevel`
  114. :param case_sensitive=True: if False, result column names
  115. will match in a case-insensitive fashion, that is,
  116. ``row['SomeColumn']``.
  117. .. versionchanged:: 0.8
  118. By default, result row names match case-sensitively.
  119. In version 0.7 and prior, all matches were case-insensitive.
  120. :param connect_args: a dictionary of options which will be
  121. passed directly to the DBAPI's ``connect()`` method as
  122. additional keyword arguments. See the example
  123. at :ref:`custom_dbapi_args`.
  124. :param convert_unicode=False: if set to True, sets
  125. the default behavior of ``convert_unicode`` on the
  126. :class:`.String` type to ``True``, regardless
  127. of a setting of ``False`` on an individual
  128. :class:`.String` type, thus causing all :class:`.String`
  129. -based columns
  130. to accommodate Python ``unicode`` objects. This flag
  131. is useful as an engine-wide setting when using a
  132. DBAPI that does not natively support Python
  133. ``unicode`` objects and raises an error when
  134. one is received (such as pyodbc with FreeTDS).
  135. See :class:`.String` for further details on
  136. what this flag indicates.
  137. :param creator: a callable which returns a DBAPI connection.
  138. This creation function will be passed to the underlying
  139. connection pool and will be used to create all new database
  140. connections. Usage of this function causes connection
  141. parameters specified in the URL argument to be bypassed.
  142. :param echo=False: if True, the Engine will log all statements
  143. as well as a repr() of their parameter lists to the engines
  144. logger, which defaults to sys.stdout. The ``echo`` attribute of
  145. ``Engine`` can be modified at any time to turn logging on and
  146. off. If set to the string ``"debug"``, result rows will be
  147. printed to the standard output as well. This flag ultimately
  148. controls a Python logger; see :ref:`dbengine_logging` for
  149. information on how to configure logging directly.
  150. :param echo_pool=False: if True, the connection pool will log
  151. all checkouts/checkins to the logging stream, which defaults to
  152. sys.stdout. This flag ultimately controls a Python logger; see
  153. :ref:`dbengine_logging` for information on how to configure logging
  154. directly.
  155. :param encoding: Defaults to ``utf-8``. This is the string
  156. encoding used by SQLAlchemy for string encode/decode
  157. operations which occur within SQLAlchemy, **outside of
  158. the DBAPI.** Most modern DBAPIs feature some degree of
  159. direct support for Python ``unicode`` objects,
  160. what you see in Python 2 as a string of the form
  161. ``u'some string'``. For those scenarios where the
  162. DBAPI is detected as not supporting a Python ``unicode``
  163. object, this encoding is used to determine the
  164. source/destination encoding. It is **not used**
  165. for those cases where the DBAPI handles unicode
  166. directly.
  167. To properly configure a system to accommodate Python
  168. ``unicode`` objects, the DBAPI should be
  169. configured to handle unicode to the greatest
  170. degree as is appropriate - see
  171. the notes on unicode pertaining to the specific
  172. target database in use at :ref:`dialect_toplevel`.
  173. Areas where string encoding may need to be accommodated
  174. outside of the DBAPI include zero or more of:
  175. * the values passed to bound parameters, corresponding to
  176. the :class:`.Unicode` type or the :class:`.String` type
  177. when ``convert_unicode`` is ``True``;
  178. * the values returned in result set columns corresponding
  179. to the :class:`.Unicode` type or the :class:`.String`
  180. type when ``convert_unicode`` is ``True``;
  181. * the string SQL statement passed to the DBAPI's
  182. ``cursor.execute()`` method;
  183. * the string names of the keys in the bound parameter
  184. dictionary passed to the DBAPI's ``cursor.execute()``
  185. as well as ``cursor.setinputsizes()`` methods;
  186. * the string column names retrieved from the DBAPI's
  187. ``cursor.description`` attribute.
  188. When using Python 3, the DBAPI is required to support
  189. *all* of the above values as Python ``unicode`` objects,
  190. which in Python 3 are just known as ``str``. In Python 2,
  191. the DBAPI does not specify unicode behavior at all,
  192. so SQLAlchemy must make decisions for each of the above
  193. values on a per-DBAPI basis - implementations are
  194. completely inconsistent in their behavior.
  195. :param execution_options: Dictionary execution options which will
  196. be applied to all connections. See
  197. :meth:`~sqlalchemy.engine.Connection.execution_options`
  198. :param implicit_returning=True: When ``True``, a RETURNING-
  199. compatible construct, if available, will be used to
  200. fetch newly generated primary key values when a single row
  201. INSERT statement is emitted with no existing returning()
  202. clause. This applies to those backends which support RETURNING
  203. or a compatible construct, including PostgreSQL, Firebird, Oracle,
  204. Microsoft SQL Server. Set this to ``False`` to disable
  205. the automatic usage of RETURNING.
  206. :param isolation_level: this string parameter is interpreted by various
  207. dialects in order to affect the transaction isolation level of the
  208. database connection. The parameter essentially accepts some subset of
  209. these string arguments: ``"SERIALIZABLE"``, ``"REPEATABLE_READ"``,
  210. ``"READ_COMMITTED"``, ``"READ_UNCOMMITTED"`` and ``"AUTOCOMMIT"``.
  211. Behavior here varies per backend, and
  212. individual dialects should be consulted directly.
  213. Note that the isolation level can also be set on a per-:class:`.Connection`
  214. basis as well, using the
  215. :paramref:`.Connection.execution_options.isolation_level`
  216. feature.
  217. .. seealso::
  218. :attr:`.Connection.default_isolation_level` - view default level
  219. :paramref:`.Connection.execution_options.isolation_level`
  220. - set per :class:`.Connection` isolation level
  221. :ref:`SQLite Transaction Isolation <sqlite_isolation_level>`
  222. :ref:`PostgreSQL Transaction Isolation <postgresql_isolation_level>`
  223. :ref:`MySQL Transaction Isolation <mysql_isolation_level>`
  224. :ref:`session_transaction_isolation` - for the ORM
  225. :param label_length=None: optional integer value which limits
  226. the size of dynamically generated column labels to that many
  227. characters. If less than 6, labels are generated as
  228. "_(counter)". If ``None``, the value of
  229. ``dialect.max_identifier_length`` is used instead.
  230. :param listeners: A list of one or more
  231. :class:`~sqlalchemy.interfaces.PoolListener` objects which will
  232. receive connection pool events.
  233. :param logging_name: String identifier which will be used within
  234. the "name" field of logging records generated within the
  235. "sqlalchemy.engine" logger. Defaults to a hexstring of the
  236. object's id.
  237. :param max_overflow=10: the number of connections to allow in
  238. connection pool "overflow", that is connections that can be
  239. opened above and beyond the pool_size setting, which defaults
  240. to five. this is only used with :class:`~sqlalchemy.pool.QueuePool`.
  241. :param module=None: reference to a Python module object (the module
  242. itself, not its string name). Specifies an alternate DBAPI module to
  243. be used by the engine's dialect. Each sub-dialect references a
  244. specific DBAPI which will be imported before first connect. This
  245. parameter causes the import to be bypassed, and the given module to
  246. be used instead. Can be used for testing of DBAPIs as well as to
  247. inject "mock" DBAPI implementations into the :class:`.Engine`.
  248. :param paramstyle=None: The `paramstyle <http://legacy.python.org/dev/peps/pep-0249/#paramstyle>`_
  249. to use when rendering bound parameters. This style defaults to the
  250. one recommended by the DBAPI itself, which is retrieved from the
  251. ``.paramstyle`` attribute of the DBAPI. However, most DBAPIs accept
  252. more than one paramstyle, and in particular it may be desirable
  253. to change a "named" paramstyle into a "positional" one, or vice versa.
  254. When this attribute is passed, it should be one of the values
  255. ``"qmark"``, ``"numeric"``, ``"named"``, ``"format"`` or
  256. ``"pyformat"``, and should correspond to a parameter style known
  257. to be supported by the DBAPI in use.
  258. :param pool=None: an already-constructed instance of
  259. :class:`~sqlalchemy.pool.Pool`, such as a
  260. :class:`~sqlalchemy.pool.QueuePool` instance. If non-None, this
  261. pool will be used directly as the underlying connection pool
  262. for the engine, bypassing whatever connection parameters are
  263. present in the URL argument. For information on constructing
  264. connection pools manually, see :ref:`pooling_toplevel`.
  265. :param poolclass=None: a :class:`~sqlalchemy.pool.Pool`
  266. subclass, which will be used to create a connection pool
  267. instance using the connection parameters given in the URL. Note
  268. this differs from ``pool`` in that you don't actually
  269. instantiate the pool in this case, you just indicate what type
  270. of pool to be used.
  271. :param pool_logging_name: String identifier which will be used within
  272. the "name" field of logging records generated within the
  273. "sqlalchemy.pool" logger. Defaults to a hexstring of the object's
  274. id.
  275. :param pool_size=5: the number of connections to keep open
  276. inside the connection pool. This used with
  277. :class:`~sqlalchemy.pool.QueuePool` as
  278. well as :class:`~sqlalchemy.pool.SingletonThreadPool`. With
  279. :class:`~sqlalchemy.pool.QueuePool`, a ``pool_size`` setting
  280. of 0 indicates no limit; to disable pooling, set ``poolclass`` to
  281. :class:`~sqlalchemy.pool.NullPool` instead.
  282. :param pool_recycle=-1: this setting causes the pool to recycle
  283. connections after the given number of seconds has passed. It
  284. defaults to -1, or no timeout. For example, setting to 3600
  285. means connections will be recycled after one hour. Note that
  286. MySQL in particular will disconnect automatically if no
  287. activity is detected on a connection for eight hours (although
  288. this is configurable with the MySQLDB connection itself and the
  289. server configuration as well).
  290. :param pool_reset_on_return='rollback': set the "reset on return"
  291. behavior of the pool, which is whether ``rollback()``,
  292. ``commit()``, or nothing is called upon connections
  293. being returned to the pool. See the docstring for
  294. ``reset_on_return`` at :class:`.Pool`.
  295. .. versionadded:: 0.7.6
  296. :param pool_timeout=30: number of seconds to wait before giving
  297. up on getting a connection from the pool. This is only used
  298. with :class:`~sqlalchemy.pool.QueuePool`.
  299. :param strategy='plain': selects alternate engine implementations.
  300. Currently available are:
  301. * the ``threadlocal`` strategy, which is described in
  302. :ref:`threadlocal_strategy`;
  303. * the ``mock`` strategy, which dispatches all statement
  304. execution to a function passed as the argument ``executor``.
  305. See `example in the FAQ
  306. <http://docs.sqlalchemy.org/en/latest/faq/metadata_schema.html#how-can-i-get-the-create-table-drop-table-output-as-a-string>`_.
  307. :param executor=None: a function taking arguments
  308. ``(sql, *multiparams, **params)``, to which the ``mock`` strategy will
  309. dispatch all statement execution. Used only by ``strategy='mock'``.
  310. """
  311. strategy = kwargs.pop('strategy', default_strategy)
  312. strategy = strategies.strategies[strategy]
  313. return strategy.create(*args, **kwargs)
  314. def engine_from_config(configuration, prefix='sqlalchemy.', **kwargs):
  315. """Create a new Engine instance using a configuration dictionary.
  316. The dictionary is typically produced from a config file.
  317. The keys of interest to ``engine_from_config()`` should be prefixed, e.g.
  318. ``sqlalchemy.url``, ``sqlalchemy.echo``, etc. The 'prefix' argument
  319. indicates the prefix to be searched for. Each matching key (after the
  320. prefix is stripped) is treated as though it were the corresponding keyword
  321. argument to a :func:`.create_engine` call.
  322. The only required key is (assuming the default prefix) ``sqlalchemy.url``,
  323. which provides the :ref:`database URL <database_urls>`.
  324. A select set of keyword arguments will be "coerced" to their
  325. expected type based on string values. The set of arguments
  326. is extensible per-dialect using the ``engine_config_types`` accessor.
  327. :param configuration: A dictionary (typically produced from a config file,
  328. but this is not a requirement). Items whose keys start with the value
  329. of 'prefix' will have that prefix stripped, and will then be passed to
  330. :ref:`create_engine`.
  331. :param prefix: Prefix to match and then strip from keys
  332. in 'configuration'.
  333. :param kwargs: Each keyword argument to ``engine_from_config()`` itself
  334. overrides the corresponding item taken from the 'configuration'
  335. dictionary. Keyword arguments should *not* be prefixed.
  336. """
  337. options = dict((key[len(prefix):], configuration[key])
  338. for key in configuration
  339. if key.startswith(prefix))
  340. options['_coerce_config'] = True
  341. options.update(kwargs)
  342. url = options.pop('url')
  343. return create_engine(url, **options)
  344. __all__ = (
  345. 'create_engine',
  346. 'engine_from_config',
  347. )