/
test_sqlite.py
3556 lines (3131 loc) · 114 KB
/
test_sqlite.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
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
"""SQLite-specific tests."""
import datetime
import json
import os
from sqlalchemy import and_
from sqlalchemy import bindparam
from sqlalchemy import CheckConstraint
from sqlalchemy import Column
from sqlalchemy import column
from sqlalchemy import Computed
from sqlalchemy import create_engine
from sqlalchemy import DDL
from sqlalchemy import DefaultClause
from sqlalchemy import event
from sqlalchemy import exc
from sqlalchemy import extract
from sqlalchemy import ForeignKey
from sqlalchemy import func
from sqlalchemy import Index
from sqlalchemy import inspect
from sqlalchemy import literal
from sqlalchemy import MetaData
from sqlalchemy import pool
from sqlalchemy import PrimaryKeyConstraint
from sqlalchemy import schema
from sqlalchemy import select
from sqlalchemy import sql
from sqlalchemy import Table
from sqlalchemy import table
from sqlalchemy import testing
from sqlalchemy import text
from sqlalchemy import tuple_
from sqlalchemy import types as sqltypes
from sqlalchemy import UniqueConstraint
from sqlalchemy.dialects.sqlite import base as sqlite
from sqlalchemy.dialects.sqlite import insert
from sqlalchemy.dialects.sqlite import pysqlite as pysqlite_dialect
from sqlalchemy.engine.url import make_url
from sqlalchemy.schema import CreateTable
from sqlalchemy.schema import FetchedValue
from sqlalchemy.sql.elements import quoted_name
from sqlalchemy.testing import assert_raises
from sqlalchemy.testing import assert_raises_message
from sqlalchemy.testing import AssertsCompiledSQL
from sqlalchemy.testing import AssertsExecutionResults
from sqlalchemy.testing import combinations
from sqlalchemy.testing import engines
from sqlalchemy.testing import eq_
from sqlalchemy.testing import eq_ignore_whitespace
from sqlalchemy.testing import expect_raises
from sqlalchemy.testing import expect_warnings
from sqlalchemy.testing import fixtures
from sqlalchemy.testing import is_
from sqlalchemy.testing import mock
from sqlalchemy.types import Boolean
from sqlalchemy.types import Date
from sqlalchemy.types import DateTime
from sqlalchemy.types import Integer
from sqlalchemy.types import String
from sqlalchemy.types import Time
def exec_sql(engine, sql, *args, **kwargs):
# TODO: convert all tests to not use this
with engine.begin() as conn:
conn.exec_driver_sql(sql, *args, **kwargs)
class TestTypes(fixtures.TestBase, AssertsExecutionResults):
__only_on__ = "sqlite"
__backend__ = True
def test_boolean(self, connection, metadata):
"""Test that the boolean only treats 1 as True"""
t = Table(
"bool_table",
metadata,
Column("id", Integer, primary_key=True),
Column("boo", Boolean(create_constraint=False)),
)
metadata.create_all(connection)
for stmt in [
"INSERT INTO bool_table (id, boo) VALUES (1, 'false');",
"INSERT INTO bool_table (id, boo) VALUES (2, 'true');",
"INSERT INTO bool_table (id, boo) VALUES (3, '1');",
"INSERT INTO bool_table (id, boo) VALUES (4, '0');",
"INSERT INTO bool_table (id, boo) VALUES (5, 1);",
"INSERT INTO bool_table (id, boo) VALUES (6, 0);",
]:
connection.exec_driver_sql(stmt)
eq_(
connection.execute(
t.select().where(t.c.boo).order_by(t.c.id)
).fetchall(),
[(3, True), (5, True)],
)
def test_string_dates_passed_raise(self, connection):
assert_raises(
exc.StatementError,
connection.execute,
select(1).where(bindparam("date", type_=Date)),
dict(date=str(datetime.date(2007, 10, 30))),
)
def test_cant_parse_datetime_message(self, connection):
for typ, disp in [
(Time, "time"),
(DateTime, "datetime"),
(Date, "date"),
]:
assert_raises_message(
ValueError,
"Invalid isoformat string:",
lambda: connection.execute(
text("select 'ASDF' as value").columns(value=typ)
).scalar(),
)
@testing.provide_metadata
def test_native_datetime(self):
dbapi = testing.db.dialect.dbapi
connect_args = {
"detect_types": dbapi.PARSE_DECLTYPES | dbapi.PARSE_COLNAMES
}
engine = engines.testing_engine(
options={"connect_args": connect_args, "native_datetime": True}
)
t = Table(
"datetest",
self.metadata,
Column("id", Integer, primary_key=True),
Column("d1", Date),
Column("d2", sqltypes.TIMESTAMP),
)
t.create(engine)
with engine.begin() as conn:
conn.execute(
t.insert(),
{
"d1": datetime.date(2010, 5, 10),
"d2": datetime.datetime(2010, 5, 10, 12, 15, 25),
},
)
row = conn.execute(t.select()).first()
eq_(
row,
(
1,
datetime.date(2010, 5, 10),
datetime.datetime(2010, 5, 10, 12, 15, 25),
),
)
r = conn.execute(func.current_date()).scalar()
assert isinstance(r, str)
@testing.provide_metadata
def test_custom_datetime(self, connection):
sqlite_date = sqlite.DATETIME(
# 2004-05-21T00:00:00
storage_format="%(year)04d-%(month)02d-%(day)02d"
"T%(hour)02d:%(minute)02d:%(second)02d",
regexp=r"^(\d+)-(\d+)-(\d+)T(\d+):(\d+):(\d+)$",
)
t = Table("t", self.metadata, Column("d", sqlite_date))
self.metadata.create_all(connection)
connection.execute(
t.insert().values(d=datetime.datetime(2010, 10, 15, 12, 37, 0))
)
connection.exec_driver_sql(
"insert into t (d) values ('2004-05-21T00:00:00')"
)
eq_(
connection.exec_driver_sql(
"select * from t order by d"
).fetchall(),
[("2004-05-21T00:00:00",), ("2010-10-15T12:37:00",)],
)
eq_(
connection.execute(select(t.c.d).order_by(t.c.d)).fetchall(),
[
(datetime.datetime(2004, 5, 21, 0, 0),),
(datetime.datetime(2010, 10, 15, 12, 37),),
],
)
@testing.provide_metadata
def test_custom_datetime_text_affinity(self, connection):
sqlite_date = sqlite.DATETIME(
storage_format="%(year)04d%(month)02d%(day)02d"
"%(hour)02d%(minute)02d%(second)02d",
regexp=r"^(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})$",
)
t = Table("t", self.metadata, Column("d", sqlite_date))
self.metadata.create_all(connection)
connection.execute(
t.insert().values(d=datetime.datetime(2010, 10, 15, 12, 37, 0))
)
connection.exec_driver_sql(
"insert into t (d) values ('20040521000000')"
)
eq_(
connection.exec_driver_sql(
"select * from t order by d"
).fetchall(),
[("20040521000000",), ("20101015123700",)],
)
eq_(
connection.execute(select(t.c.d).order_by(t.c.d)).fetchall(),
[
(datetime.datetime(2004, 5, 21, 0, 0),),
(datetime.datetime(2010, 10, 15, 12, 37),),
],
)
@testing.provide_metadata
def test_custom_date_text_affinity(self, connection):
sqlite_date = sqlite.DATE(
storage_format="%(year)04d%(month)02d%(day)02d",
regexp=r"(\d{4})(\d{2})(\d{2})",
)
t = Table("t", self.metadata, Column("d", sqlite_date))
self.metadata.create_all(connection)
connection.execute(t.insert().values(d=datetime.date(2010, 10, 15)))
connection.exec_driver_sql("insert into t (d) values ('20040521')")
eq_(
connection.exec_driver_sql(
"select * from t order by d"
).fetchall(),
[("20040521",), ("20101015",)],
)
eq_(
connection.execute(select(t.c.d).order_by(t.c.d)).fetchall(),
[(datetime.date(2004, 5, 21),), (datetime.date(2010, 10, 15),)],
)
@testing.provide_metadata
def test_custom_date(self, connection):
sqlite_date = sqlite.DATE(
# 2004-05-21T00:00:00
storage_format="%(year)04d|%(month)02d|%(day)02d",
regexp=r"(\d+)\|(\d+)\|(\d+)",
)
t = Table("t", self.metadata, Column("d", sqlite_date))
self.metadata.create_all(connection)
connection.execute(t.insert().values(d=datetime.date(2010, 10, 15)))
connection.exec_driver_sql("insert into t (d) values ('2004|05|21')")
eq_(
connection.exec_driver_sql(
"select * from t order by d"
).fetchall(),
[("2004|05|21",), ("2010|10|15",)],
)
eq_(
connection.execute(select(t.c.d).order_by(t.c.d)).fetchall(),
[(datetime.date(2004, 5, 21),), (datetime.date(2010, 10, 15),)],
)
def test_no_convert_unicode(self):
"""test no utf-8 encoding occurs"""
dialect = sqlite.dialect()
for t in (
String(),
sqltypes.CHAR(),
sqltypes.Unicode(),
sqltypes.UnicodeText(),
String(),
sqltypes.CHAR(),
sqltypes.Unicode(),
sqltypes.UnicodeText(),
):
bindproc = t.dialect_impl(dialect).bind_processor(dialect)
assert not bindproc or isinstance(bindproc("some string"), str)
class JSONTest(fixtures.TestBase):
__requires__ = ("json_type",)
__only_on__ = "sqlite"
__backend__ = True
@testing.requires.reflects_json_type
def test_reflection(self, connection, metadata):
Table("json_test", metadata, Column("foo", sqlite.JSON))
metadata.create_all(connection)
reflected = Table("json_test", MetaData(), autoload_with=connection)
is_(reflected.c.foo.type._type_affinity, sqltypes.JSON)
assert isinstance(reflected.c.foo.type, sqlite.JSON)
def test_rudimentary_roundtrip(self, metadata, connection):
sqlite_json = Table("json_test", metadata, Column("foo", sqlite.JSON))
metadata.create_all(connection)
value = {"json": {"foo": "bar"}, "recs": ["one", "two"]}
connection.execute(sqlite_json.insert(), dict(foo=value))
eq_(connection.scalar(select(sqlite_json.c.foo)), value)
def test_extract_subobject(self, connection, metadata):
sqlite_json = Table("json_test", metadata, Column("foo", sqlite.JSON))
metadata.create_all(connection)
value = {"json": {"foo": "bar"}}
connection.execute(sqlite_json.insert(), dict(foo=value))
eq_(
connection.scalar(select(sqlite_json.c.foo["json"])), value["json"]
)
def test_deprecated_serializer_args(self, metadata):
sqlite_json = Table("json_test", metadata, Column("foo", sqlite.JSON))
data_element = {"foo": "bar"}
js = mock.Mock(side_effect=json.dumps)
jd = mock.Mock(side_effect=json.loads)
with testing.expect_deprecated(
"The _json_deserializer argument to the SQLite "
"dialect has been renamed",
"The _json_serializer argument to the SQLite "
"dialect has been renamed",
):
engine = engines.testing_engine(
options=dict(_json_serializer=js, _json_deserializer=jd)
)
metadata.create_all(engine)
with engine.begin() as conn:
conn.execute(sqlite_json.insert(), {"foo": data_element})
row = conn.execute(select(sqlite_json.c.foo)).first()
eq_(row, (data_element,))
eq_(js.mock_calls, [mock.call(data_element)])
eq_(jd.mock_calls, [mock.call(json.dumps(data_element))])
class DateTimeTest(fixtures.TestBase, AssertsCompiledSQL):
def test_time_microseconds(self):
dt = datetime.datetime(2008, 6, 27, 12, 0, 0, 125)
eq_(str(dt), "2008-06-27 12:00:00.000125")
sldt = sqlite.DATETIME()
bp = sldt.bind_processor(None)
eq_(bp(dt), "2008-06-27 12:00:00.000125")
rp = sldt.result_processor(None, None)
eq_(rp(bp(dt)), dt)
def test_truncate_microseconds(self):
dt = datetime.datetime(2008, 6, 27, 12, 0, 0, 125)
dt_out = datetime.datetime(2008, 6, 27, 12, 0, 0)
eq_(str(dt), "2008-06-27 12:00:00.000125")
sldt = sqlite.DATETIME(truncate_microseconds=True)
bp = sldt.bind_processor(None)
eq_(bp(dt), "2008-06-27 12:00:00")
rp = sldt.result_processor(None, None)
eq_(rp(bp(dt)), dt_out)
def test_custom_format_compact(self):
dt = datetime.datetime(2008, 6, 27, 12, 0, 0, 125)
eq_(str(dt), "2008-06-27 12:00:00.000125")
sldt = sqlite.DATETIME(
storage_format=(
"%(year)04d%(month)02d%(day)02d"
"%(hour)02d%(minute)02d%(second)02d%(microsecond)06d"
),
regexp=r"(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})(\d{6})",
)
bp = sldt.bind_processor(None)
eq_(bp(dt), "20080627120000000125")
rp = sldt.result_processor(None, None)
eq_(rp(bp(dt)), dt)
class DateTest(fixtures.TestBase, AssertsCompiledSQL):
def test_default(self):
dt = datetime.date(2008, 6, 27)
eq_(str(dt), "2008-06-27")
sldt = sqlite.DATE()
bp = sldt.bind_processor(None)
eq_(bp(dt), "2008-06-27")
rp = sldt.result_processor(None, None)
eq_(rp(bp(dt)), dt)
def test_custom_format(self):
dt = datetime.date(2008, 6, 27)
eq_(str(dt), "2008-06-27")
sldt = sqlite.DATE(
storage_format="%(month)02d/%(day)02d/%(year)04d",
regexp=r"(?P<month>\d+)/(?P<day>\d+)/(?P<year>\d+)",
)
bp = sldt.bind_processor(None)
eq_(bp(dt), "06/27/2008")
rp = sldt.result_processor(None, None)
eq_(rp(bp(dt)), dt)
class TimeTest(fixtures.TestBase, AssertsCompiledSQL):
def test_default(self):
dt = datetime.date(2008, 6, 27)
eq_(str(dt), "2008-06-27")
sldt = sqlite.DATE()
bp = sldt.bind_processor(None)
eq_(bp(dt), "2008-06-27")
rp = sldt.result_processor(None, None)
eq_(rp(bp(dt)), dt)
def test_truncate_microseconds(self):
dt = datetime.time(12, 0, 0, 125)
dt_out = datetime.time(12, 0, 0)
eq_(str(dt), "12:00:00.000125")
sldt = sqlite.TIME(truncate_microseconds=True)
bp = sldt.bind_processor(None)
eq_(bp(dt), "12:00:00")
rp = sldt.result_processor(None, None)
eq_(rp(bp(dt)), dt_out)
def test_custom_format(self):
dt = datetime.date(2008, 6, 27)
eq_(str(dt), "2008-06-27")
sldt = sqlite.DATE(
storage_format="%(year)04d%(month)02d%(day)02d",
regexp=r"(\d{4})(\d{2})(\d{2})",
)
bp = sldt.bind_processor(None)
eq_(bp(dt), "20080627")
rp = sldt.result_processor(None, None)
eq_(rp(bp(dt)), dt)
class DefaultsTest(fixtures.TestBase, AssertsCompiledSQL):
__only_on__ = "sqlite"
__backend__ = True
def test_default_reflection(self, connection, metadata):
specs = [
(String(3), '"foo"'),
(sqltypes.NUMERIC(10, 2), "100.50"),
(Integer, "5"),
(Boolean, "False"),
]
columns = [
Column("c%i" % (i + 1), t[0], server_default=text(t[1]))
for (i, t) in enumerate(specs)
]
Table("t_defaults", metadata, *columns)
metadata.create_all(connection)
m2 = MetaData()
rt = Table("t_defaults", m2, autoload_with=connection)
expected = [c[1] for c in specs]
for i, reflected in enumerate(rt.c):
eq_(str(reflected.server_default.arg), expected[i])
@testing.exclude(
"sqlite",
"<",
(3, 3, 8),
"sqlite3 changesets 3353 and 3440 modified "
"behavior of default displayed in pragma "
"table_info()",
)
def test_default_reflection_2(self):
db = testing.db
m = MetaData()
expected = ["'my_default'", "0"]
table = """CREATE TABLE r_defaults (
data VARCHAR(40) DEFAULT 'my_default',
val INTEGER NOT NULL DEFAULT 0
)"""
try:
exec_sql(db, table)
rt = Table("r_defaults", m, autoload_with=db)
for i, reflected in enumerate(rt.c):
eq_(str(reflected.server_default.arg), expected[i])
finally:
exec_sql(db, "DROP TABLE r_defaults")
def test_default_reflection_3(self):
db = testing.db
table = """CREATE TABLE r_defaults (
data VARCHAR(40) DEFAULT 'my_default',
val INTEGER NOT NULL DEFAULT 0
)"""
try:
exec_sql(db, table)
m1 = MetaData()
t1 = Table("r_defaults", m1, autoload_with=db)
exec_sql(db, "DROP TABLE r_defaults")
t1.create(db)
m2 = MetaData()
t2 = Table("r_defaults", m2, autoload_with=db)
self.assert_compile(
CreateTable(t2),
"CREATE TABLE r_defaults (data VARCHAR(40) "
"DEFAULT 'my_default', val INTEGER DEFAULT 0 "
"NOT NULL)",
)
finally:
exec_sql(db, "DROP TABLE r_defaults")
@testing.provide_metadata
def test_boolean_default(self):
t = Table(
"t",
self.metadata,
Column("x", Boolean, server_default=sql.false()),
)
t.create(testing.db)
with testing.db.begin() as conn:
conn.execute(t.insert())
conn.execute(t.insert().values(x=True))
eq_(
conn.execute(t.select().order_by(t.c.x)).fetchall(),
[(False,), (True,)],
)
@testing.provide_metadata
def test_function_default(self):
t = Table(
"t",
self.metadata,
Column("id", Integer, primary_key=True),
Column("x", String(), server_default=func.lower("UPPERCASE")),
)
t.create(testing.db)
with testing.db.begin() as conn:
conn.execute(t.insert())
conn.execute(t.insert().values(x="foobar"))
eq_(
conn.execute(select(t.c.x).order_by(t.c.id)).fetchall(),
[("uppercase",), ("foobar",)],
)
@testing.provide_metadata
def test_expression_with_function_default(self):
t = Table(
"t",
self.metadata,
Column("id", Integer, primary_key=True),
Column("x", Integer(), server_default=func.abs(-5) + 17),
)
t.create(testing.db)
with testing.db.begin() as conn:
conn.execute(t.insert())
conn.execute(t.insert().values(x=35))
eq_(
conn.execute(select(t.c.x).order_by(t.c.id)).fetchall(),
[(22,), (35,)],
)
def test_old_style_default(self):
"""test non-quoted integer value on older sqlite pragma"""
dialect = sqlite.dialect()
info = dialect._get_column_info(
"foo", "INTEGER", False, 3, False, False, False, None
)
eq_(info["default"], "3")
class DialectTest(
fixtures.TestBase, AssertsExecutionResults, AssertsCompiledSQL
):
__only_on__ = "sqlite"
__backend__ = True
def test_3_7_16_warning(self):
with expect_warnings(
r"SQLite version \(3, 2, 8\) is older than 3.7.16, and "
"will not support right nested joins"
):
sqlite.dialect(
dbapi=mock.Mock(
version_info=(2, 6, 0), sqlite_version_info=(3, 2, 8)
)
)
@testing.only_on("sqlite+pysqlcipher")
def test_pysqlcipher_connects(self):
"""test #6586"""
str_url = str(testing.db.url)
e = create_engine(str_url)
with e.connect() as conn:
eq_(conn.scalar(text("select 1")), 1)
@testing.provide_metadata
def test_extra_reserved_words(self, connection):
"""Tests reserved words in identifiers.
'true', 'false', and 'column' are undocumented reserved words
when used as column identifiers (as of 3.5.1). Covering them
here to ensure they remain in place if the dialect's
reserved_words set is updated in the future."""
t = Table(
"reserved",
self.metadata,
Column("safe", Integer),
Column("true", Integer),
Column("false", Integer),
Column("column", Integer),
Column("exists", Integer),
)
self.metadata.create_all(connection)
connection.execute(t.insert(), dict(safe=1))
result = connection.execute(t.select())
eq_(list(result), [(1, None, None, None, None)])
@testing.provide_metadata
def test_quoted_identifiers_functional_one(self):
"""Tests autoload of tables created with quoted column names."""
metadata = self.metadata
exec_sql(
testing.db,
"""CREATE TABLE "django_content_type" (
"id" integer NOT NULL PRIMARY KEY,
"django_stuff" text NULL
)
""",
)
exec_sql(
testing.db,
"""
CREATE TABLE "django_admin_log" (
"id" integer NOT NULL PRIMARY KEY,
"action_time" datetime NOT NULL,
"content_type_id" integer NULL
REFERENCES "django_content_type" ("id"),
"object_id" text NULL,
"change_message" text NOT NULL
)
""",
)
table1 = Table("django_admin_log", metadata, autoload_with=testing.db)
table2 = Table(
"django_content_type", metadata, autoload_with=testing.db
)
j = table1.join(table2)
assert j.onclause.compare(table1.c.content_type_id == table2.c.id)
@testing.provide_metadata
def test_quoted_identifiers_functional_two(self):
"""test the edgiest of edge cases, quoted table/col names
that start and end with quotes.
SQLite claims to have fixed this in
https://www.sqlite.org/src/info/600482d161, however
it still fails if the FK points to a table name that actually
has quotes as part of its name.
"""
metadata = self.metadata
exec_sql(
testing.db,
r'''CREATE TABLE """a""" (
"""id""" integer NOT NULL PRIMARY KEY
)
''',
)
# unfortunately, still can't do this; sqlite quadruples
# up the quotes on the table name here for pragma foreign_key_list
# exec_sql(testing.db,r'''
# CREATE TABLE """b""" (
# """id""" integer NOT NULL PRIMARY KEY,
# """aid""" integer NULL
# REFERENCES """a""" ("""id""")
# )
# ''')
table1 = Table(r'"a"', metadata, autoload_with=testing.db)
assert '"id"' in table1.c
@testing.provide_metadata
def test_description_encoding(self, connection):
t = Table(
"x",
self.metadata,
Column("méil", Integer, primary_key=True),
Column("\u6e2c\u8a66", Integer),
)
self.metadata.create_all(testing.db)
result = connection.execute(t.select())
assert "méil" in result.keys()
assert "\u6e2c\u8a66" in result.keys()
def test_pool_class(self):
e = create_engine("sqlite+pysqlite://")
assert e.pool.__class__ is pool.SingletonThreadPool
e = create_engine("sqlite+pysqlite:///:memory:")
assert e.pool.__class__ is pool.SingletonThreadPool
e = create_engine(
"sqlite+pysqlite:///file:foo.db?mode=memory&uri=true"
)
assert e.pool.__class__ is pool.SingletonThreadPool
e = create_engine("sqlite+pysqlite:///foo.db")
# changed as of 2.0 #7490
assert e.pool.__class__ is pool.QueuePool
@combinations(
(
"sqlite:///foo.db", # file path is absolute
([os.path.abspath("foo.db")], {"check_same_thread": False}),
),
(
"sqlite:////abs/path/to/foo.db",
(
[os.path.abspath("/abs/path/to/foo.db")],
{"check_same_thread": False},
),
),
("sqlite://", ([":memory:"], {"check_same_thread": True})),
(
"sqlite:///?check_same_thread=true",
([":memory:"], {"check_same_thread": True}),
),
(
"sqlite:///file:path/to/database?"
"check_same_thread=true&timeout=10&mode=ro&nolock=1&uri=true",
(
["file:path/to/database?mode=ro&nolock=1"],
{"check_same_thread": True, "timeout": 10.0, "uri": True},
),
),
(
"sqlite:///file:path/to/database?mode=ro&uri=true",
(
["file:path/to/database?mode=ro"],
{"uri": True, "check_same_thread": False},
),
),
(
"sqlite:///file:path/to/database?uri=true",
(
["file:path/to/database"],
{"uri": True, "check_same_thread": False},
),
),
)
def test_connect_args(self, url, expected):
"""test create_connect_args scenarios including support for uri=True"""
d = pysqlite_dialect.dialect()
url = make_url(url)
eq_(d.create_connect_args(url), expected)
@testing.combinations(
("no_persisted", "", "ignore"),
("persisted_none", "", None),
("persisted_true", " STORED", True),
("persisted_false", " VIRTUAL", False),
id_="iaa",
)
def test_column_computed(self, text, persisted):
m = MetaData()
kwargs = {"persisted": persisted} if persisted != "ignore" else {}
t = Table(
"t",
m,
Column("x", Integer),
Column("y", Integer, Computed("x + 2", **kwargs)),
)
self.assert_compile(
schema.CreateTable(t),
"CREATE TABLE t (x INTEGER,"
" y INTEGER GENERATED ALWAYS AS (x + 2)%s)" % text,
)
class AttachedDBTest(fixtures.TablesTest):
__only_on__ = "sqlite"
__backend__ = True
run_create_tables = "each"
@classmethod
def define_tables(self, metadata):
meta = metadata
Table("created", meta, Column("foo", Integer), Column("bar", String))
Table("local_only", meta, Column("q", Integer), Column("p", Integer))
Table(
"created",
meta,
Column("id", Integer),
Column("name", String),
schema="test_schema",
)
Table(
"another_created",
meta,
Column("bat", Integer),
Column("hoho", String),
schema="test_schema",
)
def test_no_tables(self, connection):
tt = self.tables("test_schema.created", "test_schema.another_created")
for t in tt:
t.drop(connection)
insp = inspect(connection)
eq_(insp.get_table_names("test_schema"), [])
def test_column_names(self, connection):
insp = inspect(connection)
eq_(
[
d["name"]
for d in insp.get_columns("created", schema="test_schema")
],
["id", "name"],
)
eq_(
[d["name"] for d in insp.get_columns("created", schema=None)],
["foo", "bar"],
)
with expect_raises(exc.NoSuchTableError):
insp.get_columns("nonexistent", schema="test_schema")
with expect_raises(exc.NoSuchTableError):
insp.get_columns("another_created", schema=None)
with expect_raises(exc.NoSuchTableError):
insp.get_columns("local_only", schema="test_schema")
eq_([d["name"] for d in insp.get_columns("local_only")], ["q", "p"])
def test_table_names_present(self, connection):
insp = inspect(connection)
eq_(
set(insp.get_table_names("test_schema")),
{"created", "another_created"},
)
def test_table_names_system(self, connection):
insp = inspect(connection)
eq_(
set(insp.get_table_names("test_schema")),
{"created", "another_created"},
)
def test_schema_names(self, connection):
insp = inspect(connection)
eq_(insp.get_schema_names(), ["main", "test_schema"])
# implicitly creates a "temp" schema
connection.exec_driver_sql("select * from sqlite_temp_master")
# we're not including it
insp = inspect(connection)
eq_(insp.get_schema_names(), ["main", "test_schema"])
def test_reflect_system_table(self, connection):
meta = MetaData()
alt_master = Table(
"sqlite_master",
meta,
autoload_with=connection,
schema="test_schema",
)
assert len(alt_master.c) > 0
def test_reflect_user_table(self, connection):
m2 = MetaData()
c2 = Table("created", m2, autoload_with=connection)
eq_(len(c2.c), 2)
def test_crud(self, connection):
(ct,) = self.tables("test_schema.created")
connection.execute(ct.insert(), {"id": 1, "name": "foo"})
eq_(connection.execute(ct.select()).fetchall(), [(1, "foo")])
connection.execute(ct.update(), {"id": 2, "name": "bar"})
eq_(connection.execute(ct.select()).fetchall(), [(2, "bar")])
connection.execute(ct.delete())
eq_(connection.execute(ct.select()).fetchall(), [])
def test_col_targeting(self, connection):
(ct,) = self.tables("test_schema.created")
connection.execute(ct.insert(), {"id": 1, "name": "foo"})
row = connection.execute(ct.select()).first()
eq_(row._mapping["id"], 1)
eq_(row._mapping["name"], "foo")
def test_col_targeting_union(self, connection):
(ct,) = self.tables("test_schema.created")
connection.execute(ct.insert(), {"id": 1, "name": "foo"})
row = connection.execute(ct.select().union(ct.select())).first()
eq_(row._mapping["id"], 1)
eq_(row._mapping["name"], "foo")
class SQLTest(fixtures.TestBase, AssertsCompiledSQL):
"""Tests SQLite-dialect specific compilation."""
__dialect__ = sqlite.dialect()
def test_extract(self):
t = sql.table("t", sql.column("col1"))
mapping = {
"month": "%m",
"day": "%d",
"year": "%Y",
"second": "%S",
"hour": "%H",
"doy": "%j",
"minute": "%M",
"epoch": "%s",
"dow": "%w",
"week": "%W",
}
for field, subst in mapping.items():
self.assert_compile(
select(extract(field, t.c.col1)),
"SELECT CAST(STRFTIME('%s', t.col1) AS "
"INTEGER) AS anon_1 FROM t" % subst,
)
def test_plain_stringify_returning(self):
t = Table(
"t",
MetaData(),
Column("myid", Integer, primary_key=True),
Column("name", String, server_default="some str"),
Column("description", String, default=func.lower("hi")),
)
stmt = t.insert().values().return_defaults()
eq_ignore_whitespace(
str(stmt.compile(dialect=sqlite.SQLiteDialect())),
"INSERT INTO t (description) VALUES (lower(?)) "
"RETURNING myid, name, description",
)
def test_true_false(self):
self.assert_compile(sql.false(), "0")
self.assert_compile(sql.true(), "1")
def test_is_distinct_from(self):
self.assert_compile(
sql.column("x").is_distinct_from(None), "x IS NOT NULL"
)
self.assert_compile(
sql.column("x").is_not_distinct_from(False), "x IS 0"
)
def test_localtime(self):
self.assert_compile(
func.localtimestamp(), 'DATETIME(CURRENT_TIMESTAMP, "localtime")'
)
def test_constraints_with_schemas(self):
metadata = MetaData()
Table(
"t1",
metadata,
Column("id", Integer, primary_key=True),
schema="master",
)
t2 = Table(
"t2",
metadata,
Column("id", Integer, primary_key=True),
Column("t1_id", Integer, ForeignKey("master.t1.id")),
schema="master",
)
t3 = Table(
"t3",
metadata,
Column("id", Integer, primary_key=True),
Column("t1_id", Integer, ForeignKey("master.t1.id")),
schema="alternate",
)
t4 = Table(
"t4",
metadata,
Column("id", Integer, primary_key=True),
Column("t1_id", Integer, ForeignKey("master.t1.id")),