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.

744 lines
30KB

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