This repository was archived by the owner on Mar 13, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 35
Expand file tree
/
Copy pathtest_suite_20.py
More file actions
3321 lines (2834 loc) · 111 KB
/
test_suite_20.py
File metadata and controls
3321 lines (2834 loc) · 111 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 -*-
#
# Copyright 2023 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from datetime import timezone
import decimal
import operator
import os
import pytest
import random
import time
from unittest import mock
from google.cloud.spanner_v1 import RequestOptions, Client
import sqlalchemy
from sqlalchemy import create_engine, literal, FLOAT
from sqlalchemy.engine import Inspector
from sqlalchemy import inspect
from sqlalchemy import testing
from sqlalchemy import ForeignKey
from sqlalchemy import MetaData
from sqlalchemy.engine import ObjectKind
from sqlalchemy.engine import ObjectScope
from sqlalchemy.schema import DDL
from sqlalchemy.schema import Computed
from sqlalchemy.testing import config
from sqlalchemy.testing import engines
from sqlalchemy.testing import eq_
from sqlalchemy.testing import is_instance_of
from sqlalchemy.testing import provide_metadata, emits_warning
from sqlalchemy.testing import is_true
from sqlalchemy.testing import fixtures
from sqlalchemy.testing.provision import temp_table_keyword_args
from sqlalchemy.testing.schema import Column
from sqlalchemy.testing.schema import Table
from sqlalchemy import literal_column
from sqlalchemy import select
from sqlalchemy import util
from sqlalchemy import union
from sqlalchemy import event
from sqlalchemy import exists
from sqlalchemy import Boolean
from sqlalchemy import Float
from sqlalchemy import LargeBinary
from sqlalchemy import String
from sqlalchemy.sql.expression import cast
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship
from sqlalchemy.orm import Session
from sqlalchemy.types import Integer
from sqlalchemy.types import Numeric
from sqlalchemy.types import Text
from sqlalchemy.testing import requires
from sqlalchemy import Index
from sqlalchemy import types
from sqlalchemy.testing.fixtures import (
ComputedReflectionFixtureTest as _ComputedReflectionFixtureTest,
)
from google.api_core.datetime_helpers import DatetimeWithNanoseconds
from google.cloud import spanner_dbapi
from sqlalchemy.testing.suite.test_cte import * # noqa: F401, F403
from sqlalchemy.testing.suite.test_ddl import * # noqa: F401, F403
from sqlalchemy.testing.suite.test_dialect import * # noqa: F401, F403
from sqlalchemy.testing.suite.test_insert import * # noqa: F401, F403
from sqlalchemy.testing.suite.test_reflection import * # noqa: F401, F403
from sqlalchemy.testing.suite.test_deprecations import * # noqa: F401, F403
from sqlalchemy.testing.suite.test_results import * # noqa: F401, F403
from sqlalchemy.testing.suite.test_select import (
BitwiseTest as _BitwiseTest,
) # noqa: F401, F403
from sqlalchemy.testing.suite.test_sequence import (
SequenceTest as _SequenceTest,
HasSequenceTest as _HasSequenceTest,
HasSequenceTestEmpty as _HasSequenceTestEmpty,
) # noqa: F401, F403
from sqlalchemy.testing.suite.test_unicode_ddl import * # noqa: F401, F403
from sqlalchemy.testing.suite.test_update_delete import * # noqa: F401, F403
from sqlalchemy.testing.suite.test_cte import CTETest as _CTETest
from sqlalchemy.testing.suite.test_ddl import TableDDLTest as _TableDDLTest
from sqlalchemy.testing.suite.test_ddl import (
FutureTableDDLTest as _FutureTableDDLTest,
LongNameBlowoutTest as _LongNameBlowoutTest,
)
from sqlalchemy.testing.suite.test_update_delete import (
SimpleUpdateDeleteTest as _SimpleUpdateDeleteTest,
)
from sqlalchemy.testing.suite.test_dialect import (
DifficultParametersTest as _DifficultParametersTest,
EscapingTest as _EscapingTest,
ReturningGuardsTest as _ReturningGuardsTest,
)
from sqlalchemy.testing.suite.test_insert import (
InsertBehaviorTest as _InsertBehaviorTest,
)
from sqlalchemy.testing.suite.test_select import ( # noqa: F401, F403
CompoundSelectTest as _CompoundSelectTest,
ExistsTest as _ExistsTest,
FetchLimitOffsetTest as _FetchLimitOffsetTest,
IdentityAutoincrementTest as _IdentityAutoincrementTest,
IsOrIsNotDistinctFromTest as _IsOrIsNotDistinctFromTest,
LikeFunctionsTest as _LikeFunctionsTest,
OrderByLabelTest as _OrderByLabelTest,
PostCompileParamsTest as _PostCompileParamsTest,
SameNamedSchemaTableTest as _SameNamedSchemaTableTest,
)
from sqlalchemy.testing.suite.test_reflection import ( # noqa: F401, F403
ComponentReflectionTestExtra as _ComponentReflectionTestExtra,
QuotedNameArgumentTest as _QuotedNameArgumentTest,
ComponentReflectionTest as _ComponentReflectionTest,
CompositeKeyReflectionTest as _CompositeKeyReflectionTest,
ComputedReflectionTest as _ComputedReflectionTest,
HasIndexTest as _HasIndexTest,
HasTableTest as _HasTableTest,
)
from sqlalchemy.testing.suite.test_results import (
RowFetchTest as _RowFetchTest,
)
from sqlalchemy.testing.suite.test_types import ( # noqa: F401, F403
BooleanTest as _BooleanTest,
DateTest as _DateTest,
_DateFixture as __DateFixture,
DateTimeHistoricTest,
DateTimeCoercedToDateTimeTest as _DateTimeCoercedToDateTimeTest,
DateTimeMicrosecondsTest as _DateTimeMicrosecondsTest,
DateTimeTest as _DateTimeTest,
IntegerTest as _IntegerTest,
JSONTest as _JSONTest,
_LiteralRoundTripFixture,
NumericTest as _NumericTest,
StringTest as _StringTest,
TextTest as _TextTest,
TimeTest as _TimeTest,
TimeMicrosecondsTest as _TimeMicrosecondsTest,
TimestampMicrosecondsTest,
UnicodeVarcharTest as _UnicodeVarcharTest,
UnicodeTextTest as _UnicodeTextTest,
_UnicodeFixture as __UnicodeFixture,
) # noqa: F401, F403
from test._helpers import (
get_db_url,
get_project,
)
from google.cloud.sqlalchemy_spanner import version as sqlalchemy_spanner_version
config.test_schema = ""
class BooleanTest(_BooleanTest):
@pytest.mark.skip(
"The original test case was split into 2 parts: "
"test_render_literal_bool_true and test_render_literal_bool_false"
)
def test_render_literal_bool(self):
pass
def test_render_literal_bool_true(self, literal_round_trip_spanner):
"""
SPANNER OVERRIDE:
Cloud Spanner supports tables with an empty primary key, but
only a single row can be inserted into such a table -
following insertions will fail with `Row [] already exists".
Overriding the test to avoid the same failure.
"""
literal_round_trip_spanner(Boolean(), [True], [True])
def test_render_literal_bool_false(self, literal_round_trip_spanner):
"""
SPANNER OVERRIDE:
Cloud Spanner supports tables with an empty primary key, but
only a single row can be inserted into such a table -
following insertions will fail with `Row [] already exists".
Overriding the test to avoid the same failure.
"""
literal_round_trip_spanner(Boolean(), [False], [False])
@pytest.mark.skip("Not supported by Cloud Spanner")
def test_whereclause(self):
pass
class BitwiseTest(_BitwiseTest):
@pytest.mark.skip("Causes too many problems with other tests")
def test_bitwise(self, case, expected, connection):
pass
class ComponentReflectionTestExtra(_ComponentReflectionTestExtra):
@testing.requires.table_reflection
def test_nullable_reflection(self, connection, metadata):
t = Table(
"t",
metadata,
Column("a", Integer, nullable=True),
Column("b", Integer, nullable=False),
)
t.create(connection)
connection.connection.commit()
eq_(
dict(
(col["name"], col["nullable"])
for col in inspect(connection).get_columns("t")
),
{"a": True, "b": False},
)
def _type_round_trip(self, connection, metadata, *types):
t = Table(
"t", metadata, *[Column("t%d" % i, type_) for i, type_ in enumerate(types)]
)
t.create(connection)
connection.connection.commit()
return [c["type"] for c in inspect(connection).get_columns("t")]
@testing.requires.table_reflection
def test_numeric_reflection(self, connection, metadata):
"""
SPANNER OVERRIDE:
Spanner defines NUMERIC type with the constant precision=38
and scale=9. Overriding the test to check if the NUMERIC
column is successfully created and has dimensions
correct for Cloud Spanner.
"""
for typ in self._type_round_trip(connection, metadata, Numeric(18, 5)):
assert isinstance(typ, Numeric)
eq_(typ.precision, 38)
eq_(typ.scale, 9)
@testing.requires.table_reflection
def test_binary_reflection(self, connection, metadata):
"""
Check that a BYTES column with an explicitly
set size is correctly reflected.
"""
for typ in self._type_round_trip(connection, metadata, LargeBinary(20)):
assert isinstance(typ, LargeBinary)
eq_(typ.length, 20)
@testing.requires.table_reflection
def test_string_length_reflection(self, connection, metadata):
typ = self._type_round_trip(connection, metadata, types.String(52))[0]
assert isinstance(typ, types.String)
class ComputedReflectionFixtureTest(_ComputedReflectionFixtureTest):
@classmethod
def define_tables(cls, metadata):
"""SPANNER OVERRIDE:
Avoid using default values for computed columns.
"""
Table(
"computed_default_table",
metadata,
Column("id", Integer, primary_key=True),
Column("normal", Integer),
Column("computed_col", Integer, Computed("normal + 42")),
Column("with_default", Integer),
)
t = Table(
"computed_column_table",
metadata,
Column("id", Integer, primary_key=True),
Column("normal", Integer),
Column("computed_no_flag", Integer, Computed("normal + 42")),
)
if testing.requires.computed_columns_virtual.enabled:
t.append_column(
Column(
"computed_virtual",
Integer,
Computed("normal + 2", persisted=False),
)
)
if testing.requires.computed_columns_stored.enabled:
t.append_column(
Column(
"computed_stored",
Integer,
Computed("normal - 42", persisted=True),
)
)
class ComputedReflectionTest(_ComputedReflectionTest, ComputedReflectionFixtureTest):
@testing.requires.schemas
def test_get_column_returns_persisted_with_schema(self):
insp = inspect(config.db)
cols = insp.get_columns("computed_column_table", schema=config.test_schema)
data = {c["name"]: c for c in cols}
self.check_column(
data,
"computed_no_flag",
"normal+42",
testing.requires.computed_columns_default_persisted.enabled,
)
if testing.requires.computed_columns_virtual.enabled:
self.check_column(
data,
"computed_virtual",
"normal/2",
False,
)
if testing.requires.computed_columns_stored.enabled:
self.check_column(
data,
"computed_stored",
"normal-42",
True,
)
@pytest.mark.skip("Default values are not supported.")
def test_computed_col_default_not_set(self):
pass
def test_get_column_returns_computed(self):
"""
SPANNER OVERRIDE:
In Spanner all the generated columns are STORED,
meaning there are no persisted and not persisted
(in the terms of the SQLAlchemy) columns. The
method override omits the persistence reflection checks.
"""
insp = inspect(config.db)
cols = insp.get_columns("computed_default_table")
data = {c["name"]: c for c in cols}
for key in ("id", "normal", "with_default"):
is_true("computed" not in data[key])
compData = data["computed_col"]
is_true("computed" in compData)
is_true("sqltext" in compData["computed"])
eq_(self.normalize(compData["computed"]["sqltext"]), "normal+42")
def test_create_not_null_computed_column(self, connection):
"""
SPANNER TEST:
Check that on creating a computed column with a NOT NULL
clause the clause is set in front of the computed column
statement definition and doesn't cause failures.
"""
metadata = MetaData()
Table(
"Singers",
metadata,
Column("SingerId", String(36), primary_key=True, nullable=False),
Column("FirstName", String(200)),
Column("LastName", String(200), nullable=False),
Column(
"FullName",
String(400),
Computed("COALESCE(FirstName || ' ', '') || LastName"),
nullable=False,
),
)
metadata.create_all(connection)
class ComponentReflectionTest(_ComponentReflectionTest):
@pytest.mark.skip("Skip")
def test_not_existing_table(self, method, connection):
pass
@classmethod
def define_tables(cls, metadata):
cls.define_reflected_tables(metadata, None)
@classmethod
def define_views(cls, metadata, schema):
table_info = {
"dingalings": [
"dingaling_id",
"address_id",
"data",
"id_user",
],
"users": ["user_id", "test1", "test2"],
"email_addresses": ["address_id", "remote_user_id", "email_address"],
}
if testing.requires.self_referential_foreign_keys.enabled:
table_info["users"] = table_info["users"] + ["parent_user_id"]
if testing.requires.materialized_views.enabled:
materialized = {"dingalings"}
else:
materialized = set()
for table_name in ("users", "email_addresses", "dingalings"):
fullname = table_name
if schema:
fullname = f"{schema}.{table_name}"
view_name = fullname + "_v"
prefix = "MATERIALIZED " if table_name in materialized else ""
columns = ""
for column in table_info[table_name]:
stmt = table_name + "." + column + " AS " + column
if columns:
columns = columns + ", " + stmt
else:
columns = stmt
query = f"""CREATE {prefix}VIEW {view_name}
SQL SECURITY INVOKER
AS SELECT {columns}
FROM {fullname}"""
event.listen(metadata, "after_create", DDL(query))
if table_name in materialized:
index_name = "mat_index"
if schema and testing.against("oracle"):
index_name = f"{schema}.{index_name}"
idx = f"CREATE INDEX {index_name} ON {view_name}(data)"
event.listen(metadata, "after_create", DDL(idx))
event.listen(metadata, "before_drop", DDL(f"DROP {prefix}VIEW {view_name}"))
@classmethod
def define_reflected_tables(cls, metadata, schema):
if schema:
schema_prefix = schema + "."
else:
schema_prefix = ""
if testing.requires.self_referential_foreign_keys.enabled:
users = Table(
"users",
metadata,
Column("user_id", sqlalchemy.INT, primary_key=True),
Column("test1", sqlalchemy.CHAR(5), nullable=False),
Column("test2", sqlalchemy.Float(5), nullable=False),
Column(
"parent_user_id",
sqlalchemy.Integer,
sqlalchemy.ForeignKey(
"%susers.user_id" % schema_prefix, name="user_id_fk"
),
),
schema=schema,
test_needs_fk=True,
)
else:
users = Table(
"users",
metadata,
Column("user_id", sqlalchemy.INT, primary_key=True),
Column("test1", sqlalchemy.CHAR(5), nullable=False),
Column("test2", sqlalchemy.Float(5), nullable=False),
schema=schema,
test_needs_fk=True,
)
Table(
"dingalings",
metadata,
Column("dingaling_id", sqlalchemy.Integer, primary_key=True),
Column(
"address_id",
sqlalchemy.Integer,
sqlalchemy.ForeignKey("%semail_addresses.address_id" % schema_prefix),
),
Column(
"id_user",
sqlalchemy.Integer,
sqlalchemy.ForeignKey("%susers.user_id" % schema_prefix),
),
Column("data", sqlalchemy.String(30)),
schema=schema,
test_needs_fk=True,
)
Table(
"email_addresses",
metadata,
Column("address_id", sqlalchemy.Integer, primary_key=True),
Column(
"remote_user_id",
sqlalchemy.Integer,
sqlalchemy.ForeignKey(users.c.user_id),
),
Column("email_address", sqlalchemy.String(20)),
sqlalchemy.PrimaryKeyConstraint("address_id", name="email_ad_pk"),
schema=schema,
test_needs_fk=True,
)
Table(
"comment_test",
metadata,
Column("id", sqlalchemy.Integer, primary_key=True, comment="id comment"),
Column("data", sqlalchemy.String(20), comment="data % comment"),
Column(
"d2",
sqlalchemy.String(20),
comment=r"""Comment types type speedily ' " \ '' Fun!""",
),
schema=schema,
comment=r"""the test % ' " \ table comment""",
)
Table(
"no_constraints",
metadata,
Column("data", sqlalchemy.String(20)),
schema=schema,
)
if testing.requires.cross_schema_fk_reflection.enabled:
if schema is None:
Table(
"local_table",
metadata,
Column("id", sqlalchemy.Integer, primary_key=True),
Column("data", sqlalchemy.String(20)),
Column(
"remote_id",
ForeignKey("%s.remote_table_2.id" % testing.config.test_schema),
),
test_needs_fk=True,
schema=config.db.dialect.default_schema_name,
)
else:
Table(
"remote_table",
metadata,
Column("id", sqlalchemy.Integer, primary_key=True),
Column(
"local_id",
ForeignKey(
"%s.local_table.id" % config.db.dialect.default_schema_name
),
),
Column("data", sqlalchemy.String(20)),
schema=schema,
test_needs_fk=True,
)
Table(
"remote_table_2",
metadata,
Column("id", sqlalchemy.Integer, primary_key=True),
Column("data", sqlalchemy.String(20)),
schema=schema,
test_needs_fk=True,
)
if testing.requires.index_reflection.enabled:
sqlalchemy.Index("users_t_idx", users.c.test1, users.c.test2, unique=True)
sqlalchemy.Index(
"users_all_idx", users.c.user_id, users.c.test2, users.c.test1
)
if not schema:
# test_needs_fk is at the moment to force MySQL InnoDB
noncol_idx_test_nopk = Table(
"noncol_idx_test_nopk",
metadata,
Column("id", sqlalchemy.Integer, primary_key=True),
Column("q", sqlalchemy.String(5)),
test_needs_fk=True,
extend_existing=True,
)
noncol_idx_test_pk = Table(
"noncol_idx_test_pk",
metadata,
Column("id", sqlalchemy.Integer, primary_key=True),
Column("q", sqlalchemy.String(5)),
test_needs_fk=True,
extend_existing=True,
)
if testing.requires.indexes_with_ascdesc.enabled:
sqlalchemy.Index("noncol_idx_nopk", noncol_idx_test_nopk.c.q.desc())
sqlalchemy.Index("noncol_idx_pk", noncol_idx_test_pk.c.q.desc())
if testing.requires.view_column_reflection.enabled and not bool(
os.environ.get("SPANNER_EMULATOR_HOST")
):
cls.define_views(metadata, schema)
@testing.combinations(
(False, False),
(False, True, testing.requires.schemas),
(True, False, testing.requires.view_reflection),
(
True,
True,
testing.requires.schemas + testing.requires.view_reflection,
),
argnames="use_views,use_schema",
)
def test_get_columns(self, connection, use_views, use_schema):
if use_views and bool(os.environ.get("SPANNER_EMULATOR_HOST")):
pytest.skip("Skipped on emulator")
schema = None
users, addresses = (self.tables.users, self.tables.email_addresses)
if use_views:
table_names = ["users_v", "email_addresses_v", "dingalings_v"]
else:
table_names = ["users", "email_addresses"]
insp = inspect(connection)
for table_name, table in zip(table_names, (users, addresses)):
schema_name = schema
cols = insp.get_columns(table_name, schema=schema_name)
is_true(len(cols) > 0, len(cols))
# should be in order
for i, col in enumerate(table.columns):
eq_(col.name, cols[i]["name"])
ctype = cols[i]["type"].__class__
ctype_def = col.type
if isinstance(ctype_def, sqlalchemy.types.TypeEngine):
ctype_def = ctype_def.__class__
# Oracle returns Date for DateTime.
if testing.against("oracle") and ctype_def in (
types.Date,
types.DateTime,
):
ctype_def = types.Date
# assert that the desired type and return type share
# a base within one of the generic types.
is_true(
len(
set(ctype.__mro__)
.intersection(ctype_def.__mro__)
.intersection(
[
types.Integer,
types.Numeric,
types.DateTime,
types.Date,
types.Time,
types.String,
types._Binary,
]
)
)
> 0,
"%s(%s), %s(%s)" % (col.name, col.type, cols[i]["name"], ctype),
)
if not col.primary_key:
assert cols[i]["default"] is None
@pytest.mark.skipif(
bool(os.environ.get("SPANNER_EMULATOR_HOST")), reason="Skipped on emulator"
)
@testing.requires.view_reflection
def test_get_view_definition(
self,
connection,
):
schema = None
insp = inspect(connection)
for view in ["users_v", "email_addresses_v", "dingalings_v"]:
v = insp.get_view_definition(view, schema=schema)
is_true(bool(v))
@pytest.mark.skipif(
bool(os.environ.get("SPANNER_EMULATOR_HOST")), reason="Skipped on emulator"
)
@testing.requires.view_reflection
def test_get_view_definition_does_not_exist(self, connection):
super().test_get_view_definition_does_not_exist(connection)
def filter_name_values():
return testing.combinations(True, False, argnames="use_filter")
@filter_name_values()
@testing.requires.index_reflection
def test_get_multi_indexes(
self,
get_multi_exp,
use_filter,
schema=None,
scope=ObjectScope.DEFAULT,
kind=ObjectKind.TABLE,
):
"""
SPANNER OVERRIDE:
Spanner doesn't support indexes on views and
doesn't support temporary tables, so real tables are
used for testing. As the original test expects only real
tables to be read, and in Spanner all the tables are real,
expected results override is required.
"""
insp, kws, exp = get_multi_exp(
schema,
scope,
kind,
use_filter,
Inspector.get_indexes,
self.exp_indexes,
)
_ignore_tables = [
(None, "comment_test"),
(None, "dingalings"),
(None, "email_addresses"),
(None, "no_constraints"),
]
exp = {k: v for k, v in exp.items() if k not in _ignore_tables}
for kw in kws:
insp.clear_cache()
result = insp.get_multi_indexes(**kw)
self._check_table_dict(result, exp, self._required_index_keys)
def exp_pks(
self,
schema=None,
scope=ObjectScope.ANY,
kind=ObjectKind.ANY,
filter_names=None,
):
def pk(*cols, name=mock.ANY, comment=None):
return {
"constrained_columns": list(cols),
"name": name,
"comment": comment,
}
empty = pk(name=None)
if testing.requires.materialized_views_reflect_pk.enabled:
materialized = {(schema, "dingalings_v"): pk("dingaling_id")}
else:
materialized = {(schema, "dingalings_v"): empty}
views = {
(schema, "email_addresses_v"): empty,
(schema, "users_v"): empty,
(schema, "user_tmp_v"): empty,
}
self._resolve_views(views, materialized)
tables = {
(schema, "users"): pk("user_id"),
(schema, "dingalings"): pk("dingaling_id"),
(schema, "email_addresses"): pk(
"address_id", name="email_ad_pk", comment="ea pk comment"
),
(schema, "comment_test"): pk("id"),
(schema, "no_constraints"): empty,
(schema, "local_table"): pk("id"),
(schema, "remote_table"): pk("id"),
(schema, "remote_table_2"): pk("id"),
(schema, "noncol_idx_test_nopk"): pk("id"),
(schema, "noncol_idx_test_pk"): pk("id"),
(schema, self.temp_table_name()): pk("id"),
}
if not testing.requires.reflects_pk_names.enabled:
for val in tables.values():
if val["name"] is not None:
val["name"] = mock.ANY
res = self._resolve_kind(kind, tables, views, materialized)
res = self._resolve_names(schema, scope, filter_names, res)
return res
@filter_name_values()
@testing.requires.primary_key_constraint_reflection
def test_get_multi_pk_constraint(
self,
get_multi_exp,
use_filter,
schema=None,
scope=ObjectScope.DEFAULT,
kind=ObjectKind.TABLE,
):
"""
SPANNER OVERRIDE:
Spanner doesn't support temporary tables, so real tables are
used for testing. As the original test expects only real
tables to be read, and in Spanner all the tables are real,
expected results override is required.
"""
insp, kws, exp = get_multi_exp(
schema,
scope,
kind,
use_filter,
Inspector.get_pk_constraint,
self.exp_pks,
)
_ignore_tables = [(None, "no_constraints")]
exp = {k: v for k, v in exp.items() if k not in _ignore_tables}
for kw in kws:
insp.clear_cache()
result = insp.get_multi_pk_constraint(**kw)
self._check_table_dict(result, exp, self._required_pk_keys, make_lists=True)
def exp_fks(
self,
schema=None,
scope=ObjectScope.ANY,
kind=ObjectKind.ANY,
filter_names=None,
):
class tt:
def __eq__(self, other):
return other is None or config.db.dialect.default_schema_name == other
def fk(
cols,
ref_col,
ref_table,
ref_schema=schema,
name=mock.ANY,
comment=None,
):
return {
"constrained_columns": cols,
"referred_columns": ref_col,
"name": name,
"options": mock.ANY,
"referred_schema": ref_schema if ref_schema is not None else tt(),
"referred_table": ref_table,
"comment": comment,
}
materialized = {}
views = {}
self._resolve_views(views, materialized)
tables = {
(schema, "users"): [
fk(["parent_user_id"], ["user_id"], "users", name="user_id_fk")
],
(schema, "dingalings"): [
fk(["address_id"], ["address_id"], "email_addresses"),
fk(["id_user"], ["user_id"], "users"),
],
(schema, "email_addresses"): [fk(["remote_user_id"], ["user_id"], "users")],
(schema, "local_table"): [
fk(
["remote_id"],
["id"],
"remote_table_2",
ref_schema=config.test_schema,
)
],
(schema, "remote_table"): [
fk(["local_id"], ["id"], "local_table", ref_schema=None)
],
}
if not testing.requires.self_referential_foreign_keys.enabled:
tables[(schema, "users")].clear()
if not testing.requires.named_constraints.enabled:
for vals in tables.values():
for val in vals:
if val["name"] is not mock.ANY:
val["name"] = mock.ANY
res = self._resolve_kind(kind, tables, views, materialized)
res = self._resolve_names(schema, scope, filter_names, res)
return res
@filter_name_values()
@testing.requires.foreign_key_constraint_reflection
def test_get_multi_foreign_keys(
self,
get_multi_exp,
use_filter,
schema=None,
scope=ObjectScope.DEFAULT,
kind=ObjectKind.TABLE,
):
"""
SPANNER OVERRIDE:
Spanner doesn't support temporary tables, so real tables are
used for testing. As the original test expects only real
tables to be read, and in Spanner all the tables are real,
expected results override is required.
"""
insp, kws, exp = get_multi_exp(
schema,
scope,
kind,
use_filter,
Inspector.get_foreign_keys,
self.exp_fks,
)
for kw in kws:
insp.clear_cache()
result = insp.get_multi_foreign_keys(**kw)
self._adjust_sort(result, exp, lambda d: tuple(d["constrained_columns"]))
self._check_table_dict(
{
key: sorted(value, key=lambda x: x["constrained_columns"])
for key, value in result.items()
},
{
key: sorted(value, key=lambda x: x["constrained_columns"])
for key, value in exp.items()
},
self._required_fk_keys,
)
def test_get_foreign_keys_quoted_name(self, connection, metadata):
pass
def test_get_indexes_quoted_name(self, connection, metadata):
pass
def test_get_unique_constraints_quoted_name(self, connection, metadata):
pass
def exp_columns(
self,
schema=None,
scope=ObjectScope.ANY,
kind=ObjectKind.ANY,
filter_names=None,
):
def col(name, auto=False, default=mock.ANY, comment=None, nullable=True):
res = {
"name": name,
"autoincrement": auto,
"type": mock.ANY,
"default": default,
"comment": comment,
"nullable": nullable,
}
if auto == "omit":
res.pop("autoincrement")
return res
def pk(name, **kw):
kw = {"auto": True, "default": mock.ANY, "nullable": False, **kw}
return col(name, **kw)
materialized = {
(schema, "dingalings_v"): [
col("dingaling_id", auto="omit", nullable=mock.ANY),
col("address_id"),
col("id_user"),
col("data"),
]
}
views = {
(schema, "email_addresses_v"): [
col("address_id", auto="omit", nullable=mock.ANY),
col("remote_user_id"),
col("email_address"),
],
(schema, "users_v"): [
col("user_id", auto="omit", nullable=mock.ANY),
col("test1", nullable=mock.ANY),
col("test2", nullable=mock.ANY),
col("parent_user_id"),
],
(schema, "user_tmp_v"): [
col("id", auto="omit", nullable=mock.ANY),
col("name"),
col("foo"),
],
}
self._resolve_views(views, materialized)
tables = {
(schema, "users"): [
pk("user_id"),
col("test1", nullable=False),
col("test2", nullable=False),
col("parent_user_id"),
],
(schema, "dingalings"): [
pk("dingaling_id"),
col("address_id"),
col("id_user"),
col("data"),
],
(schema, "email_addresses"): [