File: test_async_pg.py

package info (click to toggle)
sqlalchemy 2.0.44%2Bds1-1
  • links: PTS
  • area: main
  • in suites: forky, sid
  • size: 26,740 kB
  • sloc: python: 414,900; makefile: 231; sh: 7
file content (394 lines) | stat: -rw-r--r-- 12,352 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
import random
import uuid

from sqlalchemy import Column
from sqlalchemy import exc
from sqlalchemy import ForeignKey
from sqlalchemy import Integer
from sqlalchemy import MetaData
from sqlalchemy import select
from sqlalchemy import String
from sqlalchemy import Table
from sqlalchemy import testing
from sqlalchemy.dialects.postgresql import asyncpg as asyncpg_dialect
from sqlalchemy.dialects.postgresql import ENUM
from sqlalchemy.testing import async_test
from sqlalchemy.testing import eq_
from sqlalchemy.testing import expect_raises
from sqlalchemy.testing import fixtures
from sqlalchemy.testing import mock
from sqlalchemy.util import greenlet_spawn


class AsyncPgTest(fixtures.TestBase):
    __requires__ = ("async_dialect",)
    __only_on__ = "postgresql+asyncpg"

    @async_test
    async def test_detect_stale_ddl_cache_raise_recover(
        self, metadata, async_testing_engine
    ):
        async def async_setup(engine, strlen):
            metadata.clear()
            t1 = Table(
                "t1",
                metadata,
                Column("id", Integer, primary_key=True),
                Column("name", String(strlen)),
            )

            # conn is an instance of AsyncConnection
            async with engine.begin() as conn:
                await conn.run_sync(metadata.drop_all)
                await conn.run_sync(metadata.create_all)
                await conn.execute(
                    t1.insert(),
                    [{"name": "some name %d" % i} for i in range(500)],
                )

        meta = MetaData()

        t1 = Table(
            "t1",
            meta,
            Column("id", Integer, primary_key=True),
            Column("name", String),
        )

        first_engine = async_testing_engine()
        second_engine = async_testing_engine()

        await async_setup(first_engine, 30)

        async with second_engine.connect() as conn:
            result = await conn.execute(
                t1.select()
                .where(t1.c.name.like("some name%"))
                .where(t1.c.id % 17 == 6)
            )

            rows = result.fetchall()
            assert len(rows) >= 29

        await async_setup(first_engine, 20)

        async with second_engine.connect() as conn:
            with testing.expect_raises_message(
                exc.NotSupportedError,
                r"cached statement plan is invalid due to a database schema "
                r"or configuration change \(SQLAlchemy asyncpg dialect "
                r"will now invalidate all prepared caches in response "
                r"to this exception\)",
            ):
                result = await conn.execute(
                    t1.select()
                    .where(t1.c.name.like("some name%"))
                    .where(t1.c.id % 17 == 6)
                )

        # works again
        async with second_engine.connect() as conn:
            result = await conn.execute(
                t1.select()
                .where(t1.c.name.like("some name%"))
                .where(t1.c.id % 17 == 6)
            )

            rows = result.fetchall()
            assert len(rows) >= 29

    @async_test
    async def test_detect_stale_type_cache_raise_recover(
        self, metadata, async_testing_engine
    ):
        async def async_setup(engine, enums):
            metadata = MetaData()
            Table(
                "t1",
                metadata,
                Column("id", Integer, primary_key=True),
                Column("name", ENUM(*enums, name="my_enum")),
            )

            # conn is an instance of AsyncConnection
            async with engine.begin() as conn:
                await conn.run_sync(metadata.drop_all)
                await conn.run_sync(metadata.create_all)

        t1 = Table(
            "t1",
            metadata,
            Column("id", Integer, primary_key=True),
            Column(
                "name",
                ENUM(
                    *("beans", "means", "keens", "faux", "beau", "flow"),
                    name="my_enum",
                ),
            ),
        )

        first_engine = async_testing_engine()
        second_engine = async_testing_engine(
            options={"connect_args": {"prepared_statement_cache_size": 0}}
        )

        await async_setup(first_engine, ("beans", "means", "keens"))

        async with second_engine.connect() as conn:
            await conn.execute(
                t1.insert(),
                [
                    {"name": random.choice(("beans", "means", "keens"))}
                    for i in range(10)
                ],
            )

        await async_setup(first_engine, ("faux", "beau", "flow"))

        async with second_engine.connect() as conn:
            with testing.expect_raises_message(
                exc.InternalError, "cache lookup failed for type"
            ):
                await conn.execute(
                    t1.insert(),
                    [
                        {"name": random.choice(("faux", "beau", "flow"))}
                        for i in range(10)
                    ],
                )

        # works again
        async with second_engine.connect() as conn:
            await conn.execute(
                t1.insert(),
                [
                    {"name": random.choice(("faux", "beau", "flow"))}
                    for i in range(10)
                ],
            )

    @testing.combinations(
        None,
        "read committed",
        "repeatable read",
        "serializable",
        argnames="isolation_level",
    )
    @async_test
    async def test_honor_server_level_iso_setting(
        self, async_testing_engine, isolation_level
    ):
        """test for #12159"""

        engine = async_testing_engine()

        arg, kw = engine.dialect.create_connect_args(engine.url)

        # 1. create an asyncpg.connection directly, set a session level
        #    isolation level on it (this is similar to server default isolation
        #    level)
        raw_asyncpg_conn = await engine.dialect.dbapi.asyncpg.connect(
            *arg, **kw
        )

        if isolation_level:
            await raw_asyncpg_conn.execute(
                f"set SESSION CHARACTERISTICS AS TRANSACTION "
                f"isolation level {isolation_level}"
            )

        # 2. fetch it, confirm the setting took and matches
        raw_iso_level = (
            await raw_asyncpg_conn.fetchrow("show transaction isolation level")
        )[0]
        if isolation_level:
            eq_(raw_iso_level, isolation_level.lower())

        # 3.build our pep-249 wrapper around asyncpg.connection
        dbapi_conn = asyncpg_dialect.AsyncAdapt_asyncpg_connection(
            engine.dialect.dbapi,
            raw_asyncpg_conn,
        )

        # 4. show the isolation level inside of a query.  this will
        #    call asyncpg.connection.transaction() in order to run the
        #    statement.
        cursor = await greenlet_spawn(dbapi_conn.cursor)
        await greenlet_spawn(
            cursor.execute, "show transaction isolation level"
        )
        row = cursor.fetchone()

        # 5. see that the raw iso level is maintained
        eq_(row[0], raw_iso_level)

        await greenlet_spawn(dbapi_conn.close)

    @testing.variation("trans", ["commit", "rollback"])
    @async_test
    async def test_dont_reset_open_transaction(
        self, trans, async_testing_engine
    ):
        """test for #11819"""

        engine = async_testing_engine()

        control_conn = await engine.connect()
        await control_conn.execution_options(isolation_level="AUTOCOMMIT")

        conn = await engine.connect()
        txid_current = (
            await conn.exec_driver_sql("select txid_current()")
        ).scalar()

        with expect_raises(exc.MissingGreenlet):
            if trans.commit:
                conn.sync_connection.connection.dbapi_connection.commit()
            elif trans.rollback:
                conn.sync_connection.connection.dbapi_connection.rollback()
            else:
                trans.fail()

        trans_exists = (
            await control_conn.exec_driver_sql(
                f"SELECT count(*) FROM pg_stat_activity "
                f"where backend_xid={txid_current}"
            )
        ).scalar()
        eq_(trans_exists, 1)

        if trans.commit:
            await conn.commit()
        elif trans.rollback:
            await conn.rollback()
        else:
            trans.fail()

        trans_exists = (
            await control_conn.exec_driver_sql(
                f"SELECT count(*) FROM pg_stat_activity "
                f"where backend_xid={txid_current}"
            )
        ).scalar()
        eq_(trans_exists, 0)
        await engine.dispose()

    @async_test
    async def test_failed_commit_recover(self, metadata, async_testing_engine):
        Table("t1", metadata, Column("id", Integer, primary_key=True))

        t2 = Table(
            "t2",
            metadata,
            Column("id", Integer, primary_key=True),
            Column(
                "t1_id",
                Integer,
                ForeignKey("t1.id", deferrable=True, initially="deferred"),
            ),
        )

        engine = async_testing_engine()

        async with engine.connect() as conn:
            await conn.run_sync(metadata.create_all)

            await conn.execute(t2.insert().values(id=1, t1_id=2))

            with testing.expect_raises_message(
                exc.IntegrityError, 'insert or update on table "t2"'
            ):
                await conn.commit()

            await conn.rollback()

            eq_((await conn.execute(select(1))).scalar(), 1)

    @async_test
    async def test_rollback_twice_no_problem(
        self, metadata, async_testing_engine
    ):
        engine = async_testing_engine()

        async with engine.connect() as conn:
            trans = await conn.begin()

            await trans.rollback()

            await conn.rollback()

    @async_test
    async def test_closed_during_execute(self, metadata, async_testing_engine):
        engine = async_testing_engine()

        async with engine.connect() as conn:
            await conn.begin()

            with testing.expect_raises_message(
                exc.DBAPIError, "connection was closed"
            ):
                await conn.exec_driver_sql(
                    "select pg_terminate_backend(pg_backend_pid())"
                )

    @async_test
    async def test_failed_rollback_recover(
        self, metadata, async_testing_engine
    ):
        engine = async_testing_engine()

        async with engine.connect() as conn:
            await conn.begin()

            (await conn.execute(select(1))).scalar()

            raw_connection = await conn.get_raw_connection()
            # close the asyncpg transaction directly
            await raw_connection._transaction.rollback()

            with testing.expect_raises_message(
                exc.InterfaceError, "already rolled back"
            ):
                await conn.rollback()

            # recovers no problem

            await conn.begin()
            await conn.rollback()

    @testing.combinations(
        "setup_asyncpg_json_codec",
        "setup_asyncpg_jsonb_codec",
        argnames="methname",
    )
    @testing.requires.python38
    @async_test
    async def test_codec_registration(
        self, metadata, async_testing_engine, methname
    ):
        """test new hooks added for #7284"""

        engine = async_testing_engine()
        with mock.patch.object(engine.dialect, methname) as codec_meth:
            conn = await engine.connect()
            adapted_conn = (await conn.get_raw_connection()).dbapi_connection
            await conn.close()

        eq_(codec_meth.mock_calls, [mock.call(adapted_conn)])

    @async_test
    async def test_name_connection_func(self, metadata, async_testing_engine):
        cache = []

        def name_f():
            name = str(uuid.uuid4())
            cache.append(name)
            return name

        engine = async_testing_engine(
            options={"connect_args": {"prepared_statement_name_func": name_f}},
        )
        async with engine.begin() as conn:
            await conn.execute(select(1))
            assert len(cache) > 0