forked from MagicStack/asyncpg
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest_prepare.py
602 lines (460 loc) · 21.2 KB
/
test_prepare.py
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
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
# Copyright (C) 2016-present the asyncpg authors and contributors
# <see AUTHORS file>
#
# This module is part of asyncpg and is released under
# the Apache 2.0 License: http://www.apache.org/licenses/LICENSE-2.0
import asyncio
import asyncpg
import gc
import unittest
from asyncpg import _testbase as tb
from asyncpg import exceptions
class TestPrepare(tb.ConnectedTestCase):
async def test_prepare_01(self):
self.assertEqual(self.con._protocol.queries_count, 0)
st = await self.con.prepare('SELECT 1 = $1 AS test')
self.assertEqual(self.con._protocol.queries_count, 0)
self.assertEqual(st.get_query(), 'SELECT 1 = $1 AS test')
rec = await st.fetchrow(1)
self.assertEqual(self.con._protocol.queries_count, 1)
self.assertTrue(rec['test'])
self.assertEqual(len(rec), 1)
self.assertEqual(False, await st.fetchval(10))
self.assertEqual(self.con._protocol.queries_count, 2)
async def test_prepare_02(self):
with self.assertRaisesRegex(Exception, 'column "a" does not exist'):
await self.con.prepare('SELECT a')
async def test_prepare_03(self):
cases = [
('text', ("'NULL'", 'NULL'), [
'aaa',
None
]),
('decimal', ('0', 0), [
123,
123.5,
None
])
]
for type, (none_name, none_val), vals in cases:
st = await self.con.prepare('''
SELECT CASE WHEN $1::{type} IS NULL THEN {default}
ELSE $1::{type} END'''.format(
type=type, default=none_name))
for val in vals:
with self.subTest(type=type, value=val):
res = await st.fetchval(val)
if val is None:
self.assertEqual(res, none_val)
else:
self.assertEqual(res, val)
async def test_prepare_04(self):
s = await self.con.prepare('SELECT $1::smallint')
self.assertEqual(await s.fetchval(10), 10)
s = await self.con.prepare('SELECT $1::smallint * 2')
self.assertEqual(await s.fetchval(10), 20)
s = await self.con.prepare('SELECT generate_series(5,10)')
self.assertEqual(await s.fetchval(), 5)
# Since the "execute" message was sent with a limit=1,
# we will receive a PortalSuspended message, instead of
# CommandComplete. Which means there will be no status
# message set.
self.assertIsNone(s.get_statusmsg())
# Repeat the same test for 'fetchrow()'.
self.assertEqual(await s.fetchrow(), (5,))
self.assertIsNone(s.get_statusmsg())
async def test_prepare_05_unknownoid(self):
s = await self.con.prepare("SELECT 'test'")
self.assertEqual(await s.fetchval(), 'test')
async def test_prepare_06_interrupted_close(self):
stmt = await self.con.prepare('''SELECT pg_sleep(10)''')
fut = self.loop.create_task(stmt.fetch())
await asyncio.sleep(0.2)
self.assertFalse(self.con.is_closed())
await self.con.close()
self.assertTrue(self.con.is_closed())
with self.assertRaises(asyncpg.QueryCanceledError):
await fut
# Test that it's OK to call close again
await self.con.close()
async def test_prepare_07_interrupted_terminate(self):
stmt = await self.con.prepare('''SELECT pg_sleep(10)''')
fut = self.loop.create_task(stmt.fetchval())
await asyncio.sleep(0.2)
self.assertFalse(self.con.is_closed())
self.con.terminate()
self.assertTrue(self.con.is_closed())
with self.assertRaisesRegex(asyncpg.ConnectionDoesNotExistError,
'closed in the middle'):
await fut
# Test that it's OK to call terminate again
self.con.terminate()
async def test_prepare_08_big_result(self):
stmt = await self.con.prepare('select generate_series(0,10000)')
result = await stmt.fetch()
self.assertEqual(len(result), 10001)
self.assertEqual(
[r[0] for r in result],
list(range(10001)))
async def test_prepare_09_raise_error(self):
# Stress test ReadBuffer.read_cstr()
msg = '0' * 1024 * 100
query = """
DO language plpgsql $$
BEGIN
RAISE EXCEPTION '{}';
END
$$;""".format(msg)
stmt = await self.con.prepare(query)
with self.assertRaisesRegex(asyncpg.RaiseError, msg):
with tb.silence_asyncio_long_exec_warning():
await stmt.fetchval()
async def test_prepare_10_stmt_lru(self):
cache = self.con._stmt_cache
query = 'select {}'
cache_max = cache.get_max_size()
iter_max = cache_max * 2 + 11
# First, we have no cached statements.
self.assertEqual(len(cache), 0)
stmts = []
for i in range(iter_max):
s = await self.con._prepare(query.format(i), use_cache=True)
self.assertEqual(await s.fetchval(), i)
stmts.append(s)
# At this point our cache should be full.
self.assertEqual(len(cache), cache_max)
self.assertTrue(all(not s.closed for s in cache.iter_statements()))
# Since there are references to the statements (`stmts` list),
# no statements are scheduled to be closed.
self.assertEqual(len(self.con._stmts_to_close), 0)
# Removing refs to statements and preparing a new statement
# will cause connection to cleanup any stale statements.
stmts.clear()
gc.collect()
# Now we have a bunch of statements that have no refs to them
# scheduled to be closed.
self.assertEqual(len(self.con._stmts_to_close), iter_max - cache_max)
self.assertTrue(all(s.closed for s in self.con._stmts_to_close))
self.assertTrue(all(not s.closed for s in cache.iter_statements()))
zero = await self.con.prepare(query.format(0))
# Hence, all stale statements should be closed now.
self.assertEqual(len(self.con._stmts_to_close), 0)
# The number of cached statements will stay the same though.
self.assertEqual(len(cache), cache_max)
self.assertTrue(all(not s.closed for s in cache.iter_statements()))
# After closing all statements will be closed.
await self.con.close()
self.assertEqual(len(self.con._stmts_to_close), 0)
self.assertEqual(len(cache), 0)
# An attempt to perform an operation on a closed statement
# will trigger an error.
with self.assertRaisesRegex(asyncpg.InterfaceError, 'is closed'):
await zero.fetchval()
async def test_prepare_11_stmt_gc(self):
# Test that prepared statements should stay in the cache after
# they are GCed.
cache = self.con._stmt_cache
# First, we have no cached statements.
self.assertEqual(len(cache), 0)
self.assertEqual(len(self.con._stmts_to_close), 0)
# The prepared statement that we'll create will be GCed
# right await. However, its state should be still in
# in the statements LRU cache.
await self.con._prepare('select 1', use_cache=True)
gc.collect()
self.assertEqual(len(cache), 1)
self.assertEqual(len(self.con._stmts_to_close), 0)
async def test_prepare_12_stmt_gc(self):
# Test that prepared statements are closed when there is no space
# for them in the LRU cache and there are no references to them.
cache = self.con._stmt_cache
cache_max = cache.get_max_size()
# First, we have no cached statements.
self.assertEqual(len(cache), 0)
self.assertEqual(len(self.con._stmts_to_close), 0)
stmt = await self.con._prepare('select 100000000', use_cache=True)
self.assertEqual(len(cache), 1)
self.assertEqual(len(self.con._stmts_to_close), 0)
for i in range(cache_max):
await self.con._prepare('select {}'.format(i), use_cache=True)
self.assertEqual(len(cache), cache_max)
self.assertEqual(len(self.con._stmts_to_close), 0)
del stmt
gc.collect()
self.assertEqual(len(cache), cache_max)
self.assertEqual(len(self.con._stmts_to_close), 1)
async def test_prepare_13_connect(self):
v = await self.con.fetchval(
'SELECT $1::smallint AS foo', 10, column='foo')
self.assertEqual(v, 10)
r = await self.con.fetchrow('SELECT $1::smallint * 2 AS test', 10)
self.assertEqual(r['test'], 20)
rows = await self.con.fetch('SELECT generate_series(0,$1::int)', 3)
self.assertEqual([r[0] for r in rows], [0, 1, 2, 3])
async def test_prepare_14_explain(self):
# Test simple EXPLAIN.
stmt = await self.con.prepare('SELECT typname FROM pg_type')
plan = await stmt.explain()
self.assertEqual(plan[0]['Plan']['Relation Name'], 'pg_type')
# Test "EXPLAIN ANALYZE".
stmt = await self.con.prepare(
'SELECT typname, typlen FROM pg_type WHERE typlen > $1')
plan = await stmt.explain(2, analyze=True)
self.assertEqual(plan[0]['Plan']['Relation Name'], 'pg_type')
self.assertIn('Actual Total Time', plan[0]['Plan'])
# Test that 'EXPLAIN ANALYZE' is executed in a transaction
# that gets rollbacked.
tr = self.con.transaction()
await tr.start()
try:
await self.con.execute('CREATE TABLE mytab (a int)')
stmt = await self.con.prepare(
'INSERT INTO mytab (a) VALUES (1), (2)')
plan = await stmt.explain(analyze=True)
self.assertEqual(plan[0]['Plan']['Operation'], 'Insert')
# Check that no data was inserted
res = await self.con.fetch('SELECT * FROM mytab')
self.assertEqual(res, [])
finally:
await tr.rollback()
async def test_prepare_15_stmt_gc_cache_disabled(self):
# Test that even if the statements cache is off, we're still
# cleaning up GCed statements.
cache = self.con._stmt_cache
self.assertEqual(len(cache), 0)
self.assertEqual(len(self.con._stmts_to_close), 0)
# Disable cache
cache.set_max_size(0)
stmt = await self.con._prepare('select 100000000', use_cache=True)
self.assertEqual(len(cache), 0)
self.assertEqual(len(self.con._stmts_to_close), 0)
del stmt
gc.collect()
# After GC, _stmts_to_close should contain stmt's state
self.assertEqual(len(cache), 0)
self.assertEqual(len(self.con._stmts_to_close), 1)
# Next "prepare" call will trigger a cleanup
stmt = await self.con._prepare('select 1', use_cache=True)
self.assertEqual(len(cache), 0)
self.assertEqual(len(self.con._stmts_to_close), 0)
del stmt
async def test_prepare_16_command_result(self):
async def status(query):
stmt = await self.con.prepare(query)
await stmt.fetch()
return stmt.get_statusmsg()
try:
self.assertEqual(
await status('CREATE TABLE mytab (a int)'),
'CREATE TABLE')
self.assertEqual(
await status('INSERT INTO mytab (a) VALUES (1), (2)'),
'INSERT 0 2')
self.assertEqual(
await status('SELECT a FROM mytab'),
'SELECT 2')
self.assertEqual(
await status('UPDATE mytab SET a = 3 WHERE a = 1'),
'UPDATE 1')
finally:
self.assertEqual(
await status('DROP TABLE mytab'),
'DROP TABLE')
async def test_prepare_17_stmt_closed_lru(self):
st = await self.con.prepare('SELECT 1')
st._state.mark_closed()
with self.assertRaisesRegex(asyncpg.InterfaceError, 'is closed'):
await st.fetch()
st = await self.con.prepare('SELECT 1')
self.assertEqual(await st.fetchval(), 1)
async def test_prepare_18_empty_result(self):
# test EmptyQueryResponse protocol message
st = await self.con.prepare('')
self.assertEqual(await st.fetch(), [])
self.assertIsNone(await st.fetchval())
self.assertIsNone(await st.fetchrow())
self.assertEqual(await self.con.fetch(''), [])
self.assertIsNone(await self.con.fetchval(''))
self.assertIsNone(await self.con.fetchrow(''))
async def test_prepare_19_concurrent_calls(self):
st = self.loop.create_task(self.con.fetchval(
'SELECT ROW(pg_sleep(0.1), 1)'))
# Wait for some time to make sure the first query is fully
# prepared (!) and is now awaiting the results (!!).
await asyncio.sleep(0.01)
with self.assertRaisesRegex(asyncpg.InterfaceError,
'another operation'):
await self.con.execute('SELECT 2')
self.assertEqual(await st, (None, 1))
async def test_prepare_20_concurrent_calls(self):
expected = ((None, 1),)
for methname, val in [('fetch', [expected]),
('fetchval', expected[0]),
('fetchrow', expected)]:
with self.subTest(meth=methname):
meth = getattr(self.con, methname)
vf = self.loop.create_task(
meth('SELECT ROW(pg_sleep(0.1), 1)'))
await asyncio.sleep(0.01)
with self.assertRaisesRegex(asyncpg.InterfaceError,
'another operation'):
await meth('SELECT 2')
self.assertEqual(await vf, val)
async def test_prepare_21_errors(self):
stmt = await self.con.prepare('SELECT 10 / $1::int')
with self.assertRaises(asyncpg.DivisionByZeroError):
await stmt.fetchval(0)
self.assertEqual(await stmt.fetchval(5), 2)
async def test_prepare_22_empty(self):
# Support for empty target list was added in PostgreSQL 9.4
if self.server_version < (9, 4):
raise unittest.SkipTest(
'PostgreSQL servers < 9.4 do not support empty target list.')
result = await self.con.fetchrow('SELECT')
self.assertEqual(result, ())
self.assertEqual(repr(result), '<Record>')
async def test_prepare_statement_invalid(self):
await self.con.execute('CREATE TABLE tab1(a int, b int)')
try:
await self.con.execute('INSERT INTO tab1 VALUES (1, 2)')
stmt = await self.con.prepare('SELECT * FROM tab1')
await self.con.execute(
'ALTER TABLE tab1 ALTER COLUMN b SET DATA TYPE text')
with self.assertRaisesRegex(asyncpg.InvalidCachedStatementError,
'cached statement plan is invalid'):
await stmt.fetchrow()
finally:
await self.con.execute('DROP TABLE tab1')
@tb.with_connection_options(statement_cache_size=0)
async def test_prepare_23_no_stmt_cache_seq(self):
self.assertEqual(self.con._stmt_cache.get_max_size(), 0)
async def check_simple():
# Run a simple query a few times.
self.assertEqual(await self.con.fetchval('SELECT 1'), 1)
self.assertEqual(await self.con.fetchval('SELECT 2'), 2)
self.assertEqual(await self.con.fetchval('SELECT 1'), 1)
await check_simple()
# Run a query that timeouts.
with self.assertRaises(asyncio.TimeoutError):
await self.con.fetchrow('select pg_sleep(10)', timeout=0.02)
# Check that we can run new queries after a timeout.
await check_simple()
# Try a cursor/timeout combination. Cursors should always use
# named prepared statements.
async with self.con.transaction():
with self.assertRaises(asyncio.TimeoutError):
async for _ in self.con.cursor( # NOQA
'select pg_sleep(10)', timeout=0.1):
pass
# Check that we can run queries after a failed cursor
# operation.
await check_simple()
@tb.with_connection_options(max_cached_statement_lifetime=142)
async def test_prepare_24_max_lifetime(self):
cache = self.con._stmt_cache
self.assertEqual(cache.get_max_lifetime(), 142)
cache.set_max_lifetime(1)
s = await self.con._prepare('SELECT 1', use_cache=True)
state = s._state
s = await self.con._prepare('SELECT 1', use_cache=True)
self.assertIs(s._state, state)
s = await self.con._prepare('SELECT 1', use_cache=True)
self.assertIs(s._state, state)
await asyncio.sleep(1)
s = await self.con._prepare('SELECT 1', use_cache=True)
self.assertIsNot(s._state, state)
@tb.with_connection_options(max_cached_statement_lifetime=0.5)
async def test_prepare_25_max_lifetime_reset(self):
cache = self.con._stmt_cache
s = await self.con._prepare('SELECT 1', use_cache=True)
state = s._state
# Disable max_lifetime
cache.set_max_lifetime(0)
await asyncio.sleep(1)
# The statement should still be cached (as we disabled the timeout).
s = await self.con._prepare('SELECT 1', use_cache=True)
self.assertIs(s._state, state)
@tb.with_connection_options(max_cached_statement_lifetime=0.5)
async def test_prepare_26_max_lifetime_max_size(self):
cache = self.con._stmt_cache
s = await self.con._prepare('SELECT 1', use_cache=True)
state = s._state
# Disable max_lifetime
cache.set_max_size(0)
s = await self.con._prepare('SELECT 1', use_cache=True)
self.assertIsNot(s._state, state)
# Check that nothing crashes after the initial timeout
await asyncio.sleep(1)
@tb.with_connection_options(max_cacheable_statement_size=50)
async def test_prepare_27_max_cacheable_statement_size(self):
cache = self.con._stmt_cache
await self.con._prepare('SELECT 1', use_cache=True)
self.assertEqual(len(cache), 1)
# Test that long and explicitly created prepared statements
# are not cached.
await self.con._prepare("SELECT \'" + "a" * 50 + "\'", use_cache=True)
self.assertEqual(len(cache), 1)
# Test that implicitly created long prepared statements
# are not cached.
await self.con.fetchval("SELECT \'" + "a" * 50 + "\'")
self.assertEqual(len(cache), 1)
# Test that short prepared statements can still be cached.
await self.con._prepare('SELECT 2', use_cache=True)
self.assertEqual(len(cache), 2)
async def test_prepare_28_max_args(self):
N = 32768
args = ','.join('${}'.format(i) for i in range(1, N + 1))
query = 'SELECT ARRAY[{}]'.format(args)
with self.assertRaisesRegex(
exceptions.InterfaceError,
'the number of query arguments cannot exceed 32767'):
await self.con.fetchval(query, *range(1, N + 1))
async def test_prepare_29_duplicates(self):
# In addition to test_record.py, let's have a full functional
# test for records with duplicate keys.
r = await self.con.fetchrow('SELECT 1 as a, 2 as b, 3 as a')
self.assertEqual(list(r.items()), [('a', 1), ('b', 2), ('a', 3)])
self.assertEqual(list(r.keys()), ['a', 'b', 'a'])
self.assertEqual(list(r.values()), [1, 2, 3])
self.assertEqual(r['a'], 3)
self.assertEqual(r['b'], 2)
self.assertEqual(r[0], 1)
self.assertEqual(r[1], 2)
self.assertEqual(r[2], 3)
async def test_prepare_30_invalid_arg_count(self):
with self.assertRaisesRegex(
exceptions.InterfaceError,
'the server expects 1 argument for this query, 0 were passed'):
await self.con.fetchval('SELECT $1::int')
with self.assertRaisesRegex(
exceptions.InterfaceError,
'the server expects 0 arguments for this query, 1 was passed'):
await self.con.fetchval('SELECT 1', 1)
async def test_prepare_31_pgbouncer_note(self):
try:
await self.con.execute("""
DO $$ BEGIN
RAISE EXCEPTION
'duplicate statement' USING ERRCODE = '42P05';
END; $$ LANGUAGE plpgsql;
""")
except asyncpg.DuplicatePreparedStatementError as e:
self.assertTrue('pgbouncer' in e.hint)
else:
self.fail('DuplicatePreparedStatementError not raised')
try:
await self.con.execute("""
DO $$ BEGIN
RAISE EXCEPTION
'invalid statement' USING ERRCODE = '26000';
END; $$ LANGUAGE plpgsql;
""")
except asyncpg.InvalidSQLStatementNameError as e:
self.assertTrue('pgbouncer' in e.hint)
else:
self.fail('InvalidSQLStatementNameError not raised')
async def test_prepare_does_not_use_cache(self):
cache = self.con._stmt_cache
# prepare with disabled cache
await self.con.prepare('select 1')
self.assertEqual(len(cache), 0)