forked from sqlalchemy/sqlalchemy
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_execute.py
More file actions
3071 lines (2547 loc) · 96.3 KB
/
Copy pathtest_execute.py
File metadata and controls
3071 lines (2547 loc) · 96.3 KB
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
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# coding: utf-8
from contextlib import contextmanager
import re
import weakref
import sqlalchemy as tsa
from sqlalchemy import bindparam
from sqlalchemy import create_engine
from sqlalchemy import create_mock_engine
from sqlalchemy import event
from sqlalchemy import func
from sqlalchemy import inspect
from sqlalchemy import INT
from sqlalchemy import Integer
from sqlalchemy import LargeBinary
from sqlalchemy import MetaData
from sqlalchemy import select
from sqlalchemy import Sequence
from sqlalchemy import String
from sqlalchemy import testing
from sqlalchemy import text
from sqlalchemy import TypeDecorator
from sqlalchemy import util
from sqlalchemy import VARCHAR
from sqlalchemy.engine import default
from sqlalchemy.engine.base import Connection
from sqlalchemy.engine.base import Engine
from sqlalchemy.sql import column
from sqlalchemy.sql import literal
from sqlalchemy.testing import assert_raises
from sqlalchemy.testing import assert_raises_message
from sqlalchemy.testing import config
from sqlalchemy.testing import engines
from sqlalchemy.testing import eq_
from sqlalchemy.testing import expect_warnings
from sqlalchemy.testing import fixtures
from sqlalchemy.testing import is_
from sqlalchemy.testing import is_false
from sqlalchemy.testing import is_not_
from sqlalchemy.testing import is_true
from sqlalchemy.testing import mock
from sqlalchemy.testing.assertsql import CompiledSQL
from sqlalchemy.testing.engines import testing_engine
from sqlalchemy.testing.mock import call
from sqlalchemy.testing.mock import Mock
from sqlalchemy.testing.mock import patch
from sqlalchemy.testing.schema import Column
from sqlalchemy.testing.schema import Table
from sqlalchemy.testing.util import gc_collect
from sqlalchemy.testing.util import picklers
from sqlalchemy.util import collections_abc
class SomeException(Exception):
pass
class ExecuteTest(fixtures.TablesTest):
__backend__ = True
@classmethod
def define_tables(cls, metadata):
Table(
"users",
metadata,
Column("user_id", INT, primary_key=True, autoincrement=False),
Column("user_name", VARCHAR(20)),
)
Table(
"users_autoinc",
metadata,
Column(
"user_id", INT, primary_key=True, test_needs_autoincrement=True
),
Column("user_name", VARCHAR(20)),
)
@testing.fails_on(
"postgresql+pg8000",
"pg8000 still doesn't allow single paren without params",
)
def test_no_params_option(self):
stmt = (
"SELECT '%'"
+ testing.db.dialect.statement_compiler(
testing.db.dialect, None
).default_from()
)
conn = testing.db.connect()
result = (
conn.execution_options(no_parameters=True)
.exec_driver_sql(stmt)
.scalar()
)
eq_(result, "%")
def test_raw_positional_invalid(self, connection):
assert_raises_message(
tsa.exc.ArgumentError,
"List argument must consist only of tuples or dictionaries",
connection.exec_driver_sql,
"insert into users (user_id, user_name) " "values (?, ?)",
[2, "fred"],
)
assert_raises_message(
tsa.exc.ArgumentError,
"List argument must consist only of tuples or dictionaries",
connection.exec_driver_sql,
"insert into users (user_id, user_name) " "values (?, ?)",
[[3, "ed"], [4, "horse"]],
)
def test_raw_named_invalid(self, connection):
# this is awkward b.c. this is just testing if regular Python
# is raising TypeError if they happened to send arguments that
# look like the legacy ones which also happen to conflict with
# the positional signature for the method. some combinations
# can get through and fail differently
assert_raises(
TypeError,
connection.exec_driver_sql,
"insert into users (user_id, user_name) "
"values (%(id)s, %(name)s)",
{"id": 2, "name": "ed"},
{"id": 3, "name": "horse"},
{"id": 4, "name": "horse"},
)
assert_raises(
TypeError,
connection.exec_driver_sql,
"insert into users (user_id, user_name) "
"values (%(id)s, %(name)s)",
id=4,
name="sally",
)
@testing.requires.qmark_paramstyle
def test_raw_qmark(self, connection):
conn = connection
conn.exec_driver_sql(
"insert into users (user_id, user_name) " "values (?, ?)",
(1, "jack"),
)
conn.exec_driver_sql(
"insert into users (user_id, user_name) " "values (?, ?)",
(2, "fred"),
)
conn.exec_driver_sql(
"insert into users (user_id, user_name) " "values (?, ?)",
[(3, "ed"), (4, "horse")],
)
conn.exec_driver_sql(
"insert into users (user_id, user_name) " "values (?, ?)",
[(5, "barney"), (6, "donkey")],
)
conn.exec_driver_sql(
"insert into users (user_id, user_name) " "values (?, ?)",
(7, "sally"),
)
res = conn.exec_driver_sql("select * from users order by user_id")
assert res.fetchall() == [
(1, "jack"),
(2, "fred"),
(3, "ed"),
(4, "horse"),
(5, "barney"),
(6, "donkey"),
(7, "sally"),
]
res = conn.exec_driver_sql(
"select * from users where user_name=?", ("jack",)
)
assert res.fetchall() == [(1, "jack")]
@testing.requires.format_paramstyle
def test_raw_sprintf(self, connection):
conn = connection
conn.exec_driver_sql(
"insert into users (user_id, user_name) " "values (%s, %s)",
(1, "jack"),
)
conn.exec_driver_sql(
"insert into users (user_id, user_name) " "values (%s, %s)",
[(2, "ed"), (3, "horse")],
)
conn.exec_driver_sql(
"insert into users (user_id, user_name) " "values (%s, %s)",
(4, "sally"),
)
conn.exec_driver_sql("insert into users (user_id) values (%s)", (5,))
res = conn.exec_driver_sql("select * from users order by user_id")
assert res.fetchall() == [
(1, "jack"),
(2, "ed"),
(3, "horse"),
(4, "sally"),
(5, None),
]
res = conn.exec_driver_sql(
"select * from users where user_name=%s", ("jack",)
)
assert res.fetchall() == [(1, "jack")]
@testing.requires.pyformat_paramstyle
def test_raw_python(self, connection):
conn = connection
conn.exec_driver_sql(
"insert into users (user_id, user_name) "
"values (%(id)s, %(name)s)",
{"id": 1, "name": "jack"},
)
conn.exec_driver_sql(
"insert into users (user_id, user_name) "
"values (%(id)s, %(name)s)",
[{"id": 2, "name": "ed"}, {"id": 3, "name": "horse"}],
)
conn.exec_driver_sql(
"insert into users (user_id, user_name) "
"values (%(id)s, %(name)s)",
dict(id=4, name="sally"),
)
res = conn.exec_driver_sql("select * from users order by user_id")
assert res.fetchall() == [
(1, "jack"),
(2, "ed"),
(3, "horse"),
(4, "sally"),
]
@testing.requires.named_paramstyle
def test_raw_named(self, connection):
conn = connection
conn.exec_driver_sql(
"insert into users (user_id, user_name) " "values (:id, :name)",
{"id": 1, "name": "jack"},
)
conn.exec_driver_sql(
"insert into users (user_id, user_name) " "values (:id, :name)",
[{"id": 2, "name": "ed"}, {"id": 3, "name": "horse"}],
)
conn.exec_driver_sql(
"insert into users (user_id, user_name) " "values (:id, :name)",
{"id": 4, "name": "sally"},
)
res = conn.exec_driver_sql("select * from users order by user_id")
assert res.fetchall() == [
(1, "jack"),
(2, "ed"),
(3, "horse"),
(4, "sally"),
]
@testing.engines.close_open_connections
def test_exception_wrapping_dbapi(self):
conn = testing.db.connect()
# engine does not have exec_driver_sql
assert_raises_message(
tsa.exc.DBAPIError,
r"not_a_valid_statement",
conn.exec_driver_sql,
"not_a_valid_statement",
)
@testing.requires.sqlite
def test_exception_wrapping_non_dbapi_error(self):
e = create_engine("sqlite://")
e.dialect.is_disconnect = is_disconnect = Mock()
with e.connect() as c:
c.connection.cursor = Mock(
return_value=Mock(
execute=Mock(
side_effect=TypeError("I'm not a DBAPI error")
)
)
)
assert_raises_message(
TypeError,
"I'm not a DBAPI error",
c.exec_driver_sql,
"select ",
)
eq_(is_disconnect.call_count, 0)
def test_exception_wrapping_non_standard_dbapi_error(self):
class DBAPIError(Exception):
pass
class OperationalError(DBAPIError):
pass
class NonStandardException(OperationalError):
pass
with patch.object(
testing.db.dialect, "dbapi", Mock(Error=DBAPIError)
), patch.object(
testing.db.dialect, "is_disconnect", lambda *arg: False
), patch.object(
testing.db.dialect,
"do_execute",
Mock(side_effect=NonStandardException),
):
with testing.db.connect() as conn:
assert_raises(
tsa.exc.OperationalError, conn.exec_driver_sql, "select 1"
)
def test_exception_wrapping_non_dbapi_statement(self):
class MyType(TypeDecorator):
impl = Integer
def process_bind_param(self, value, dialect):
raise SomeException("nope")
def _go(conn):
assert_raises_message(
tsa.exc.StatementError,
r"\(.*.SomeException\) " r"nope\n\[SQL\: u?SELECT 1 ",
conn.execute,
select([1]).where(column("foo") == literal("bar", MyType())),
)
_go(testing.db)
with testing.db.connect() as conn:
_go(conn)
def test_not_an_executable(self):
for obj in (
Table("foo", MetaData(), Column("x", Integer)),
Column("x", Integer),
tsa.and_(True),
tsa.and_(True).compile(),
column("foo"),
column("foo").compile(),
MetaData(),
Integer(),
tsa.Index(name="foo"),
tsa.UniqueConstraint("x"),
):
with testing.db.connect() as conn:
assert_raises_message(
tsa.exc.ObjectNotExecutableError,
"Not an executable object",
conn.execute,
obj,
)
def test_stmt_exception_bytestring_raised(self):
name = util.u("méil")
with testing.db.connect() as conn:
assert_raises_message(
tsa.exc.StatementError,
util.u(
"A value is required for bind parameter 'uname'\n"
r".*SELECT users.user_name AS .m\xe9il."
)
if util.py2k
else util.u(
"A value is required for bind parameter 'uname'\n"
".*SELECT users.user_name AS .méil."
),
conn.execute,
select([users.c.user_name.label(name)]).where(
users.c.user_name == bindparam("uname")
),
{"uname_incorrect": "foo"},
)
def test_stmt_exception_bytestring_utf8(self):
# uncommon case for Py3K, bytestring object passed
# as the error message
message = util.u("some message méil").encode("utf-8")
err = tsa.exc.SQLAlchemyError(message)
if util.py2k:
# string passes it through
eq_(str(err), message)
# unicode accessor decodes to utf-8
eq_(unicode(err), util.u("some message méil")) # noqa
else:
eq_(str(err), util.u("some message méil"))
def test_stmt_exception_bytestring_latin1(self):
# uncommon case for Py3K, bytestring object passed
# as the error message
message = util.u("some message méil").encode("latin-1")
err = tsa.exc.SQLAlchemyError(message)
if util.py2k:
# string passes it through
eq_(str(err), message)
# unicode accessor decodes to utf-8
eq_(unicode(err), util.u("some message m\\xe9il")) # noqa
else:
eq_(str(err), util.u("some message m\\xe9il"))
def test_stmt_exception_unicode_hook_unicode(self):
# uncommon case for Py2K, Unicode object passed
# as the error message
message = util.u("some message méil")
err = tsa.exc.SQLAlchemyError(message)
if util.py2k:
eq_(unicode(err), util.u("some message méil")) # noqa
else:
eq_(str(err), util.u("some message méil"))
def test_stmt_exception_str_multi_args(self):
err = tsa.exc.SQLAlchemyError("some message", 206)
eq_(str(err), "('some message', 206)")
def test_stmt_exception_str_multi_args_bytestring(self):
message = util.u("some message méil").encode("utf-8")
err = tsa.exc.SQLAlchemyError(message, 206)
eq_(str(err), str((message, 206)))
def test_stmt_exception_str_multi_args_unicode(self):
message = util.u("some message méil")
err = tsa.exc.SQLAlchemyError(message, 206)
eq_(str(err), str((message, 206)))
def test_stmt_exception_pickleable_no_dbapi(self):
self._test_stmt_exception_pickleable(Exception("hello world"))
@testing.crashes(
"postgresql+psycopg2",
"Older versions don't support cursor pickling, newer ones do",
)
@testing.fails_on(
"mysql+oursql",
"Exception doesn't come back exactly the same from pickle",
)
@testing.fails_on(
"mysql+mysqlconnector",
"Exception doesn't come back exactly the same from pickle",
)
@testing.fails_on(
"oracle+cx_oracle",
"cx_oracle exception seems to be having " "some issue with pickling",
)
def test_stmt_exception_pickleable_plus_dbapi(self):
raw = testing.db.raw_connection()
the_orig = None
try:
try:
cursor = raw.cursor()
cursor.execute("SELECTINCORRECT")
except testing.db.dialect.dbapi.DatabaseError as orig:
# py3k has "orig" in local scope...
the_orig = orig
finally:
raw.close()
self._test_stmt_exception_pickleable(the_orig)
def _test_stmt_exception_pickleable(self, orig):
for sa_exc in (
tsa.exc.StatementError(
"some error",
"select * from table",
{"foo": "bar"},
orig,
False,
),
tsa.exc.InterfaceError(
"select * from table", {"foo": "bar"}, orig, True
),
tsa.exc.NoReferencedTableError("message", "tname"),
tsa.exc.NoReferencedColumnError("message", "tname", "cname"),
tsa.exc.CircularDependencyError(
"some message", [1, 2, 3], [(1, 2), (3, 4)]
),
):
for loads, dumps in picklers():
repickled = loads(dumps(sa_exc))
eq_(repickled.args[0], sa_exc.args[0])
if isinstance(sa_exc, tsa.exc.StatementError):
eq_(repickled.params, {"foo": "bar"})
eq_(repickled.statement, sa_exc.statement)
if hasattr(sa_exc, "connection_invalidated"):
eq_(
repickled.connection_invalidated,
sa_exc.connection_invalidated,
)
eq_(repickled.orig.args[0], orig.args[0])
def test_dont_wrap_mixin(self):
class MyException(Exception, tsa.exc.DontWrapMixin):
pass
class MyType(TypeDecorator):
impl = Integer
def process_bind_param(self, value, dialect):
raise MyException("nope")
def _go(conn):
assert_raises_message(
MyException,
"nope",
conn.execute,
select([1]).where(column("foo") == literal("bar", MyType())),
)
_go(testing.db)
conn = testing.db.connect()
try:
_go(conn)
finally:
conn.close()
def test_empty_insert(self):
"""test that execute() interprets [] as a list with no params"""
users_autoinc = self.tables.users_autoinc
testing.db.execute(
users_autoinc.insert().values(user_name=bindparam("name", None)),
[],
)
eq_(testing.db.execute(users_autoinc.select()).fetchall(), [(1, None)])
@testing.only_on("sqlite")
def test_execute_compiled_favors_compiled_paramstyle(self):
with patch.object(testing.db.dialect, "do_execute") as do_exec:
stmt = users.update().values(user_id=1, user_name="foo")
d1 = default.DefaultDialect(paramstyle="format")
d2 = default.DefaultDialect(paramstyle="pyformat")
testing.db.execute(stmt.compile(dialect=d1))
testing.db.execute(stmt.compile(dialect=d2))
eq_(
do_exec.mock_calls,
[
call(
mock.ANY,
"UPDATE users SET user_id=%s, user_name=%s",
(1, "foo"),
mock.ANY,
),
call(
mock.ANY,
"UPDATE users SET user_id=%(user_id)s, "
"user_name=%(user_name)s",
{"user_name": "foo", "user_id": 1},
mock.ANY,
),
],
)
@testing.requires.ad_hoc_engines
def test_engine_level_options(self):
eng = engines.testing_engine(
options={"execution_options": {"foo": "bar"}}
)
with eng.connect() as conn:
eq_(conn._execution_options["foo"], "bar")
eq_(
conn.execution_options(bat="hoho")._execution_options["foo"],
"bar",
)
eq_(
conn.execution_options(bat="hoho")._execution_options["bat"],
"hoho",
)
eq_(
conn.execution_options(foo="hoho")._execution_options["foo"],
"hoho",
)
eng.update_execution_options(foo="hoho")
conn = eng.connect()
eq_(conn._execution_options["foo"], "hoho")
@testing.requires.ad_hoc_engines
def test_generative_engine_execution_options(self):
eng = engines.testing_engine(
options={"execution_options": {"base": "x1"}}
)
is_(eng.engine, eng)
eng1 = eng.execution_options(foo="b1")
is_(eng1.engine, eng1)
eng2 = eng.execution_options(foo="b2")
eng1a = eng1.execution_options(bar="a1")
eng2a = eng2.execution_options(foo="b3", bar="a2")
is_(eng2a.engine, eng2a)
eq_(eng._execution_options, {"base": "x1"})
eq_(eng1._execution_options, {"base": "x1", "foo": "b1"})
eq_(eng2._execution_options, {"base": "x1", "foo": "b2"})
eq_(eng1a._execution_options, {"base": "x1", "foo": "b1", "bar": "a1"})
eq_(eng2a._execution_options, {"base": "x1", "foo": "b3", "bar": "a2"})
is_(eng1a.pool, eng.pool)
# test pool is shared
eng2.dispose()
is_(eng1a.pool, eng2.pool)
is_(eng.pool, eng2.pool)
@testing.requires.ad_hoc_engines
def test_autocommit_option_no_issue_first_connect(self):
eng = create_engine(testing.db.url)
eng.update_execution_options(autocommit=True)
conn = eng.connect()
eq_(conn._execution_options, {"autocommit": True})
conn.close()
def test_initialize_rollback(self):
"""test a rollback happens during first connect"""
eng = create_engine(testing.db.url)
with patch.object(eng.dialect, "do_rollback") as do_rollback:
assert do_rollback.call_count == 0
connection = eng.connect()
assert do_rollback.call_count == 1
connection.close()
@testing.requires.ad_hoc_engines
def test_dialect_init_uses_options(self):
eng = create_engine(testing.db.url)
def my_init(connection):
connection.execution_options(foo="bar").execute(select([1]))
with patch.object(eng.dialect, "initialize", my_init):
conn = eng.connect()
eq_(conn._execution_options, {})
conn.close()
@testing.requires.ad_hoc_engines
def test_generative_engine_event_dispatch_hasevents(self):
def l1(*arg, **kw):
pass
eng = create_engine(testing.db.url)
assert not eng._has_events
event.listen(eng, "before_execute", l1)
eng2 = eng.execution_options(foo="bar")
assert eng2._has_events
def test_works_after_dispose(self):
eng = create_engine(testing.db.url)
for i in range(3):
eq_(eng.scalar(select([1])), 1)
eng.dispose()
def test_works_after_dispose_testing_engine(self):
eng = engines.testing_engine()
for i in range(3):
eq_(eng.scalar(select([1])), 1)
eng.dispose()
class UnicodeReturnsTest(fixtures.TestBase):
@testing.requires.python3
def test_unicode_test_not_in_python3(self):
eng = engines.testing_engine()
eng.dialect.returns_unicode_strings = String.RETURNS_UNKNOWN
assert_raises_message(
tsa.exc.InvalidRequestError,
"RETURNS_UNKNOWN is unsupported in Python 3",
eng.connect,
)
@testing.requires.python2
def test_unicode_test_fails_warning(self):
class MockCursor(engines.DBAPIProxyCursor):
def execute(self, stmt, params=None, **kw):
if "test unicode returns" in stmt:
raise self.engine.dialect.dbapi.DatabaseError("boom")
else:
return super(MockCursor, self).execute(stmt, params, **kw)
eng = engines.proxying_engine(cursor_cls=MockCursor)
with testing.expect_warnings(
"Exception attempting to detect unicode returns"
):
eng.connect()
# because plain varchar passed, we don't know the correct answer
eq_(eng.dialect.returns_unicode_strings, String.RETURNS_CONDITIONAL)
eng.dispose()
class ConvenienceExecuteTest(fixtures.TablesTest):
__backend__ = True
@classmethod
def define_tables(cls, metadata):
cls.table = Table(
"exec_test",
metadata,
Column("a", Integer),
Column("b", Integer),
test_needs_acid=True,
)
def _trans_fn(self, is_transaction=False):
def go(conn, x, value=None):
if is_transaction:
conn = conn.connection
conn.execute(self.table.insert().values(a=x, b=value))
return go
def _trans_rollback_fn(self, is_transaction=False):
def go(conn, x, value=None):
if is_transaction:
conn = conn.connection
conn.execute(self.table.insert().values(a=x, b=value))
raise SomeException("breakage")
return go
def _assert_no_data(self):
eq_(
testing.db.scalar(
select([func.count("*")]).select_from(self.table)
),
0,
)
def _assert_fn(self, x, value=None):
eq_(testing.db.execute(self.table.select()).fetchall(), [(x, value)])
def test_transaction_engine_ctx_commit(self):
fn = self._trans_fn()
ctx = testing.db.begin()
testing.run_as_contextmanager(ctx, fn, 5, value=8)
self._assert_fn(5, value=8)
def test_transaction_engine_ctx_begin_fails(self):
engine = engines.testing_engine()
mock_connection = Mock(
return_value=Mock(begin=Mock(side_effect=Exception("boom")))
)
engine._connection_cls = mock_connection
assert_raises(Exception, engine.begin)
eq_(mock_connection.return_value.close.mock_calls, [call()])
def test_transaction_engine_ctx_rollback(self):
fn = self._trans_rollback_fn()
ctx = testing.db.begin()
assert_raises_message(
Exception,
"breakage",
testing.run_as_contextmanager,
ctx,
fn,
5,
value=8,
)
self._assert_no_data()
def test_transaction_connection_ctx_commit(self):
fn = self._trans_fn(True)
with testing.db.connect() as conn:
ctx = conn.begin()
testing.run_as_contextmanager(ctx, fn, 5, value=8)
self._assert_fn(5, value=8)
def test_transaction_connection_ctx_rollback(self):
fn = self._trans_rollback_fn(True)
with testing.db.connect() as conn:
ctx = conn.begin()
assert_raises_message(
Exception,
"breakage",
testing.run_as_contextmanager,
ctx,
fn,
5,
value=8,
)
self._assert_no_data()
def test_connection_as_ctx(self):
fn = self._trans_fn()
ctx = testing.db.connect()
testing.run_as_contextmanager(ctx, fn, 5, value=8)
# autocommit is on
self._assert_fn(5, value=8)
@testing.fails_on("mysql+oursql", "oursql bug ? getting wrong rowcount")
def test_connect_as_ctx_noautocommit(self):
fn = self._trans_fn()
self._assert_no_data()
with testing.db.connect() as conn:
ctx = conn.execution_options(autocommit=False)
testing.run_as_contextmanager(ctx, fn, 5, value=8)
# autocommit is off
self._assert_no_data()
class CompiledCacheTest(fixtures.TestBase):
__backend__ = True
@classmethod
def setup_class(cls):
global users, metadata
metadata = MetaData(testing.db)
users = Table(
"users",
metadata,
Column(
"user_id", INT, primary_key=True, test_needs_autoincrement=True
),
Column("user_name", VARCHAR(20)),
Column("extra_data", VARCHAR(20)),
)
metadata.create_all()
@engines.close_first
def teardown(self):
testing.db.execute(users.delete())
@classmethod
def teardown_class(cls):
metadata.drop_all()
def test_cache(self):
conn = testing.db.connect()
cache = {}
cached_conn = conn.execution_options(compiled_cache=cache)
ins = users.insert()
with patch.object(
ins, "compile", Mock(side_effect=ins.compile)
) as compile_mock:
cached_conn.execute(ins, {"user_name": "u1"})
cached_conn.execute(ins, {"user_name": "u2"})
cached_conn.execute(ins, {"user_name": "u3"})
eq_(compile_mock.call_count, 1)
assert len(cache) == 1
eq_(conn.exec_driver_sql("select count(*) from users").scalar(), 3)
@testing.only_on(
["sqlite", "mysql", "postgresql"],
"uses blob value that is problematic for some DBAPIs",
)
@testing.provide_metadata
def test_cache_noleak_on_statement_values(self):
# This is a non regression test for an object reference leak caused
# by the compiled_cache.
metadata = self.metadata
photo = Table(
"photo",
metadata,
Column(
"id", Integer, primary_key=True, test_needs_autoincrement=True
),
Column("photo_blob", LargeBinary()),
)
metadata.create_all()
conn = testing.db.connect()
cache = {}
cached_conn = conn.execution_options(compiled_cache=cache)
class PhotoBlob(bytearray):
pass
blob = PhotoBlob(100)
ref_blob = weakref.ref(blob)
ins = photo.insert()
with patch.object(
ins, "compile", Mock(side_effect=ins.compile)
) as compile_mock:
cached_conn.execute(ins, {"photo_blob": blob})
eq_(compile_mock.call_count, 1)
eq_(len(cache), 1)
eq_(conn.exec_driver_sql("select count(*) from photo").scalar(), 1)
del blob
gc_collect()
# The compiled statement cache should not hold any reference to the
# the statement values (only the keys).
eq_(ref_blob(), None)
def test_keys_independent_of_ordering(self):
conn = testing.db.connect()
conn.execute(
users.insert(),
{"user_id": 1, "user_name": "u1", "extra_data": "e1"},
)
cache = {}
cached_conn = conn.execution_options(compiled_cache=cache)
upd = users.update().where(users.c.user_id == bindparam("b_user_id"))
with patch.object(
upd, "compile", Mock(side_effect=upd.compile)
) as compile_mock:
cached_conn.execute(
upd,
util.OrderedDict(
[
("b_user_id", 1),
("user_name", "u2"),
("extra_data", "e2"),
]
),
)
cached_conn.execute(
upd,
util.OrderedDict(
[
("b_user_id", 1),
("extra_data", "e3"),
("user_name", "u3"),
]
),
)
cached_conn.execute(
upd,
util.OrderedDict(
[
("extra_data", "e4"),
("user_name", "u4"),
("b_user_id", 1),
]
),
)
eq_(compile_mock.call_count, 1)
eq_(len(cache), 1)
@testing.requires.schemas
@testing.provide_metadata
def test_schema_translate_in_key(self):
Table("x", self.metadata, Column("q", Integer))
Table(
"x", self.metadata, Column("q", Integer), schema=config.test_schema
)
self.metadata.create_all()
m = MetaData()
t1 = Table("x", m, Column("q", Integer))
ins = t1.insert()
stmt = select([t1.c.q])
cache = {}
with config.db.connect().execution_options(
compiled_cache=cache
) as conn:
conn.execute(ins, {"q": 1})
eq_(conn.scalar(stmt), 1)
with config.db.connect().execution_options(
compiled_cache=cache,
schema_translate_map={None: config.test_schema},
) as conn:
conn.execute(ins, {"q": 2})
eq_(conn.scalar(stmt), 2)
with config.db.connect().execution_options(
compiled_cache=cache, schema_translate_map={None: None},
) as conn:
# should use default schema again even though statement
# was compiled with test_schema in the map
eq_(conn.scalar(stmt), 1)
with config.db.connect().execution_options(
compiled_cache=cache
) as conn:
eq_(conn.scalar(stmt), 1)
class MockStrategyTest(fixtures.TestBase):
def _engine_fixture(self):
buf = util.StringIO()
def dump(sql, *multiparams, **params):
buf.write(util.text_type(sql.compile(dialect=engine.dialect)))
engine = create_mock_engine("postgresql://", executor=dump)
return engine, buf
def test_sequence_not_duped(self):
engine, buf = self._engine_fixture()
metadata = MetaData()
t = Table(