summaryrefslogtreecommitdiff
path: root/test/dialect/postgresql/test_async_pg_py3k.py
blob: 49014fcaf94144c1414803693ecefc24bdcf55b2 (plain)
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
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 ENUM
from sqlalchemy.testing import async_test
from sqlalchemy.testing import eq_
from sqlalchemy.testing import fixtures
from sqlalchemy.testing import mock


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)
                ],
            )

    @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