Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.8/site-packages/sqlalchemy/engine/create.py: 65%

116 statements  

« prev     ^ index     » next       coverage.py v7.0.1, created at 2022-12-25 06:11 +0000

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 

8 

9from . import base 

10from . import url as _url 

11from .mock import create_mock_engine 

12from .. import event 

13from .. import exc 

14from .. import pool as poollib 

15from .. import util 

16from ..sql import compiler 

17 

18 

19@util.deprecated_params( 

20 strategy=( 

21 "1.4", 

22 "The :paramref:`_sa.create_engine.strategy` keyword is deprecated, " 

23 "and the only argument accepted is 'mock'; please use " 

24 ":func:`.create_mock_engine` going forward. For general " 

25 "customization of create_engine which may have been accomplished " 

26 "using strategies, see :class:`.CreateEnginePlugin`.", 

27 ), 

28 empty_in_strategy=( 

29 "1.4", 

30 "The :paramref:`_sa.create_engine.empty_in_strategy` keyword is " 

31 "deprecated, and no longer has any effect. All IN expressions " 

32 "are now rendered using " 

33 'the "expanding parameter" strategy which renders a set of bound' 

34 'expressions, or an "empty set" SELECT, at statement execution' 

35 "time.", 

36 ), 

37 case_sensitive=( 

38 "1.4", 

39 "The :paramref:`_sa.create_engine.case_sensitive` parameter " 

40 "is deprecated and will be removed in a future release. " 

41 "Applications should work with result column names in a case " 

42 "sensitive fashion.", 

43 ), 

44) 

45def create_engine(url, **kwargs): 

46 """Create a new :class:`_engine.Engine` instance. 

47 

48 The standard calling form is to send the :ref:`URL <database_urls>` as the 

49 first positional argument, usually a string 

50 that indicates database dialect and connection arguments:: 

51 

52 engine = create_engine("postgresql://scott:tiger@localhost/test") 

53 

54 .. note:: 

55 

56 Please review :ref:`database_urls` for general guidelines in composing 

57 URL strings. In particular, special characters, such as those often 

58 part of passwords, must be URL encoded to be properly parsed. 

59 

60 Additional keyword arguments may then follow it which 

61 establish various options on the resulting :class:`_engine.Engine` 

62 and its underlying :class:`.Dialect` and :class:`_pool.Pool` 

63 constructs:: 

64 

65 engine = create_engine("mysql://scott:tiger@hostname/dbname", 

66 encoding='latin1', echo=True) 

67 

68 The string form of the URL is 

69 ``dialect[+driver]://user:password@host/dbname[?key=value..]``, where 

70 ``dialect`` is a database name such as ``mysql``, ``oracle``, 

71 ``postgresql``, etc., and ``driver`` the name of a DBAPI, such as 

72 ``psycopg2``, ``pyodbc``, ``cx_oracle``, etc. Alternatively, 

73 the URL can be an instance of :class:`~sqlalchemy.engine.url.URL`. 

74 

75 ``**kwargs`` takes a wide variety of options which are routed 

76 towards their appropriate components. Arguments may be specific to 

77 the :class:`_engine.Engine`, the underlying :class:`.Dialect`, 

78 as well as the 

79 :class:`_pool.Pool`. Specific dialects also accept keyword arguments that 

80 are unique to that dialect. Here, we describe the parameters 

81 that are common to most :func:`_sa.create_engine()` usage. 

82 

83 Once established, the newly resulting :class:`_engine.Engine` will 

84 request a connection from the underlying :class:`_pool.Pool` once 

85 :meth:`_engine.Engine.connect` is called, or a method which depends on it 

86 such as :meth:`_engine.Engine.execute` is invoked. The 

87 :class:`_pool.Pool` in turn 

88 will establish the first actual DBAPI connection when this request 

89 is received. The :func:`_sa.create_engine` call itself does **not** 

90 establish any actual DBAPI connections directly. 

91 

92 .. seealso:: 

93 

94 :doc:`/core/engines` 

95 

96 :doc:`/dialects/index` 

97 

98 :ref:`connections_toplevel` 

99 

100 :param case_sensitive: if False, result column names 

101 will match in a case-insensitive fashion, that is, 

102 ``row['SomeColumn']``. 

103 

104 :param connect_args: a dictionary of options which will be 

105 passed directly to the DBAPI's ``connect()`` method as 

106 additional keyword arguments. See the example 

107 at :ref:`custom_dbapi_args`. 

108 

109 :param convert_unicode=False: if set to True, causes 

110 all :class:`.String` datatypes to act as though the 

111 :paramref:`.String.convert_unicode` flag has been set to ``True``, 

112 regardless of a setting of ``False`` on an individual :class:`.String` 

113 type. This has the effect of causing all :class:`.String` -based 

114 columns to accommodate Python Unicode objects directly as though the 

115 datatype were the :class:`.Unicode` type. 

116 

117 .. deprecated:: 1.3 

118 

119 The :paramref:`_sa.create_engine.convert_unicode` parameter 

120 is deprecated and will be removed in a future release. 

121 All modern DBAPIs now support Python Unicode directly and this 

122 parameter is unnecessary. 

123 

124 :param creator: a callable which returns a DBAPI connection. 

125 This creation function will be passed to the underlying 

126 connection pool and will be used to create all new database 

127 connections. Usage of this function causes connection 

128 parameters specified in the URL argument to be bypassed. 

129 

130 This hook is not as flexible as the newer 

131 :meth:`_events.DialectEvents.do_connect` hook which allows complete 

132 control over how a connection is made to the database, given the full 

133 set of URL arguments and state beforehand. 

134 

135 .. seealso:: 

136 

137 :meth:`_events.DialectEvents.do_connect` - event hook that allows 

138 full control over DBAPI connection mechanics. 

139 

140 :ref:`custom_dbapi_args` 

141 

142 :param echo=False: if True, the Engine will log all statements 

143 as well as a ``repr()`` of their parameter lists to the default log 

144 handler, which defaults to ``sys.stdout`` for output. If set to the 

145 string ``"debug"``, result rows will be printed to the standard output 

146 as well. The ``echo`` attribute of ``Engine`` can be modified at any 

147 time to turn logging on and off; direct control of logging is also 

148 available using the standard Python ``logging`` module. 

149 

150 .. seealso:: 

151 

152 :ref:`dbengine_logging` - further detail on how to configure 

153 logging. 

154 

155 

156 :param echo_pool=False: if True, the connection pool will log 

157 informational output such as when connections are invalidated 

158 as well as when connections are recycled to the default log handler, 

159 which defaults to ``sys.stdout`` for output. If set to the string 

160 ``"debug"``, the logging will include pool checkouts and checkins. 

161 Direct control of logging is also available using the standard Python 

162 ``logging`` module. 

163 

164 .. seealso:: 

165 

166 :ref:`dbengine_logging` - further detail on how to configure 

167 logging. 

168 

169 

170 :param empty_in_strategy: No longer used; SQLAlchemy now uses 

171 "empty set" behavior for IN in all cases. 

172 

173 :param enable_from_linting: defaults to True. Will emit a warning 

174 if a given SELECT statement is found to have un-linked FROM elements 

175 which would cause a cartesian product. 

176 

177 .. versionadded:: 1.4 

178 

179 .. seealso:: 

180 

181 :ref:`change_4737` 

182 

183 :param encoding: **legacy Python 2 value only, where it only applies to 

184 specific DBAPIs, not used in Python 3 for any modern DBAPI driver. 

185 Please refer to individual dialect documentation for client encoding 

186 behaviors.** Defaults to the string value ``utf-8``. This value 

187 refers **only** to the character encoding that is used when SQLAlchemy 

188 sends or receives data from a :term:`DBAPI` that does not support 

189 Python Unicode and **is only used under Python 2**, only for certain 

190 DBAPI drivers, and only in certain circumstances. **Python 3 users 

191 please DISREGARD this parameter and refer to the documentation for the 

192 specific dialect in use in order to configure character encoding 

193 behavior.** 

194 

195 .. note:: The ``encoding`` parameter deals only with in-Python 

196 encoding issues that were prevalent with **some DBAPIS only** 

197 under **Python 2 only**. Under Python 3 it is not used by 

198 any modern dialect. For DBAPIs that require 

199 client encoding configurations, which are most of those outside 

200 of SQLite, please consult specific :ref:`dialect documentation 

201 <dialect_toplevel>` for details. 

202 

203 All modern DBAPIs that work in Python 3 necessarily feature direct 

204 support for Python unicode strings. Under Python 2, this was not 

205 always the case. For those scenarios where the DBAPI is detected as 

206 not supporting a Python ``unicode`` object under Python 2, this 

207 encoding is used to determine the source/destination encoding. It is 

208 **not used** for those cases where the DBAPI handles unicode directly. 

209 

210 To properly configure a system to accommodate Python ``unicode`` 

211 objects, the DBAPI should be configured to handle unicode to the 

212 greatest degree as is appropriate - see the notes on unicode pertaining 

213 to the specific target database in use at :ref:`dialect_toplevel`. 

214 

215 Areas where string encoding may need to be accommodated 

216 outside of the DBAPI, nearly always under **Python 2 only**, 

217 include zero or more of: 

218 

219 * the values passed to bound parameters, corresponding to 

220 the :class:`.Unicode` type or the :class:`.String` type 

221 when ``convert_unicode`` is ``True``; 

222 * the values returned in result set columns corresponding 

223 to the :class:`.Unicode` type or the :class:`.String` 

224 type when ``convert_unicode`` is ``True``; 

225 * the string SQL statement passed to the DBAPI's 

226 ``cursor.execute()`` method; 

227 * the string names of the keys in the bound parameter 

228 dictionary passed to the DBAPI's ``cursor.execute()`` 

229 as well as ``cursor.setinputsizes()`` methods; 

230 * the string column names retrieved from the DBAPI's 

231 ``cursor.description`` attribute. 

232 

233 When using Python 3, the DBAPI is required to support all of the above 

234 values as Python ``unicode`` objects, which in Python 3 are just known 

235 as ``str``. In Python 2, the DBAPI does not specify unicode behavior 

236 at all, so SQLAlchemy must make decisions for each of the above values 

237 on a per-DBAPI basis - implementations are completely inconsistent in 

238 their behavior. 

239 

240 :param execution_options: Dictionary execution options which will 

241 be applied to all connections. See 

242 :meth:`~sqlalchemy.engine.Connection.execution_options` 

243 

244 :param future: Use the 2.0 style :class:`_future.Engine` and 

245 :class:`_future.Connection` API. 

246 

247 .. versionadded:: 1.4 

248 

249 .. seealso:: 

250 

251 :ref:`migration_20_toplevel` 

252 

253 :param hide_parameters: Boolean, when set to True, SQL statement parameters 

254 will not be displayed in INFO logging nor will they be formatted into 

255 the string representation of :class:`.StatementError` objects. 

256 

257 .. versionadded:: 1.3.8 

258 

259 .. seealso:: 

260 

261 :ref:`dbengine_logging` - further detail on how to configure 

262 logging. 

263 

264 :param implicit_returning=True: Legacy flag that when set to ``False`` 

265 will disable the use of ``RETURNING`` on supporting backends where it 

266 would normally be used to fetch newly generated primary key values for 

267 single-row INSERT statements that do not otherwise specify a RETURNING 

268 clause. This behavior applies primarily to the PostgreSQL, Oracle, 

269 SQL Server backends. 

270 

271 .. warning:: this flag originally allowed the "implicit returning" 

272 feature to be *enabled* back when it was very new and there was not 

273 well-established database support. In modern SQLAlchemy, this flag 

274 should **always be set to True**. Some SQLAlchemy features will 

275 fail to function properly if this flag is set to ``False``. 

276 

277 :param isolation_level: this string parameter is interpreted by various 

278 dialects in order to affect the transaction isolation level of the 

279 database connection. The parameter essentially accepts some subset of 

280 these string arguments: ``"SERIALIZABLE"``, ``"REPEATABLE READ"``, 

281 ``"READ COMMITTED"``, ``"READ UNCOMMITTED"`` and ``"AUTOCOMMIT"``. 

282 Behavior here varies per backend, and 

283 individual dialects should be consulted directly. 

284 

285 Note that the isolation level can also be set on a 

286 per-:class:`_engine.Connection` basis as well, using the 

287 :paramref:`.Connection.execution_options.isolation_level` 

288 feature. 

289 

290 .. seealso:: 

291 

292 :ref:`dbapi_autocommit` 

293 

294 :param json_deserializer: for dialects that support the 

295 :class:`_types.JSON` 

296 datatype, this is a Python callable that will convert a JSON string 

297 to a Python object. By default, the Python ``json.loads`` function is 

298 used. 

299 

300 .. versionchanged:: 1.3.7 The SQLite dialect renamed this from 

301 ``_json_deserializer``. 

302 

303 :param json_serializer: for dialects that support the :class:`_types.JSON` 

304 datatype, this is a Python callable that will render a given object 

305 as JSON. By default, the Python ``json.dumps`` function is used. 

306 

307 .. versionchanged:: 1.3.7 The SQLite dialect renamed this from 

308 ``_json_serializer``. 

309 

310 

311 :param label_length=None: optional integer value which limits 

312 the size of dynamically generated column labels to that many 

313 characters. If less than 6, labels are generated as 

314 "_(counter)". If ``None``, the value of 

315 ``dialect.max_identifier_length``, which may be affected via the 

316 :paramref:`_sa.create_engine.max_identifier_length` parameter, 

317 is used instead. The value of 

318 :paramref:`_sa.create_engine.label_length` 

319 may not be larger than that of 

320 :paramref:`_sa.create_engine.max_identfier_length`. 

321 

322 .. seealso:: 

323 

324 :paramref:`_sa.create_engine.max_identifier_length` 

325 

326 :param listeners: A list of one or more 

327 :class:`~sqlalchemy.interfaces.PoolListener` objects which will 

328 receive connection pool events. 

329 

330 :param logging_name: String identifier which will be used within 

331 the "name" field of logging records generated within the 

332 "sqlalchemy.engine" logger. Defaults to a hexstring of the 

333 object's id. 

334 

335 .. seealso:: 

336 

337 :ref:`dbengine_logging` - further detail on how to configure 

338 logging. 

339 

340 :paramref:`_engine.Connection.execution_options.logging_token` 

341 

342 

343 

344 :param max_identifier_length: integer; override the max_identifier_length 

345 determined by the dialect. if ``None`` or zero, has no effect. This 

346 is the database's configured maximum number of characters that may be 

347 used in a SQL identifier such as a table name, column name, or label 

348 name. All dialects determine this value automatically, however in the 

349 case of a new database version for which this value has changed but 

350 SQLAlchemy's dialect has not been adjusted, the value may be passed 

351 here. 

352 

353 .. versionadded:: 1.3.9 

354 

355 .. seealso:: 

356 

357 :paramref:`_sa.create_engine.label_length` 

358 

359 :param max_overflow=10: the number of connections to allow in 

360 connection pool "overflow", that is connections that can be 

361 opened above and beyond the pool_size setting, which defaults 

362 to five. this is only used with :class:`~sqlalchemy.pool.QueuePool`. 

363 

364 :param module=None: reference to a Python module object (the module 

365 itself, not its string name). Specifies an alternate DBAPI module to 

366 be used by the engine's dialect. Each sub-dialect references a 

367 specific DBAPI which will be imported before first connect. This 

368 parameter causes the import to be bypassed, and the given module to 

369 be used instead. Can be used for testing of DBAPIs as well as to 

370 inject "mock" DBAPI implementations into the :class:`_engine.Engine`. 

371 

372 :param paramstyle=None: The `paramstyle <https://legacy.python.org/dev/peps/pep-0249/#paramstyle>`_ 

373 to use when rendering bound parameters. This style defaults to the 

374 one recommended by the DBAPI itself, which is retrieved from the 

375 ``.paramstyle`` attribute of the DBAPI. However, most DBAPIs accept 

376 more than one paramstyle, and in particular it may be desirable 

377 to change a "named" paramstyle into a "positional" one, or vice versa. 

378 When this attribute is passed, it should be one of the values 

379 ``"qmark"``, ``"numeric"``, ``"named"``, ``"format"`` or 

380 ``"pyformat"``, and should correspond to a parameter style known 

381 to be supported by the DBAPI in use. 

382 

383 :param pool=None: an already-constructed instance of 

384 :class:`~sqlalchemy.pool.Pool`, such as a 

385 :class:`~sqlalchemy.pool.QueuePool` instance. If non-None, this 

386 pool will be used directly as the underlying connection pool 

387 for the engine, bypassing whatever connection parameters are 

388 present in the URL argument. For information on constructing 

389 connection pools manually, see :ref:`pooling_toplevel`. 

390 

391 :param poolclass=None: a :class:`~sqlalchemy.pool.Pool` 

392 subclass, which will be used to create a connection pool 

393 instance using the connection parameters given in the URL. Note 

394 this differs from ``pool`` in that you don't actually 

395 instantiate the pool in this case, you just indicate what type 

396 of pool to be used. 

397 

398 :param pool_logging_name: String identifier which will be used within 

399 the "name" field of logging records generated within the 

400 "sqlalchemy.pool" logger. Defaults to a hexstring of the object's 

401 id. 

402 

403 

404 .. seealso:: 

405 

406 :ref:`dbengine_logging` - further detail on how to configure 

407 logging. 

408 

409 

410 :param pool_pre_ping: boolean, if True will enable the connection pool 

411 "pre-ping" feature that tests connections for liveness upon 

412 each checkout. 

413 

414 .. versionadded:: 1.2 

415 

416 .. seealso:: 

417 

418 :ref:`pool_disconnects_pessimistic` 

419 

420 :param pool_size=5: the number of connections to keep open 

421 inside the connection pool. This used with 

422 :class:`~sqlalchemy.pool.QueuePool` as 

423 well as :class:`~sqlalchemy.pool.SingletonThreadPool`. With 

424 :class:`~sqlalchemy.pool.QueuePool`, a ``pool_size`` setting 

425 of 0 indicates no limit; to disable pooling, set ``poolclass`` to 

426 :class:`~sqlalchemy.pool.NullPool` instead. 

427 

428 :param pool_recycle=-1: this setting causes the pool to recycle 

429 connections after the given number of seconds has passed. It 

430 defaults to -1, or no timeout. For example, setting to 3600 

431 means connections will be recycled after one hour. Note that 

432 MySQL in particular will disconnect automatically if no 

433 activity is detected on a connection for eight hours (although 

434 this is configurable with the MySQLDB connection itself and the 

435 server configuration as well). 

436 

437 .. seealso:: 

438 

439 :ref:`pool_setting_recycle` 

440 

441 :param pool_reset_on_return='rollback': set the 

442 :paramref:`_pool.Pool.reset_on_return` parameter of the underlying 

443 :class:`_pool.Pool` object, which can be set to the values 

444 ``"rollback"``, ``"commit"``, or ``None``. 

445 

446 .. seealso:: 

447 

448 :ref:`pool_reset_on_return` 

449 

450 :param pool_timeout=30: number of seconds to wait before giving 

451 up on getting a connection from the pool. This is only used 

452 with :class:`~sqlalchemy.pool.QueuePool`. This can be a float but is 

453 subject to the limitations of Python time functions which may not be 

454 reliable in the tens of milliseconds. 

455 

456 .. note: don't use 30.0 above, it seems to break with the :param tag 

457 

458 :param pool_use_lifo=False: use LIFO (last-in-first-out) when retrieving 

459 connections from :class:`.QueuePool` instead of FIFO 

460 (first-in-first-out). Using LIFO, a server-side timeout scheme can 

461 reduce the number of connections used during non- peak periods of 

462 use. When planning for server-side timeouts, ensure that a recycle or 

463 pre-ping strategy is in use to gracefully handle stale connections. 

464 

465 .. versionadded:: 1.3 

466 

467 .. seealso:: 

468 

469 :ref:`pool_use_lifo` 

470 

471 :ref:`pool_disconnects` 

472 

473 :param plugins: string list of plugin names to load. See 

474 :class:`.CreateEnginePlugin` for background. 

475 

476 .. versionadded:: 1.2.3 

477 

478 :param query_cache_size: size of the cache used to cache the SQL string 

479 form of queries. Set to zero to disable caching. 

480 

481 The cache is pruned of its least recently used items when its size reaches 

482 N * 1.5. Defaults to 500, meaning the cache will always store at least 

483 500 SQL statements when filled, and will grow up to 750 items at which 

484 point it is pruned back down to 500 by removing the 250 least recently 

485 used items. 

486 

487 Caching is accomplished on a per-statement basis by generating a 

488 cache key that represents the statement's structure, then generating 

489 string SQL for the current dialect only if that key is not present 

490 in the cache. All statements support caching, however some features 

491 such as an INSERT with a large set of parameters will intentionally 

492 bypass the cache. SQL logging will indicate statistics for each 

493 statement whether or not it were pull from the cache. 

494 

495 .. note:: some ORM functions related to unit-of-work persistence as well 

496 as some attribute loading strategies will make use of individual 

497 per-mapper caches outside of the main cache. 

498 

499 

500 .. seealso:: 

501 

502 :ref:`sql_caching` 

503 

504 .. versionadded:: 1.4 

505 

506 """ # noqa 

507 

508 if "strategy" in kwargs: 

509 strat = kwargs.pop("strategy") 

510 if strat == "mock": 

511 return create_mock_engine(url, **kwargs) 

512 else: 

513 raise exc.ArgumentError("unknown strategy: %r" % strat) 

514 

515 kwargs.pop("empty_in_strategy", None) 

516 

517 # create url.URL object 

518 u = _url.make_url(url) 

519 

520 u, plugins, kwargs = u._instantiate_plugins(kwargs) 

521 

522 entrypoint = u._get_entrypoint() 

523 dialect_cls = entrypoint.get_dialect_cls(u) 

524 

525 if kwargs.pop("_coerce_config", False): 

526 

527 def pop_kwarg(key, default=None): 

528 value = kwargs.pop(key, default) 

529 if key in dialect_cls.engine_config_types: 

530 value = dialect_cls.engine_config_types[key](value) 

531 return value 

532 

533 else: 

534 pop_kwarg = kwargs.pop 

535 

536 dialect_args = {} 

537 # consume dialect arguments from kwargs 

538 for k in util.get_cls_kwargs(dialect_cls): 

539 if k in kwargs: 

540 dialect_args[k] = pop_kwarg(k) 

541 

542 dbapi = kwargs.pop("module", None) 

543 if dbapi is None: 

544 dbapi_args = {} 

545 for k in util.get_func_kwargs(dialect_cls.dbapi): 

546 if k in kwargs: 

547 dbapi_args[k] = pop_kwarg(k) 

548 dbapi = dialect_cls.dbapi(**dbapi_args) 

549 

550 dialect_args["dbapi"] = dbapi 

551 

552 dialect_args.setdefault("compiler_linting", compiler.NO_LINTING) 

553 enable_from_linting = kwargs.pop("enable_from_linting", True) 

554 if enable_from_linting: 

555 dialect_args["compiler_linting"] ^= compiler.COLLECT_CARTESIAN_PRODUCTS 

556 

557 for plugin in plugins: 

558 plugin.handle_dialect_kwargs(dialect_cls, dialect_args) 

559 

560 # create dialect 

561 dialect = dialect_cls(**dialect_args) 

562 

563 # assemble connection arguments 

564 (cargs, cparams) = dialect.create_connect_args(u) 

565 cparams.update(pop_kwarg("connect_args", {})) 

566 cargs = list(cargs) # allow mutability 

567 

568 # look for existing pool or create 

569 pool = pop_kwarg("pool", None) 

570 if pool is None: 

571 

572 def connect(connection_record=None): 

573 if dialect._has_events: 

574 for fn in dialect.dispatch.do_connect: 

575 connection = fn(dialect, connection_record, cargs, cparams) 

576 if connection is not None: 

577 return connection 

578 return dialect.connect(*cargs, **cparams) 

579 

580 creator = pop_kwarg("creator", connect) 

581 

582 poolclass = pop_kwarg("poolclass", None) 

583 if poolclass is None: 

584 poolclass = dialect.get_dialect_pool_class(u) 

585 pool_args = {"dialect": dialect} 

586 

587 # consume pool arguments from kwargs, translating a few of 

588 # the arguments 

589 translate = { 

590 "logging_name": "pool_logging_name", 

591 "echo": "echo_pool", 

592 "timeout": "pool_timeout", 

593 "recycle": "pool_recycle", 

594 "events": "pool_events", 

595 "reset_on_return": "pool_reset_on_return", 

596 "pre_ping": "pool_pre_ping", 

597 "use_lifo": "pool_use_lifo", 

598 } 

599 for k in util.get_cls_kwargs(poolclass): 

600 tk = translate.get(k, k) 

601 if tk in kwargs: 

602 pool_args[k] = pop_kwarg(tk) 

603 

604 for plugin in plugins: 

605 plugin.handle_pool_kwargs(poolclass, pool_args) 

606 

607 pool = poolclass(creator, **pool_args) 

608 else: 

609 if isinstance(pool, poollib.dbapi_proxy._DBProxy): 

610 pool = pool.get_pool(*cargs, **cparams) 

611 

612 pool._dialect = dialect 

613 

614 # create engine. 

615 if pop_kwarg("future", False): 

616 from sqlalchemy import future 

617 

618 default_engine_class = future.Engine 

619 else: 

620 default_engine_class = base.Engine 

621 

622 engineclass = kwargs.pop("_future_engine_class", default_engine_class) 

623 

624 engine_args = {} 

625 for k in util.get_cls_kwargs(engineclass): 

626 if k in kwargs: 

627 engine_args[k] = pop_kwarg(k) 

628 

629 # internal flags used by the test suite for instrumenting / proxying 

630 # engines with mocks etc. 

631 _initialize = kwargs.pop("_initialize", True) 

632 _wrap_do_on_connect = kwargs.pop("_wrap_do_on_connect", None) 

633 

634 # all kwargs should be consumed 

635 if kwargs: 

636 raise TypeError( 

637 "Invalid argument(s) %s sent to create_engine(), " 

638 "using configuration %s/%s/%s. Please check that the " 

639 "keyword arguments are appropriate for this combination " 

640 "of components." 

641 % ( 

642 ",".join("'%s'" % k for k in kwargs), 

643 dialect.__class__.__name__, 

644 pool.__class__.__name__, 

645 engineclass.__name__, 

646 ) 

647 ) 

648 

649 engine = engineclass(pool, dialect, u, **engine_args) 

650 

651 if _initialize: 

652 do_on_connect = dialect.on_connect_url(u) 

653 if do_on_connect: 

654 if _wrap_do_on_connect: 

655 do_on_connect = _wrap_do_on_connect(do_on_connect) 

656 

657 def on_connect(dbapi_connection, connection_record): 

658 do_on_connect(dbapi_connection) 

659 

660 event.listen(pool, "connect", on_connect) 

661 

662 def first_connect(dbapi_connection, connection_record): 

663 c = base.Connection( 

664 engine, 

665 connection=dbapi_connection, 

666 _has_events=False, 

667 # reconnecting will be a reentrant condition, so if the 

668 # connection goes away, Connection is then closed 

669 _allow_revalidate=False, 

670 ) 

671 c._execution_options = util.EMPTY_DICT 

672 

673 try: 

674 dialect.initialize(c) 

675 finally: 

676 # note that "invalidated" and "closed" are mutually 

677 # exclusive in 1.4 Connection. 

678 if not c.invalidated and not c.closed: 

679 # transaction is rolled back otherwise, tested by 

680 # test/dialect/postgresql/test_dialect.py 

681 # ::MiscBackendTest::test_initial_transaction_state 

682 dialect.do_rollback(c.connection) 

683 

684 # previously, the "first_connect" event was used here, which was then 

685 # scaled back if the "on_connect" handler were present. now, 

686 # since "on_connect" is virtually always present, just use 

687 # "connect" event with once_unless_exception in all cases so that 

688 # the connection event flow is consistent in all cases. 

689 event.listen( 

690 pool, "connect", first_connect, _once_unless_exception=True 

691 ) 

692 

693 dialect_cls.engine_created(engine) 

694 if entrypoint is not dialect_cls: 

695 entrypoint.engine_created(engine) 

696 

697 for plugin in plugins: 

698 plugin.engine_created(engine) 

699 

700 return engine 

701 

702 

703def engine_from_config(configuration, prefix="sqlalchemy.", **kwargs): 

704 """Create a new Engine instance using a configuration dictionary. 

705 

706 The dictionary is typically produced from a config file. 

707 

708 The keys of interest to ``engine_from_config()`` should be prefixed, e.g. 

709 ``sqlalchemy.url``, ``sqlalchemy.echo``, etc. The 'prefix' argument 

710 indicates the prefix to be searched for. Each matching key (after the 

711 prefix is stripped) is treated as though it were the corresponding keyword 

712 argument to a :func:`_sa.create_engine` call. 

713 

714 The only required key is (assuming the default prefix) ``sqlalchemy.url``, 

715 which provides the :ref:`database URL <database_urls>`. 

716 

717 A select set of keyword arguments will be "coerced" to their 

718 expected type based on string values. The set of arguments 

719 is extensible per-dialect using the ``engine_config_types`` accessor. 

720 

721 :param configuration: A dictionary (typically produced from a config file, 

722 but this is not a requirement). Items whose keys start with the value 

723 of 'prefix' will have that prefix stripped, and will then be passed to 

724 :func:`_sa.create_engine`. 

725 

726 :param prefix: Prefix to match and then strip from keys 

727 in 'configuration'. 

728 

729 :param kwargs: Each keyword argument to ``engine_from_config()`` itself 

730 overrides the corresponding item taken from the 'configuration' 

731 dictionary. Keyword arguments should *not* be prefixed. 

732 

733 """ 

734 

735 options = dict( 

736 (key[len(prefix) :], configuration[key]) 

737 for key in configuration 

738 if key.startswith(prefix) 

739 ) 

740 options["_coerce_config"] = True 

741 options.update(kwargs) 

742 url = options.pop("url") 

743 return create_engine(url, **options)