summaryrefslogtreecommitdiff
path: root/lib/sqlalchemy/dialects/postgresql/asyncpg.py
Commit message (Collapse)AuthorAgeFilesLines
...
* reinvent xdist hooks in terms of pytest fixturesMike Bayer2021-01-131-1/+0
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | To allow the "connection" pytest fixture and others work correctly in conjunction with setup/teardown that expects to be external to the transaction, remove and prevent any usage of "xdist" style names that are hardcoded by pytest to run inside of fixtures, even function level ones. Instead use pytest autouse fixtures to implement our own r"setup|teardown_test(?:_class)?" methods so that we can ensure function-scoped fixtures are run within them. A new more explicit flow is set up within plugin_base and pytestplugin such that the order of setup/teardown steps, which there are now many, is fully documented and controllable. New granularity has been added to the test teardown phase to distinguish between "end of the test" when lock-holding structures on connections should be released to allow for table drops, vs. "end of the test plus its teardown steps" when we can perform final cleanup on connections and run assertions that everything is closed out. From there we can remove most of the defensive "tear down everything" logic inside of engines which for many years would frequently dispose of pools over and over again, creating for a broken and expensive connection flow. A quick test shows that running test/sql/ against a single Postgresql engine with the new approach uses 75% fewer new connections, creating 42 new connections total, vs. 164 new connections total with the previous system. As part of this, the new fixtures metadata/connection/future_connection have been integrated such that they can be combined together effectively. The fixture_session(), provide_metadata() fixtures have been improved, including that fixture_session() now strongly references sessions which are explicitly torn down before table drops occur afer a test. Major changes have been made to the ConnectionKiller such that it now features different "scopes" for testing engines and will limit its cleanup to those testing engines corresponding to end of test, end of test class, or end of test session. The system by which it tracks DBAPI connections has been reworked, is ultimately somewhat similar to how it worked before but is organized more clearly along with the proxy-tracking logic. A "testing_engine" fixture is also added that works as a pytest fixture rather than a standalone function. The connection cleanup logic should now be very robust, as we now can use the same global connection pools for the whole suite without ever disposing them, while also running a query for PostgreSQL locks remaining after every test and assert there are no open transactions leaking between tests at all. Additional steps are added that also accommodate for asyncio connections not explicitly closed, as is the case for legacy sync-style tests as well as the async tests themselves. As always, hundreds of tests are further refined to use the new fixtures where problems with loose connections were identified, largely as a result of the new PostgreSQL assertions, many more tests have moved from legacy patterns into the newest. An unfortunate discovery during the creation of this system is that autouse fixtures (as well as if they are set up by @pytest.mark.usefixtures) are not usable at our current scale with pytest 4.6.11 running under Python 2. It's unclear if this is due to the older version of pytest or how it implements itself for Python 2, as well as if the issue is CPU slowness or just large memory use, but collecting the full span of tests takes over a minute for a single process when any autouse fixtures are in place and on CI the jobs just time out after ten minutes. So at the moment this patch also reinvents a small version of "autouse" fixtures when py2k is running, which skips generating the real fixture and instead uses two global pytest fixtures (which don't seem to impact performance) to invoke the "autouse" fixtures ourselves outside of pytest. This will limit our ability to do more with fixtures until we can remove py2k support. py.test is still observed to be much slower in collection in the 4.6.11 version compared to modern 6.2 versions, so add support for new TOX_POSTGRESQL_PY2K and TOX_MYSQL_PY2K environment variables that will run the suite for fewer backends under Python 2. For Python 3 pin pytest to modern 6.2 versions where performance for collection has been improved greatly. Includes the following improvements: Fixed bug in asyncio connection pool where ``asyncio.TimeoutError`` would be raised rather than :class:`.exc.TimeoutError`. Also repaired the :paramref:`_sa.create_engine.pool_timeout` parameter set to zero when using the async engine, which previously would ignore the timeout and block rather than timing out immediately as is the behavior with regular :class:`.QueuePool`. For asyncio the connection pool will now also not interact at all with an asyncio connection whose ConnectionFairy is being garbage collected; a warning that the connection was not properly closed is emitted and the connection is discarded. Within the test suite the ConnectionKiller is now maintaining strong references to all DBAPI connections and ensuring they are released when tests end, including those whose ConnectionFairy proxies are GCed. Identified cx_Oracle.stmtcachesize as a major factor in Oracle test scalability issues, this can be reset on a per-test basis rather than setting it to zero across the board. the addition of this flag has resolved the long-standing oracle "two task" error problem. For SQL Server, changed the temp table style used by the "suite" tests to be the double-pound-sign, i.e. global, variety, which is much easier to test generically. There are already reflection tests that are more finely tuned to both styles of temp table within the mssql test suite. Additionally, added an extra step to the "dropfirst" mechanism for SQL Server that will remove all foreign key constraints first as some issues were observed when using this flag when multiple schemas had not been torn down. Identified and fixed two subtle failure modes in the engine, when commit/rollback fails in a begin() context manager, the connection is explicitly closed, and when "initialize()" fails on the first new connection of a dialect, the transactional state on that connection is still rolled back. Fixes: #5826 Fixes: #5827 Change-Id: Ib1d05cb8c7cf84f9a4bfd23df397dc23c9329bfe
* happy new yearMike Bayer2021-01-041-1/+1
| | | | Change-Id: Ic5bb19ca8be3cb47c95a0d3315d84cb484bac47c
* Cache asyngpg prepared statementsMike Bayer2021-01-021-21/+157
| | | | | | | | | | | | | | | | | Enhanced the performance of the asyncpg dialect by caching the asyncpg PreparedStatement objects on a per-connection basis. For a test case that makes use of the same statement on a set of pooled connections this appears to grant a 10-20% speed improvement. The cache size is adjustable and may also be disabled. Unfortunately the caching gets more complicated when there are schema changes present. An invalidation scheme is now also added to accommodate for prepared statements as well as asyncpg cached OIDs. However, the exception raises cannot be prevented if DDL has changed database structures that were cached for a particular asyncpg connection. Logic is added to clear the caches when these errors occur. Change-Id: Icf02aa4871eb192f245690f28be4e9f9c35656c6
* Support testing of async drivers without fallback modeFederico Caselli2020-12-301-3/+10
| | | | Change-Id: I4940d184a4dc790782fcddfb9873af3cca844398
* Make sure asyncpgfallback has __slots__Mike Bayer2020-12-011-0/+3
| | | | | | | | | | | | the test suite failed to find that we started accessing a non-existent slot "_isolation_setting" added by me in 9b779611f9, as the test suite makes use of the AsyncAdaptFallback_asyncpg_connection subclass, which didn't include __slots__ and therefore didn't catch that _isolation_setting wasn't added to slots. Fixes: #5739 Change-Id: Ibbbedc2ee0f1d1c9d91ba7898d755812deccb380
* Support pool.connect() event firing before all elseMike Bayer2020-11-191-2/+13
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | Fixed regression where a connection pool event specified with a keyword, most notably ``insert=True``, would be lost when the event were set up. This would prevent startup events that need to fire before dialect-level events from working correctly. The internal mechanics of the engine connection routine has been altered such that it's now guaranteed that a user-defined event handler for the :meth:`_pool.PoolEvents.connect` handler, when established using ``insert=True``, will allow an event handler to run that is definitely invoked **before** any dialect-specific initialization starts up, most notably when it does things like detect default schema name. Previously, this would occur in most cases but not unconditionally. A new example is added to the schema documentation illustrating how to establish the "default schema name" within an on-connect event (upcoming as part of I882edd5bbe06ee5b4d0a9c148854a57b2bcd4741) Addiional changes to support setting default schema name: The Oracle dialect now uses ``select sys_context( 'userenv', 'current_schema' ) from dual`` to get the default schema name, rather than ``SELECT USER FROM DUAL``, to accommodate for changes to the session-local schema name under Oracle. Added a read/write ``.autocommit`` attribute to the DBAPI-adaptation layer for the asyncpg dialect. This so that when working with DBAPI-specific schemes that need to use "autocommit" directly with the DBAPI connection, the same ``.autocommit`` attribute which works with both psycopg2 as well as pg8000 is available. Fixes: #5716 Fixes: #5708 Change-Id: I7dce56b4345ffc720e25e2aaccb7e42bb29e5671
* s/craete/create/gThomas Grainger2020-11-101-1/+1
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | <!-- Provide a general summary of your proposed changes in the Title field above --> ### Description it's a typo fix ### Checklist <!-- go over following points. check them with an `x` if they do apply, (they turn into clickable checkboxes once the PR is submitted, so no need to do everything at once) --> This pull request is: - [x] A documentation / typographical error fix - Good to go, no issue or tests are needed - [ ] A short code fix - please include the issue number, and create an issue if none exists, which must include a complete example of the issue. one line code fixes without an issue and demonstration will not be accepted. - Please include: `Fixes: #<issue number>` in the commit message - please include tests. one line code fixes without tests will not be accepted. - [ ] A new feature implementation - please include the issue number, and create an issue if none exists, which must include a complete example of how the feature would look. - Please include: `Fixes: #<issue number>` in the commit message - please include tests. **Have a nice day!** Closes: #5689 Pull-request: https://github.com/sqlalchemy/sqlalchemy/pull/5689 Pull-request-sha: 3823b2552da2a7b7a345979ad6283d848c0ec7a5 Change-Id: I170e7bea60182ebec8867499b2ea171d813fc49a
* Genericize setinputsizes and support pyodbcMike Bayer2020-10-161-1/+17
| | | | | | | | | | | | Reworked the "setinputsizes()" set of dialect hooks to be correctly extensible for any arbirary DBAPI, by allowing dialects individual hooks that may invoke cursor.setinputsizes() in the appropriate style for that DBAPI. In particular this is intended to support pyodbc's style of usage which is fundamentally different from that of cx_Oracle. Added support for pyodbc. Fixes: #5649 Change-Id: I9f1794f8368bf3663a286932cfe3992dae244a10
* Fetch first supportFederico Caselli2020-10-021-1/+0
| | | | | | | | | Add support to ``FETCH {FIRST | NEXT} [ count ] {ROW | ROWS} {ONLY | WITH TIES}`` in the select for the supported backends, currently PostgreSQL, Oracle and MSSQL. Fixes: #5576 Change-Id: Ibb5871a457c0555f82b37e354e7787d15575f1f7
* upgrade to black 20.8b1Mike Bayer2020-09-281-2/+4
| | | | | | | It's better, the majority of these changes look more readable to me. also found some docstrings that had formatting / quoting issues. Change-Id: I582a45fde3a5648b2f36bab96bad56881321899b
* Improve Asyncpg json handlingFederico Caselli2020-09-231-11/+67
| | | | | | | | | Set default type codec for ``json`` and ``jsonb`` types when using the asyncpg driver. By default asyncpg will not decode them and return strings instead. Fixes: #5584 Change-Id: I41348eff8096ccf87b952d7e797c0694c6c4b5c4
* Don't change asyncpg's "char" codecMike Bayer2020-09-161-19/+4
| | | | | | | | | | | | | | This codec was used to ensure the "pg_attribute.generated" column comes back as a string and not bytes, matching how other PG drivers treat this datatype. However, this breaks asyncpg's internal implementation of set_type_codec going forward and the "char" datatype is actually a bytes in any case. So at the moment it appears psycopg2/pg8000 are broken for mis-treatment of the datatype and asyncpg is broken in that it was allowing us to change a codec that it appears to rely upon internally. Fixes: #5586 Change-Id: I937eba315904721aa4e2726b95432910a8affe5f
* Deprecate engine-wise ss cursors; repair mariadbconnectorMike Bayer2020-09-131-4/+0
| | | | | | | | | | | | | | | | | | | The server_side_cursors engine-wide feature relies upon regexp parsing of statements a well as general guessing as to when the feature should be used. This is not within the 2.0 way of doing things and should be removed. Additionally, mariadbconnector defaults to unbuffered cursors; add new cursor hooks so that mariadbconnector can specify buffered or unbuffered cursors without too much difficulty. This will also correctly default mariadbconnector to buffered cursors which should repair the segfaults we've been getting. Try to restore the assert_raises that was removed in 5b6dfc0c38bf1f01da4b8 to see if mariadbconnector segfaults are resolved. Change-Id: I77f1c972c742e40694972f578140bb0cac8c39eb
* Create connection characteristics API; implement postgresql flagsMike Bayer2020-09-081-1/+19
| | | | | | | | | | | Added support for PostgreSQL "readonly" and "deferrable" flags for all of psycopg2, asyncpg and pg8000 dialects. This takes advantage of a newly generalized version of the "isolation level" API to support other kinds of session attributes set via execution options that are reliably reset when connections are returned to the connection pool. Fixes: #5549 Change-Id: I0ad6d7a095e49d331618274c40ce75c76afdc7dd
* Implement rudimentary asyncio support w/ asyncpgMike Bayer2020-08-131-0/+786
Using the approach introduced at https://gist.github.com/zzzeek/6287e28054d3baddc07fa21a7227904e We can now create asyncio endpoints that are then handled in "implicit IO" form within the majority of the Core internals. Then coroutines are re-exposed at the point at which we call into asyncpg methods. Patch includes: * asyncpg dialect * asyncio package * engine, result, ORM session classes * new test fixtures, tests * some work with pep-484 and a short plugin for the pyannotate package, which seems to have so-so results Change-Id: Idbcc0eff72c4cad572914acdd6f40ddb1aef1a7d Fixes: #3414