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

116 statements  

« prev     ^ index     » next       coverage.py v7.2.7, created at 2023-06-07 06:35 +0000

1# engine/create.py 

2# Copyright (C) 2005-2023 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 logging_name: String identifier which will be used within 

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

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

329 object's id. 

330 

331 .. seealso:: 

332 

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

334 logging. 

335 

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

337 

338 

339 

340 :param max_identifier_length: integer; override the max_identifier_length 

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

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

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

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

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

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

347 here. 

348 

349 .. versionadded:: 1.3.9 

350 

351 .. seealso:: 

352 

353 :paramref:`_sa.create_engine.label_length` 

354 

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

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

357 opened above and beyond the pool_size setting, which defaults 

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

359 

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

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

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

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

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

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

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

367 

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

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

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

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

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

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

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

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

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

377 to be supported by the DBAPI in use. 

378 

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

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

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

382 pool will be used directly as the underlying connection pool 

383 for the engine, bypassing whatever connection parameters are 

384 present in the URL argument. For information on constructing 

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

386 

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

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

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

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

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

392 of pool to be used. 

393 

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

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

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

397 id. 

398 

399 

400 .. seealso:: 

401 

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

403 logging. 

404 

405 

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

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

408 each checkout. 

409 

410 .. versionadded:: 1.2 

411 

412 .. seealso:: 

413 

414 :ref:`pool_disconnects_pessimistic` 

415 

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

417 inside the connection pool. This used with 

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

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

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

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

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

423 

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

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

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

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

428 MySQL in particular will disconnect automatically if no 

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

430 this is configurable with the MySQLDB connection itself and the 

431 server configuration as well). 

432 

433 .. seealso:: 

434 

435 :ref:`pool_setting_recycle` 

436 

437 :param pool_reset_on_return='rollback': set the 

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

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

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

441 

442 .. seealso:: 

443 

444 :ref:`pool_reset_on_return` 

445 

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

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

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

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

450 reliable in the tens of milliseconds. 

451 

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

453 

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

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

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

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

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

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

460 

461 .. versionadded:: 1.3 

462 

463 .. seealso:: 

464 

465 :ref:`pool_use_lifo` 

466 

467 :ref:`pool_disconnects` 

468 

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

470 :class:`.CreateEnginePlugin` for background. 

471 

472 .. versionadded:: 1.2.3 

473 

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

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

476 

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

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

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

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

481 used items. 

482 

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

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

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

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

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

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

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

490 

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

492 as some attribute loading strategies will make use of individual 

493 per-mapper caches outside of the main cache. 

494 

495 

496 .. seealso:: 

497 

498 :ref:`sql_caching` 

499 

500 .. versionadded:: 1.4 

501 

502 """ # noqa 

503 

504 if "strategy" in kwargs: 

505 strat = kwargs.pop("strategy") 

506 if strat == "mock": 

507 return create_mock_engine(url, **kwargs) 

508 else: 

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

510 

511 kwargs.pop("empty_in_strategy", None) 

512 

513 # create url.URL object 

514 u = _url.make_url(url) 

515 

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

517 

518 entrypoint = u._get_entrypoint() 

519 dialect_cls = entrypoint.get_dialect_cls(u) 

520 

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

522 

523 def pop_kwarg(key, default=None): 

524 value = kwargs.pop(key, default) 

525 if key in dialect_cls.engine_config_types: 

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

527 return value 

528 

529 else: 

530 pop_kwarg = kwargs.pop 

531 

532 dialect_args = {} 

533 # consume dialect arguments from kwargs 

534 for k in util.get_cls_kwargs(dialect_cls): 

535 if k in kwargs: 

536 dialect_args[k] = pop_kwarg(k) 

537 

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

539 if dbapi is None: 

540 dbapi_args = {} 

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

542 if k in kwargs: 

543 dbapi_args[k] = pop_kwarg(k) 

544 dbapi = dialect_cls.dbapi(**dbapi_args) 

545 

546 dialect_args["dbapi"] = dbapi 

547 

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

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

550 if enable_from_linting: 

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

552 

553 for plugin in plugins: 

554 plugin.handle_dialect_kwargs(dialect_cls, dialect_args) 

555 

556 # create dialect 

557 dialect = dialect_cls(**dialect_args) 

558 

559 # assemble connection arguments 

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

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

562 cargs = list(cargs) # allow mutability 

563 

564 # look for existing pool or create 

565 pool = pop_kwarg("pool", None) 

566 if pool is None: 

567 

568 def connect(connection_record=None): 

569 if dialect._has_events: 

570 for fn in dialect.dispatch.do_connect: 

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

572 if connection is not None: 

573 return connection 

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

575 

576 creator = pop_kwarg("creator", connect) 

577 

578 poolclass = pop_kwarg("poolclass", None) 

579 if poolclass is None: 

580 poolclass = dialect.get_dialect_pool_class(u) 

581 pool_args = {"dialect": dialect} 

582 

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

584 # the arguments 

585 translate = { 

586 "logging_name": "pool_logging_name", 

587 "echo": "echo_pool", 

588 "timeout": "pool_timeout", 

589 "recycle": "pool_recycle", 

590 "events": "pool_events", 

591 "reset_on_return": "pool_reset_on_return", 

592 "pre_ping": "pool_pre_ping", 

593 "use_lifo": "pool_use_lifo", 

594 } 

595 for k in util.get_cls_kwargs(poolclass): 

596 tk = translate.get(k, k) 

597 if tk in kwargs: 

598 pool_args[k] = pop_kwarg(tk) 

599 

600 for plugin in plugins: 

601 plugin.handle_pool_kwargs(poolclass, pool_args) 

602 

603 pool = poolclass(creator, **pool_args) 

604 else: 

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

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

607 

608 pool._dialect = dialect 

609 

610 # create engine. 

611 if pop_kwarg("future", False): 

612 from sqlalchemy import future 

613 

614 default_engine_class = future.Engine 

615 else: 

616 default_engine_class = base.Engine 

617 

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

619 

620 engine_args = {} 

621 for k in util.get_cls_kwargs(engineclass): 

622 if k in kwargs: 

623 engine_args[k] = pop_kwarg(k) 

624 

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

626 # engines with mocks etc. 

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

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

629 

630 # all kwargs should be consumed 

631 if kwargs: 

632 raise TypeError( 

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

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

635 "keyword arguments are appropriate for this combination " 

636 "of components." 

637 % ( 

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

639 dialect.__class__.__name__, 

640 pool.__class__.__name__, 

641 engineclass.__name__, 

642 ) 

643 ) 

644 

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

646 

647 if _initialize: 

648 do_on_connect = dialect.on_connect_url(u) 

649 if do_on_connect: 

650 if _wrap_do_on_connect: 

651 do_on_connect = _wrap_do_on_connect(do_on_connect) 

652 

653 def on_connect(dbapi_connection, connection_record): 

654 do_on_connect(dbapi_connection) 

655 

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

657 

658 def first_connect(dbapi_connection, connection_record): 

659 c = base.Connection( 

660 engine, 

661 connection=dbapi_connection, 

662 _has_events=False, 

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

664 # connection goes away, Connection is then closed 

665 _allow_revalidate=False, 

666 ) 

667 c._execution_options = util.EMPTY_DICT 

668 

669 try: 

670 dialect.initialize(c) 

671 finally: 

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

673 # exclusive in 1.4 Connection. 

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

675 # transaction is rolled back otherwise, tested by 

676 # test/dialect/postgresql/test_dialect.py 

677 # ::MiscBackendTest::test_initial_transaction_state 

678 dialect.do_rollback(c.connection) 

679 

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

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

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

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

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

685 event.listen( 

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

687 ) 

688 

689 dialect_cls.engine_created(engine) 

690 if entrypoint is not dialect_cls: 

691 entrypoint.engine_created(engine) 

692 

693 for plugin in plugins: 

694 plugin.engine_created(engine) 

695 

696 return engine 

697 

698 

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

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

701 

702 The dictionary is typically produced from a config file. 

703 

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

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

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

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

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

709 

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

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

712 

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

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

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

716 

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

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

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

720 :func:`_sa.create_engine`. 

721 

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

723 in 'configuration'. 

724 

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

726 overrides the corresponding item taken from the 'configuration' 

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

728 

729 """ 

730 

731 options = dict( 

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

733 for key in configuration 

734 if key.startswith(prefix) 

735 ) 

736 options["_coerce_config"] = True 

737 options.update(kwargs) 

738 url = options.pop("url") 

739 return create_engine(url, **options)