You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

756 regels
31 KiB

  1. # engine/create.py
  2. # Copyright (C) 2005-2022 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. :attr:`_engine.Connection.default_isolation_level`
  231. - view default level
  232. :paramref:`.Connection.execution_options.isolation_level`
  233. - set per :class:`_engine.Connection` isolation level
  234. :ref:`SQLite Transaction Isolation <sqlite_isolation_level>`
  235. :ref:`PostgreSQL Transaction Isolation <postgresql_isolation_level>`
  236. :ref:`MySQL Transaction Isolation <mysql_isolation_level>`
  237. :ref:`session_transaction_isolation` - for the ORM
  238. :param json_deserializer: for dialects that support the
  239. :class:`_types.JSON`
  240. datatype, this is a Python callable that will convert a JSON string
  241. to a Python object. By default, the Python ``json.loads`` function is
  242. used.
  243. .. versionchanged:: 1.3.7 The SQLite dialect renamed this from
  244. ``_json_deserializer``.
  245. :param json_serializer: for dialects that support the :class:`_types.JSON`
  246. datatype, this is a Python callable that will render a given object
  247. as JSON. By default, the Python ``json.dumps`` function is used.
  248. .. versionchanged:: 1.3.7 The SQLite dialect renamed this from
  249. ``_json_serializer``.
  250. :param label_length=None: optional integer value which limits
  251. the size of dynamically generated column labels to that many
  252. characters. If less than 6, labels are generated as
  253. "_(counter)". If ``None``, the value of
  254. ``dialect.max_identifier_length``, which may be affected via the
  255. :paramref:`_sa.create_engine.max_identifier_length` parameter,
  256. is used instead. The value of
  257. :paramref:`_sa.create_engine.label_length`
  258. may not be larger than that of
  259. :paramref:`_sa.create_engine.max_identfier_length`.
  260. .. seealso::
  261. :paramref:`_sa.create_engine.max_identifier_length`
  262. :param listeners: A list of one or more
  263. :class:`~sqlalchemy.interfaces.PoolListener` objects which will
  264. receive connection pool events.
  265. :param logging_name: String identifier which will be used within
  266. the "name" field of logging records generated within the
  267. "sqlalchemy.engine" logger. Defaults to a hexstring of the
  268. object's id.
  269. .. seealso::
  270. :ref:`dbengine_logging` - further detail on how to configure
  271. logging.
  272. :paramref:`_engine.Connection.execution_options.logging_token`
  273. :param max_identifier_length: integer; override the max_identifier_length
  274. determined by the dialect. if ``None`` or zero, has no effect. This
  275. is the database's configured maximum number of characters that may be
  276. used in a SQL identifier such as a table name, column name, or label
  277. name. All dialects determine this value automatically, however in the
  278. case of a new database version for which this value has changed but
  279. SQLAlchemy's dialect has not been adjusted, the value may be passed
  280. here.
  281. .. versionadded:: 1.3.9
  282. .. seealso::
  283. :paramref:`_sa.create_engine.label_length`
  284. :param max_overflow=10: the number of connections to allow in
  285. connection pool "overflow", that is connections that can be
  286. opened above and beyond the pool_size setting, which defaults
  287. to five. this is only used with :class:`~sqlalchemy.pool.QueuePool`.
  288. :param module=None: reference to a Python module object (the module
  289. itself, not its string name). Specifies an alternate DBAPI module to
  290. be used by the engine's dialect. Each sub-dialect references a
  291. specific DBAPI which will be imported before first connect. This
  292. parameter causes the import to be bypassed, and the given module to
  293. be used instead. Can be used for testing of DBAPIs as well as to
  294. inject "mock" DBAPI implementations into the :class:`_engine.Engine`.
  295. :param paramstyle=None: The `paramstyle <https://legacy.python.org/dev/peps/pep-0249/#paramstyle>`_
  296. to use when rendering bound parameters. This style defaults to the
  297. one recommended by the DBAPI itself, which is retrieved from the
  298. ``.paramstyle`` attribute of the DBAPI. However, most DBAPIs accept
  299. more than one paramstyle, and in particular it may be desirable
  300. to change a "named" paramstyle into a "positional" one, or vice versa.
  301. When this attribute is passed, it should be one of the values
  302. ``"qmark"``, ``"numeric"``, ``"named"``, ``"format"`` or
  303. ``"pyformat"``, and should correspond to a parameter style known
  304. to be supported by the DBAPI in use.
  305. :param pool=None: an already-constructed instance of
  306. :class:`~sqlalchemy.pool.Pool`, such as a
  307. :class:`~sqlalchemy.pool.QueuePool` instance. If non-None, this
  308. pool will be used directly as the underlying connection pool
  309. for the engine, bypassing whatever connection parameters are
  310. present in the URL argument. For information on constructing
  311. connection pools manually, see :ref:`pooling_toplevel`.
  312. :param poolclass=None: a :class:`~sqlalchemy.pool.Pool`
  313. subclass, which will be used to create a connection pool
  314. instance using the connection parameters given in the URL. Note
  315. this differs from ``pool`` in that you don't actually
  316. instantiate the pool in this case, you just indicate what type
  317. of pool to be used.
  318. :param pool_logging_name: String identifier which will be used within
  319. the "name" field of logging records generated within the
  320. "sqlalchemy.pool" logger. Defaults to a hexstring of the object's
  321. id.
  322. .. seealso::
  323. :ref:`dbengine_logging` - further detail on how to configure
  324. logging.
  325. :param pool_pre_ping: boolean, if True will enable the connection pool
  326. "pre-ping" feature that tests connections for liveness upon
  327. each checkout.
  328. .. versionadded:: 1.2
  329. .. seealso::
  330. :ref:`pool_disconnects_pessimistic`
  331. :param pool_size=5: the number of connections to keep open
  332. inside the connection pool. This used with
  333. :class:`~sqlalchemy.pool.QueuePool` as
  334. well as :class:`~sqlalchemy.pool.SingletonThreadPool`. With
  335. :class:`~sqlalchemy.pool.QueuePool`, a ``pool_size`` setting
  336. of 0 indicates no limit; to disable pooling, set ``poolclass`` to
  337. :class:`~sqlalchemy.pool.NullPool` instead.
  338. :param pool_recycle=-1: this setting causes the pool to recycle
  339. connections after the given number of seconds has passed. It
  340. defaults to -1, or no timeout. For example, setting to 3600
  341. means connections will be recycled after one hour. Note that
  342. MySQL in particular will disconnect automatically if no
  343. activity is detected on a connection for eight hours (although
  344. this is configurable with the MySQLDB connection itself and the
  345. server configuration as well).
  346. .. seealso::
  347. :ref:`pool_setting_recycle`
  348. :param pool_reset_on_return='rollback': set the
  349. :paramref:`_pool.Pool.reset_on_return` parameter of the underlying
  350. :class:`_pool.Pool` object, which can be set to the values
  351. ``"rollback"``, ``"commit"``, or ``None``.
  352. .. seealso::
  353. :paramref:`_pool.Pool.reset_on_return`
  354. :param pool_timeout=30: number of seconds to wait before giving
  355. up on getting a connection from the pool. This is only used
  356. with :class:`~sqlalchemy.pool.QueuePool`. This can be a float but is
  357. subject to the limitations of Python time functions which may not be
  358. reliable in the tens of milliseconds.
  359. .. note: don't use 30.0 above, it seems to break with the :param tag
  360. :param pool_use_lifo=False: use LIFO (last-in-first-out) when retrieving
  361. connections from :class:`.QueuePool` instead of FIFO
  362. (first-in-first-out). Using LIFO, a server-side timeout scheme can
  363. reduce the number of connections used during non- peak periods of
  364. use. When planning for server-side timeouts, ensure that a recycle or
  365. pre-ping strategy is in use to gracefully handle stale connections.
  366. .. versionadded:: 1.3
  367. .. seealso::
  368. :ref:`pool_use_lifo`
  369. :ref:`pool_disconnects`
  370. :param plugins: string list of plugin names to load. See
  371. :class:`.CreateEnginePlugin` for background.
  372. .. versionadded:: 1.2.3
  373. :param query_cache_size: size of the cache used to cache the SQL string
  374. form of queries. Set to zero to disable caching.
  375. The cache is pruned of its least recently used items when its size reaches
  376. N * 1.5. Defaults to 500, meaning the cache will always store at least
  377. 500 SQL statements when filled, and will grow up to 750 items at which
  378. point it is pruned back down to 500 by removing the 250 least recently
  379. used items.
  380. Caching is accomplished on a per-statement basis by generating a
  381. cache key that represents the statement's structure, then generating
  382. string SQL for the current dialect only if that key is not present
  383. in the cache. All statements support caching, however some features
  384. such as an INSERT with a large set of parameters will intentionally
  385. bypass the cache. SQL logging will indicate statistics for each
  386. statement whether or not it were pull from the cache.
  387. .. note:: some ORM functions related to unit-of-work persistence as well
  388. as some attribute loading strategies will make use of individual
  389. per-mapper caches outside of the main cache.
  390. .. seealso::
  391. :ref:`sql_caching`
  392. .. versionadded:: 1.4
  393. """ # noqa
  394. if "strategy" in kwargs:
  395. strat = kwargs.pop("strategy")
  396. if strat == "mock":
  397. return create_mock_engine(url, **kwargs)
  398. else:
  399. raise exc.ArgumentError("unknown strategy: %r" % strat)
  400. kwargs.pop("empty_in_strategy", None)
  401. # create url.URL object
  402. u = _url.make_url(url)
  403. u, plugins, kwargs = u._instantiate_plugins(kwargs)
  404. entrypoint = u._get_entrypoint()
  405. dialect_cls = entrypoint.get_dialect_cls(u)
  406. if kwargs.pop("_coerce_config", False):
  407. def pop_kwarg(key, default=None):
  408. value = kwargs.pop(key, default)
  409. if key in dialect_cls.engine_config_types:
  410. value = dialect_cls.engine_config_types[key](value)
  411. return value
  412. else:
  413. pop_kwarg = kwargs.pop
  414. dialect_args = {}
  415. # consume dialect arguments from kwargs
  416. for k in util.get_cls_kwargs(dialect_cls):
  417. if k in kwargs:
  418. dialect_args[k] = pop_kwarg(k)
  419. dbapi = kwargs.pop("module", None)
  420. if dbapi is None:
  421. dbapi_args = {}
  422. for k in util.get_func_kwargs(dialect_cls.dbapi):
  423. if k in kwargs:
  424. dbapi_args[k] = pop_kwarg(k)
  425. dbapi = dialect_cls.dbapi(**dbapi_args)
  426. dialect_args["dbapi"] = dbapi
  427. dialect_args.setdefault("compiler_linting", compiler.NO_LINTING)
  428. enable_from_linting = kwargs.pop("enable_from_linting", True)
  429. if enable_from_linting:
  430. dialect_args["compiler_linting"] ^= compiler.COLLECT_CARTESIAN_PRODUCTS
  431. for plugin in plugins:
  432. plugin.handle_dialect_kwargs(dialect_cls, dialect_args)
  433. # create dialect
  434. dialect = dialect_cls(**dialect_args)
  435. # assemble connection arguments
  436. (cargs, cparams) = dialect.create_connect_args(u)
  437. cparams.update(pop_kwarg("connect_args", {}))
  438. cargs = list(cargs) # allow mutability
  439. # look for existing pool or create
  440. pool = pop_kwarg("pool", None)
  441. if pool is None:
  442. def connect(connection_record=None):
  443. if dialect._has_events:
  444. for fn in dialect.dispatch.do_connect:
  445. connection = fn(dialect, connection_record, cargs, cparams)
  446. if connection is not None:
  447. return connection
  448. return dialect.connect(*cargs, **cparams)
  449. creator = pop_kwarg("creator", connect)
  450. poolclass = pop_kwarg("poolclass", None)
  451. if poolclass is None:
  452. poolclass = dialect.get_dialect_pool_class(u)
  453. pool_args = {"dialect": dialect}
  454. # consume pool arguments from kwargs, translating a few of
  455. # the arguments
  456. translate = {
  457. "logging_name": "pool_logging_name",
  458. "echo": "echo_pool",
  459. "timeout": "pool_timeout",
  460. "recycle": "pool_recycle",
  461. "events": "pool_events",
  462. "reset_on_return": "pool_reset_on_return",
  463. "pre_ping": "pool_pre_ping",
  464. "use_lifo": "pool_use_lifo",
  465. }
  466. for k in util.get_cls_kwargs(poolclass):
  467. tk = translate.get(k, k)
  468. if tk in kwargs:
  469. pool_args[k] = pop_kwarg(tk)
  470. for plugin in plugins:
  471. plugin.handle_pool_kwargs(poolclass, pool_args)
  472. pool = poolclass(creator, **pool_args)
  473. else:
  474. if isinstance(pool, poollib.dbapi_proxy._DBProxy):
  475. pool = pool.get_pool(*cargs, **cparams)
  476. pool._dialect = dialect
  477. # create engine.
  478. if pop_kwarg("future", False):
  479. from sqlalchemy import future
  480. default_engine_class = future.Engine
  481. else:
  482. default_engine_class = base.Engine
  483. engineclass = kwargs.pop("_future_engine_class", default_engine_class)
  484. engine_args = {}
  485. for k in util.get_cls_kwargs(engineclass):
  486. if k in kwargs:
  487. engine_args[k] = pop_kwarg(k)
  488. # internal flags used by the test suite for instrumenting / proxying
  489. # engines with mocks etc.
  490. _initialize = kwargs.pop("_initialize", True)
  491. _wrap_do_on_connect = kwargs.pop("_wrap_do_on_connect", None)
  492. # all kwargs should be consumed
  493. if kwargs:
  494. raise TypeError(
  495. "Invalid argument(s) %s sent to create_engine(), "
  496. "using configuration %s/%s/%s. Please check that the "
  497. "keyword arguments are appropriate for this combination "
  498. "of components."
  499. % (
  500. ",".join("'%s'" % k for k in kwargs),
  501. dialect.__class__.__name__,
  502. pool.__class__.__name__,
  503. engineclass.__name__,
  504. )
  505. )
  506. engine = engineclass(pool, dialect, u, **engine_args)
  507. if _initialize:
  508. do_on_connect = dialect.on_connect_url(u)
  509. if do_on_connect:
  510. if _wrap_do_on_connect:
  511. do_on_connect = _wrap_do_on_connect(do_on_connect)
  512. def on_connect(dbapi_connection, connection_record):
  513. do_on_connect(dbapi_connection)
  514. event.listen(pool, "connect", on_connect)
  515. def first_connect(dbapi_connection, connection_record):
  516. c = base.Connection(
  517. engine,
  518. connection=dbapi_connection,
  519. _has_events=False,
  520. # reconnecting will be a reentrant condition, so if the
  521. # connection goes away, Connection is then closed
  522. _allow_revalidate=False,
  523. )
  524. c._execution_options = util.EMPTY_DICT
  525. try:
  526. dialect.initialize(c)
  527. finally:
  528. # note that "invalidated" and "closed" are mutually
  529. # exclusive in 1.4 Connection.
  530. if not c.invalidated and not c.closed:
  531. # transaction is rolled back otherwise, tested by
  532. # test/dialect/postgresql/test_dialect.py
  533. # ::MiscBackendTest::test_initial_transaction_state
  534. dialect.do_rollback(c.connection)
  535. # previously, the "first_connect" event was used here, which was then
  536. # scaled back if the "on_connect" handler were present. now,
  537. # since "on_connect" is virtually always present, just use
  538. # "connect" event with once_unless_exception in all cases so that
  539. # the connection event flow is consistent in all cases.
  540. event.listen(
  541. pool, "connect", first_connect, _once_unless_exception=True
  542. )
  543. dialect_cls.engine_created(engine)
  544. if entrypoint is not dialect_cls:
  545. entrypoint.engine_created(engine)
  546. for plugin in plugins:
  547. plugin.engine_created(engine)
  548. return engine
  549. def engine_from_config(configuration, prefix="sqlalchemy.", **kwargs):
  550. """Create a new Engine instance using a configuration dictionary.
  551. The dictionary is typically produced from a config file.
  552. The keys of interest to ``engine_from_config()`` should be prefixed, e.g.
  553. ``sqlalchemy.url``, ``sqlalchemy.echo``, etc. The 'prefix' argument
  554. indicates the prefix to be searched for. Each matching key (after the
  555. prefix is stripped) is treated as though it were the corresponding keyword
  556. argument to a :func:`_sa.create_engine` call.
  557. The only required key is (assuming the default prefix) ``sqlalchemy.url``,
  558. which provides the :ref:`database URL <database_urls>`.
  559. A select set of keyword arguments will be "coerced" to their
  560. expected type based on string values. The set of arguments
  561. is extensible per-dialect using the ``engine_config_types`` accessor.
  562. :param configuration: A dictionary (typically produced from a config file,
  563. but this is not a requirement). Items whose keys start with the value
  564. of 'prefix' will have that prefix stripped, and will then be passed to
  565. :func:`_sa.create_engine`.
  566. :param prefix: Prefix to match and then strip from keys
  567. in 'configuration'.
  568. :param kwargs: Each keyword argument to ``engine_from_config()`` itself
  569. overrides the corresponding item taken from the 'configuration'
  570. dictionary. Keyword arguments should *not* be prefixed.
  571. """
  572. options = dict(
  573. (key[len(prefix) :], configuration[key])
  574. for key in configuration
  575. if key.startswith(prefix)
  576. )
  577. options["_coerce_config"] = True
  578. options.update(kwargs)
  579. url = options.pop("url")
  580. return create_engine(url, **options)