create.py 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739
  1. # engine/create.py
  2. # Copyright (C) 2005-2024 the SQLAlchemy authors and contributors
  3. # <see AUTHORS file>
  4. #
  5. # This module is part of SQLAlchemy and is released under
  6. # the MIT License: https://www.opensource.org/licenses/mit-license.php
  7. from . import base
  8. from . import url as _url
  9. from .mock import create_mock_engine
  10. from .. import event
  11. from .. import exc
  12. from .. import pool as poollib
  13. from .. import util
  14. from ..sql import compiler
  15. @util.deprecated_params(
  16. strategy=(
  17. "1.4",
  18. "The :paramref:`_sa.create_engine.strategy` keyword is deprecated, "
  19. "and the only argument accepted is 'mock'; please use "
  20. ":func:`.create_mock_engine` going forward. For general "
  21. "customization of create_engine which may have been accomplished "
  22. "using strategies, see :class:`.CreateEnginePlugin`.",
  23. ),
  24. empty_in_strategy=(
  25. "1.4",
  26. "The :paramref:`_sa.create_engine.empty_in_strategy` keyword is "
  27. "deprecated, and no longer has any effect. All IN expressions "
  28. "are now rendered using "
  29. 'the "expanding parameter" strategy which renders a set of bound'
  30. 'expressions, or an "empty set" SELECT, at statement execution'
  31. "time.",
  32. ),
  33. case_sensitive=(
  34. "1.4",
  35. "The :paramref:`_sa.create_engine.case_sensitive` parameter "
  36. "is deprecated and will be removed in a future release. "
  37. "Applications should work with result column names in a case "
  38. "sensitive fashion.",
  39. ),
  40. )
  41. def create_engine(url, **kwargs):
  42. """Create a new :class:`_engine.Engine` instance.
  43. The standard calling form is to send the :ref:`URL <database_urls>` as the
  44. first positional argument, usually a string
  45. that indicates database dialect and connection arguments::
  46. engine = create_engine("postgresql://scott:tiger@localhost/test")
  47. .. note::
  48. Please review :ref:`database_urls` for general guidelines in composing
  49. URL strings. In particular, special characters, such as those often
  50. part of passwords, must be URL encoded to be properly parsed.
  51. Additional keyword arguments may then follow it which
  52. establish various options on the resulting :class:`_engine.Engine`
  53. and its underlying :class:`.Dialect` and :class:`_pool.Pool`
  54. constructs::
  55. engine = create_engine("mysql://scott:tiger@hostname/dbname",
  56. encoding='latin1', echo=True)
  57. The string form of the URL is
  58. ``dialect[+driver]://user:password@host/dbname[?key=value..]``, where
  59. ``dialect`` is a database name such as ``mysql``, ``oracle``,
  60. ``postgresql``, etc., and ``driver`` the name of a DBAPI, such as
  61. ``psycopg2``, ``pyodbc``, ``cx_oracle``, etc. Alternatively,
  62. the URL can be an instance of :class:`~sqlalchemy.engine.url.URL`.
  63. ``**kwargs`` takes a wide variety of options which are routed
  64. towards their appropriate components. Arguments may be specific to
  65. the :class:`_engine.Engine`, the underlying :class:`.Dialect`,
  66. as well as the
  67. :class:`_pool.Pool`. Specific dialects also accept keyword arguments that
  68. are unique to that dialect. Here, we describe the parameters
  69. that are common to most :func:`_sa.create_engine()` usage.
  70. Once established, the newly resulting :class:`_engine.Engine` will
  71. request a connection from the underlying :class:`_pool.Pool` once
  72. :meth:`_engine.Engine.connect` is called, or a method which depends on it
  73. such as :meth:`_engine.Engine.execute` is invoked. The
  74. :class:`_pool.Pool` in turn
  75. will establish the first actual DBAPI connection when this request
  76. is received. The :func:`_sa.create_engine` call itself does **not**
  77. establish any actual DBAPI connections directly.
  78. .. seealso::
  79. :doc:`/core/engines`
  80. :doc:`/dialects/index`
  81. :ref:`connections_toplevel`
  82. :param case_sensitive: if False, result column names
  83. will match in a case-insensitive fashion, that is,
  84. ``row['SomeColumn']``.
  85. :param connect_args: a dictionary of options which will be
  86. passed directly to the DBAPI's ``connect()`` method as
  87. additional keyword arguments. See the example
  88. at :ref:`custom_dbapi_args`.
  89. :param convert_unicode=False: if set to True, causes
  90. all :class:`.String` datatypes to act as though the
  91. :paramref:`.String.convert_unicode` flag has been set to ``True``,
  92. regardless of a setting of ``False`` on an individual :class:`.String`
  93. type. This has the effect of causing all :class:`.String` -based
  94. columns to accommodate Python Unicode objects directly as though the
  95. datatype were the :class:`.Unicode` type.
  96. .. deprecated:: 1.3
  97. The :paramref:`_sa.create_engine.convert_unicode` parameter
  98. is deprecated and will be removed in a future release.
  99. All modern DBAPIs now support Python Unicode directly and this
  100. parameter is unnecessary.
  101. :param creator: a callable which returns a DBAPI connection.
  102. This creation function will be passed to the underlying
  103. connection pool and will be used to create all new database
  104. connections. Usage of this function causes connection
  105. parameters specified in the URL argument to be bypassed.
  106. This hook is not as flexible as the newer
  107. :meth:`_events.DialectEvents.do_connect` hook which allows complete
  108. control over how a connection is made to the database, given the full
  109. set of URL arguments and state beforehand.
  110. .. seealso::
  111. :meth:`_events.DialectEvents.do_connect` - event hook that allows
  112. full control over DBAPI connection mechanics.
  113. :ref:`custom_dbapi_args`
  114. :param echo=False: if True, the Engine will log all statements
  115. as well as a ``repr()`` of their parameter lists to the default log
  116. handler, which defaults to ``sys.stdout`` for output. If set to the
  117. string ``"debug"``, result rows will be printed to the standard output
  118. as well. The ``echo`` attribute of ``Engine`` can be modified at any
  119. time to turn logging on and off; direct control of logging is also
  120. available using the standard Python ``logging`` module.
  121. .. seealso::
  122. :ref:`dbengine_logging` - further detail on how to configure
  123. logging.
  124. :param echo_pool=False: if True, the connection pool will log
  125. informational output such as when connections are invalidated
  126. as well as when connections are recycled to the default log handler,
  127. which defaults to ``sys.stdout`` for output. If set to the string
  128. ``"debug"``, the logging will include pool checkouts and checkins.
  129. Direct control of logging is also available using the standard Python
  130. ``logging`` module.
  131. .. seealso::
  132. :ref:`dbengine_logging` - further detail on how to configure
  133. logging.
  134. :param empty_in_strategy: No longer used; SQLAlchemy now uses
  135. "empty set" behavior for IN in all cases.
  136. :param enable_from_linting: defaults to True. Will emit a warning
  137. if a given SELECT statement is found to have un-linked FROM elements
  138. which would cause a cartesian product.
  139. .. versionadded:: 1.4
  140. .. seealso::
  141. :ref:`change_4737`
  142. :param encoding: **legacy Python 2 value only, where it only applies to
  143. specific DBAPIs, not used in Python 3 for any modern DBAPI driver.
  144. Please refer to individual dialect documentation for client encoding
  145. behaviors.** Defaults to the string value ``utf-8``. This value
  146. refers **only** to the character encoding that is used when SQLAlchemy
  147. sends or receives data from a :term:`DBAPI` that does not support
  148. Python Unicode and **is only used under Python 2**, only for certain
  149. DBAPI drivers, and only in certain circumstances. **Python 3 users
  150. please DISREGARD this parameter and refer to the documentation for the
  151. specific dialect in use in order to configure character encoding
  152. behavior.**
  153. .. note:: The ``encoding`` parameter deals only with in-Python
  154. encoding issues that were prevalent with **some DBAPIS only**
  155. under **Python 2 only**. Under Python 3 it is not used by
  156. any modern dialect. For DBAPIs that require
  157. client encoding configurations, which are most of those outside
  158. of SQLite, please consult specific :ref:`dialect documentation
  159. <dialect_toplevel>` for details.
  160. All modern DBAPIs that work in Python 3 necessarily feature direct
  161. support for Python unicode strings. Under Python 2, this was not
  162. always the case. For those scenarios where the DBAPI is detected as
  163. not supporting a Python ``unicode`` object under Python 2, this
  164. encoding is used to determine the source/destination encoding. It is
  165. **not used** for those cases where the DBAPI handles unicode directly.
  166. To properly configure a system to accommodate Python ``unicode``
  167. objects, the DBAPI should be configured to handle unicode to the
  168. greatest degree as is appropriate - see the notes on unicode pertaining
  169. to the specific target database in use at :ref:`dialect_toplevel`.
  170. Areas where string encoding may need to be accommodated
  171. outside of the DBAPI, nearly always under **Python 2 only**,
  172. include zero or more of:
  173. * the values passed to bound parameters, corresponding to
  174. the :class:`.Unicode` type or the :class:`.String` type
  175. when ``convert_unicode`` is ``True``;
  176. * the values returned in result set columns corresponding
  177. to the :class:`.Unicode` type or the :class:`.String`
  178. type when ``convert_unicode`` is ``True``;
  179. * the string SQL statement passed to the DBAPI's
  180. ``cursor.execute()`` method;
  181. * the string names of the keys in the bound parameter
  182. dictionary passed to the DBAPI's ``cursor.execute()``
  183. as well as ``cursor.setinputsizes()`` methods;
  184. * the string column names retrieved from the DBAPI's
  185. ``cursor.description`` attribute.
  186. When using Python 3, the DBAPI is required to support all of the above
  187. values as Python ``unicode`` objects, which in Python 3 are just known
  188. as ``str``. In Python 2, the DBAPI does not specify unicode behavior
  189. at all, so SQLAlchemy must make decisions for each of the above values
  190. on a per-DBAPI basis - implementations are completely inconsistent in
  191. their behavior.
  192. :param execution_options: Dictionary execution options which will
  193. be applied to all connections. See
  194. :meth:`~sqlalchemy.engine.Connection.execution_options`
  195. :param future: Use the 2.0 style :class:`_future.Engine` and
  196. :class:`_future.Connection` API.
  197. .. versionadded:: 1.4
  198. .. seealso::
  199. :ref:`migration_20_toplevel`
  200. :param hide_parameters: Boolean, when set to True, SQL statement parameters
  201. will not be displayed in INFO logging nor will they be formatted into
  202. the string representation of :class:`.StatementError` objects.
  203. .. versionadded:: 1.3.8
  204. .. seealso::
  205. :ref:`dbengine_logging` - further detail on how to configure
  206. logging.
  207. :param implicit_returning=True: Legacy flag that when set to ``False``
  208. will disable the use of ``RETURNING`` on supporting backends where it
  209. would normally be used to fetch newly generated primary key values for
  210. single-row INSERT statements that do not otherwise specify a RETURNING
  211. clause. This behavior applies primarily to the PostgreSQL, Oracle,
  212. SQL Server backends.
  213. .. warning:: this flag originally allowed the "implicit returning"
  214. feature to be *enabled* back when it was very new and there was not
  215. well-established database support. In modern SQLAlchemy, this flag
  216. should **always be set to True**. Some SQLAlchemy features will
  217. fail to function properly if this flag is set to ``False``.
  218. :param isolation_level: this string parameter is interpreted by various
  219. dialects in order to affect the transaction isolation level of the
  220. database connection. The parameter essentially accepts some subset of
  221. these string arguments: ``"SERIALIZABLE"``, ``"REPEATABLE READ"``,
  222. ``"READ COMMITTED"``, ``"READ UNCOMMITTED"`` and ``"AUTOCOMMIT"``.
  223. Behavior here varies per backend, and
  224. individual dialects should be consulted directly.
  225. Note that the isolation level can also be set on a
  226. per-:class:`_engine.Connection` basis as well, using the
  227. :paramref:`.Connection.execution_options.isolation_level`
  228. feature.
  229. .. seealso::
  230. :ref:`dbapi_autocommit`
  231. :param json_deserializer: for dialects that support the
  232. :class:`_types.JSON`
  233. datatype, this is a Python callable that will convert a JSON string
  234. to a Python object. By default, the Python ``json.loads`` function is
  235. used.
  236. .. versionchanged:: 1.3.7 The SQLite dialect renamed this from
  237. ``_json_deserializer``.
  238. :param json_serializer: for dialects that support the :class:`_types.JSON`
  239. datatype, this is a Python callable that will render a given object
  240. as JSON. By default, the Python ``json.dumps`` function is used.
  241. .. versionchanged:: 1.3.7 The SQLite dialect renamed this from
  242. ``_json_serializer``.
  243. :param label_length=None: optional integer value which limits
  244. the size of dynamically generated column labels to that many
  245. characters. If less than 6, labels are generated as
  246. "_(counter)". If ``None``, the value of
  247. ``dialect.max_identifier_length``, which may be affected via the
  248. :paramref:`_sa.create_engine.max_identifier_length` parameter,
  249. is used instead. The value of
  250. :paramref:`_sa.create_engine.label_length`
  251. may not be larger than that of
  252. :paramref:`_sa.create_engine.max_identfier_length`.
  253. .. seealso::
  254. :paramref:`_sa.create_engine.max_identifier_length`
  255. :param logging_name: String identifier which will be used within
  256. the "name" field of logging records generated within the
  257. "sqlalchemy.engine" logger. Defaults to a hexstring of the
  258. object's id.
  259. .. seealso::
  260. :ref:`dbengine_logging` - further detail on how to configure
  261. logging.
  262. :paramref:`_engine.Connection.execution_options.logging_token`
  263. :param max_identifier_length: integer; override the max_identifier_length
  264. determined by the dialect. if ``None`` or zero, has no effect. This
  265. is the database's configured maximum number of characters that may be
  266. used in a SQL identifier such as a table name, column name, or label
  267. name. All dialects determine this value automatically, however in the
  268. case of a new database version for which this value has changed but
  269. SQLAlchemy's dialect has not been adjusted, the value may be passed
  270. here.
  271. .. versionadded:: 1.3.9
  272. .. seealso::
  273. :paramref:`_sa.create_engine.label_length`
  274. :param max_overflow=10: the number of connections to allow in
  275. connection pool "overflow", that is connections that can be
  276. opened above and beyond the pool_size setting, which defaults
  277. to five. this is only used with :class:`~sqlalchemy.pool.QueuePool`.
  278. :param module=None: reference to a Python module object (the module
  279. itself, not its string name). Specifies an alternate DBAPI module to
  280. be used by the engine's dialect. Each sub-dialect references a
  281. specific DBAPI which will be imported before first connect. This
  282. parameter causes the import to be bypassed, and the given module to
  283. be used instead. Can be used for testing of DBAPIs as well as to
  284. inject "mock" DBAPI implementations into the :class:`_engine.Engine`.
  285. :param paramstyle=None: The `paramstyle <https://legacy.python.org/dev/peps/pep-0249/#paramstyle>`_
  286. to use when rendering bound parameters. This style defaults to the
  287. one recommended by the DBAPI itself, which is retrieved from the
  288. ``.paramstyle`` attribute of the DBAPI. However, most DBAPIs accept
  289. more than one paramstyle, and in particular it may be desirable
  290. to change a "named" paramstyle into a "positional" one, or vice versa.
  291. When this attribute is passed, it should be one of the values
  292. ``"qmark"``, ``"numeric"``, ``"named"``, ``"format"`` or
  293. ``"pyformat"``, and should correspond to a parameter style known
  294. to be supported by the DBAPI in use.
  295. :param pool=None: an already-constructed instance of
  296. :class:`~sqlalchemy.pool.Pool`, such as a
  297. :class:`~sqlalchemy.pool.QueuePool` instance. If non-None, this
  298. pool will be used directly as the underlying connection pool
  299. for the engine, bypassing whatever connection parameters are
  300. present in the URL argument. For information on constructing
  301. connection pools manually, see :ref:`pooling_toplevel`.
  302. :param poolclass=None: a :class:`~sqlalchemy.pool.Pool`
  303. subclass, which will be used to create a connection pool
  304. instance using the connection parameters given in the URL. Note
  305. this differs from ``pool`` in that you don't actually
  306. instantiate the pool in this case, you just indicate what type
  307. of pool to be used.
  308. :param pool_logging_name: String identifier which will be used within
  309. the "name" field of logging records generated within the
  310. "sqlalchemy.pool" logger. Defaults to a hexstring of the object's
  311. id.
  312. .. seealso::
  313. :ref:`dbengine_logging` - further detail on how to configure
  314. logging.
  315. :param pool_pre_ping: boolean, if True will enable the connection pool
  316. "pre-ping" feature that tests connections for liveness upon
  317. each checkout.
  318. .. versionadded:: 1.2
  319. .. seealso::
  320. :ref:`pool_disconnects_pessimistic`
  321. :param pool_size=5: the number of connections to keep open
  322. inside the connection pool. This used with
  323. :class:`~sqlalchemy.pool.QueuePool` as
  324. well as :class:`~sqlalchemy.pool.SingletonThreadPool`. With
  325. :class:`~sqlalchemy.pool.QueuePool`, a ``pool_size`` setting
  326. of 0 indicates no limit; to disable pooling, set ``poolclass`` to
  327. :class:`~sqlalchemy.pool.NullPool` instead.
  328. :param pool_recycle=-1: this setting causes the pool to recycle
  329. connections after the given number of seconds has passed. It
  330. defaults to -1, or no timeout. For example, setting to 3600
  331. means connections will be recycled after one hour. Note that
  332. MySQL in particular will disconnect automatically if no
  333. activity is detected on a connection for eight hours (although
  334. this is configurable with the MySQLDB connection itself and the
  335. server configuration as well).
  336. .. seealso::
  337. :ref:`pool_setting_recycle`
  338. :param pool_reset_on_return='rollback': set the
  339. :paramref:`_pool.Pool.reset_on_return` parameter of the underlying
  340. :class:`_pool.Pool` object, which can be set to the values
  341. ``"rollback"``, ``"commit"``, or ``None``.
  342. .. seealso::
  343. :ref:`pool_reset_on_return`
  344. :param pool_timeout=30: number of seconds to wait before giving
  345. up on getting a connection from the pool. This is only used
  346. with :class:`~sqlalchemy.pool.QueuePool`. This can be a float but is
  347. subject to the limitations of Python time functions which may not be
  348. reliable in the tens of milliseconds.
  349. .. note: don't use 30.0 above, it seems to break with the :param tag
  350. :param pool_use_lifo=False: use LIFO (last-in-first-out) when retrieving
  351. connections from :class:`.QueuePool` instead of FIFO
  352. (first-in-first-out). Using LIFO, a server-side timeout scheme can
  353. reduce the number of connections used during non- peak periods of
  354. use. When planning for server-side timeouts, ensure that a recycle or
  355. pre-ping strategy is in use to gracefully handle stale connections.
  356. .. versionadded:: 1.3
  357. .. seealso::
  358. :ref:`pool_use_lifo`
  359. :ref:`pool_disconnects`
  360. :param plugins: string list of plugin names to load. See
  361. :class:`.CreateEnginePlugin` for background.
  362. .. versionadded:: 1.2.3
  363. :param query_cache_size: size of the cache used to cache the SQL string
  364. form of queries. Set to zero to disable caching.
  365. The cache is pruned of its least recently used items when its size reaches
  366. N * 1.5. Defaults to 500, meaning the cache will always store at least
  367. 500 SQL statements when filled, and will grow up to 750 items at which
  368. point it is pruned back down to 500 by removing the 250 least recently
  369. used items.
  370. Caching is accomplished on a per-statement basis by generating a
  371. cache key that represents the statement's structure, then generating
  372. string SQL for the current dialect only if that key is not present
  373. in the cache. All statements support caching, however some features
  374. such as an INSERT with a large set of parameters will intentionally
  375. bypass the cache. SQL logging will indicate statistics for each
  376. statement whether or not it were pull from the cache.
  377. .. note:: some ORM functions related to unit-of-work persistence as well
  378. as some attribute loading strategies will make use of individual
  379. per-mapper caches outside of the main cache.
  380. .. seealso::
  381. :ref:`sql_caching`
  382. .. versionadded:: 1.4
  383. """ # noqa
  384. if "strategy" in kwargs:
  385. strat = kwargs.pop("strategy")
  386. if strat == "mock":
  387. return create_mock_engine(url, **kwargs)
  388. else:
  389. raise exc.ArgumentError("unknown strategy: %r" % strat)
  390. kwargs.pop("empty_in_strategy", None)
  391. # create url.URL object
  392. u = _url.make_url(url)
  393. u, plugins, kwargs = u._instantiate_plugins(kwargs)
  394. entrypoint = u._get_entrypoint()
  395. dialect_cls = entrypoint.get_dialect_cls(u)
  396. if kwargs.pop("_coerce_config", False):
  397. def pop_kwarg(key, default=None):
  398. value = kwargs.pop(key, default)
  399. if key in dialect_cls.engine_config_types:
  400. value = dialect_cls.engine_config_types[key](value)
  401. return value
  402. else:
  403. pop_kwarg = kwargs.pop
  404. dialect_args = {}
  405. # consume dialect arguments from kwargs
  406. for k in util.get_cls_kwargs(dialect_cls):
  407. if k in kwargs:
  408. dialect_args[k] = pop_kwarg(k)
  409. dbapi = kwargs.pop("module", None)
  410. if dbapi is None:
  411. dbapi_args = {}
  412. for k in util.get_func_kwargs(dialect_cls.dbapi):
  413. if k in kwargs:
  414. dbapi_args[k] = pop_kwarg(k)
  415. dbapi = dialect_cls.dbapi(**dbapi_args)
  416. dialect_args["dbapi"] = dbapi
  417. dialect_args.setdefault("compiler_linting", compiler.NO_LINTING)
  418. enable_from_linting = kwargs.pop("enable_from_linting", True)
  419. if enable_from_linting:
  420. dialect_args["compiler_linting"] ^= compiler.COLLECT_CARTESIAN_PRODUCTS
  421. for plugin in plugins:
  422. plugin.handle_dialect_kwargs(dialect_cls, dialect_args)
  423. # create dialect
  424. dialect = dialect_cls(**dialect_args)
  425. # assemble connection arguments
  426. (cargs, cparams) = dialect.create_connect_args(u)
  427. cparams.update(pop_kwarg("connect_args", {}))
  428. cargs = list(cargs) # allow mutability
  429. # look for existing pool or create
  430. pool = pop_kwarg("pool", None)
  431. if pool is None:
  432. def connect(connection_record=None):
  433. if dialect._has_events:
  434. for fn in dialect.dispatch.do_connect:
  435. connection = fn(dialect, connection_record, cargs, cparams)
  436. if connection is not None:
  437. return connection
  438. return dialect.connect(*cargs, **cparams)
  439. creator = pop_kwarg("creator", connect)
  440. poolclass = pop_kwarg("poolclass", None)
  441. if poolclass is None:
  442. poolclass = dialect.get_dialect_pool_class(u)
  443. pool_args = {"dialect": dialect}
  444. # consume pool arguments from kwargs, translating a few of
  445. # the arguments
  446. translate = {
  447. "logging_name": "pool_logging_name",
  448. "echo": "echo_pool",
  449. "timeout": "pool_timeout",
  450. "recycle": "pool_recycle",
  451. "events": "pool_events",
  452. "reset_on_return": "pool_reset_on_return",
  453. "pre_ping": "pool_pre_ping",
  454. "use_lifo": "pool_use_lifo",
  455. }
  456. for k in util.get_cls_kwargs(poolclass):
  457. tk = translate.get(k, k)
  458. if tk in kwargs:
  459. pool_args[k] = pop_kwarg(tk)
  460. for plugin in plugins:
  461. plugin.handle_pool_kwargs(poolclass, pool_args)
  462. pool = poolclass(creator, **pool_args)
  463. else:
  464. if isinstance(pool, poollib.dbapi_proxy._DBProxy):
  465. pool = pool.get_pool(*cargs, **cparams)
  466. pool._dialect = dialect
  467. # create engine.
  468. if pop_kwarg("future", False):
  469. from sqlalchemy import future
  470. default_engine_class = future.Engine
  471. else:
  472. default_engine_class = base.Engine
  473. engineclass = kwargs.pop("_future_engine_class", default_engine_class)
  474. engine_args = {}
  475. for k in util.get_cls_kwargs(engineclass):
  476. if k in kwargs:
  477. engine_args[k] = pop_kwarg(k)
  478. # internal flags used by the test suite for instrumenting / proxying
  479. # engines with mocks etc.
  480. _initialize = kwargs.pop("_initialize", True)
  481. _wrap_do_on_connect = kwargs.pop("_wrap_do_on_connect", None)
  482. # all kwargs should be consumed
  483. if kwargs:
  484. raise TypeError(
  485. "Invalid argument(s) %s sent to create_engine(), "
  486. "using configuration %s/%s/%s. Please check that the "
  487. "keyword arguments are appropriate for this combination "
  488. "of components."
  489. % (
  490. ",".join("'%s'" % k for k in kwargs),
  491. dialect.__class__.__name__,
  492. pool.__class__.__name__,
  493. engineclass.__name__,
  494. )
  495. )
  496. engine = engineclass(pool, dialect, u, **engine_args)
  497. if _initialize:
  498. do_on_connect = dialect.on_connect_url(u)
  499. if do_on_connect:
  500. if _wrap_do_on_connect:
  501. do_on_connect = _wrap_do_on_connect(do_on_connect)
  502. def on_connect(dbapi_connection, connection_record):
  503. do_on_connect(dbapi_connection)
  504. event.listen(pool, "connect", on_connect)
  505. def first_connect(dbapi_connection, connection_record):
  506. c = base.Connection(
  507. engine,
  508. connection=dbapi_connection,
  509. _has_events=False,
  510. # reconnecting will be a reentrant condition, so if the
  511. # connection goes away, Connection is then closed
  512. _allow_revalidate=False,
  513. )
  514. c._execution_options = util.EMPTY_DICT
  515. try:
  516. dialect.initialize(c)
  517. finally:
  518. # note that "invalidated" and "closed" are mutually
  519. # exclusive in 1.4 Connection.
  520. if not c.invalidated and not c.closed:
  521. # transaction is rolled back otherwise, tested by
  522. # test/dialect/postgresql/test_dialect.py
  523. # ::MiscBackendTest::test_initial_transaction_state
  524. dialect.do_rollback(c.connection)
  525. # previously, the "first_connect" event was used here, which was then
  526. # scaled back if the "on_connect" handler were present. now,
  527. # since "on_connect" is virtually always present, just use
  528. # "connect" event with once_unless_exception in all cases so that
  529. # the connection event flow is consistent in all cases.
  530. event.listen(
  531. pool, "connect", first_connect, _once_unless_exception=True
  532. )
  533. dialect_cls.engine_created(engine)
  534. if entrypoint is not dialect_cls:
  535. entrypoint.engine_created(engine)
  536. for plugin in plugins:
  537. plugin.engine_created(engine)
  538. return engine
  539. def engine_from_config(configuration, prefix="sqlalchemy.", **kwargs):
  540. """Create a new Engine instance using a configuration dictionary.
  541. The dictionary is typically produced from a config file.
  542. The keys of interest to ``engine_from_config()`` should be prefixed, e.g.
  543. ``sqlalchemy.url``, ``sqlalchemy.echo``, etc. The 'prefix' argument
  544. indicates the prefix to be searched for. Each matching key (after the
  545. prefix is stripped) is treated as though it were the corresponding keyword
  546. argument to a :func:`_sa.create_engine` call.
  547. The only required key is (assuming the default prefix) ``sqlalchemy.url``,
  548. which provides the :ref:`database URL <database_urls>`.
  549. A select set of keyword arguments will be "coerced" to their
  550. expected type based on string values. The set of arguments
  551. is extensible per-dialect using the ``engine_config_types`` accessor.
  552. :param configuration: A dictionary (typically produced from a config file,
  553. but this is not a requirement). Items whose keys start with the value
  554. of 'prefix' will have that prefix stripped, and will then be passed to
  555. :func:`_sa.create_engine`.
  556. :param prefix: Prefix to match and then strip from keys
  557. in 'configuration'.
  558. :param kwargs: Each keyword argument to ``engine_from_config()`` itself
  559. overrides the corresponding item taken from the 'configuration'
  560. dictionary. Keyword arguments should *not* be prefixed.
  561. """
  562. options = dict(
  563. (key[len(prefix) :], configuration[key])
  564. for key in configuration
  565. if key.startswith(prefix)
  566. )
  567. options["_coerce_config"] = True
  568. options.update(kwargs)
  569. url = options.pop("url")
  570. return create_engine(url, **options)