-
Notifications
You must be signed in to change notification settings - Fork 0
/
test_suite.py
2635 lines (2112 loc) · 97.4 KB
/
test_suite.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
"""Run SQLAlchemy's dialect testing suite against the Dataflex dialect."""
# coding=utf-8
# noinspection PyPackageRequirements
import pytest
import pyodbc
import operator
from uuid import uuid4
from random import sample
from decimal import Decimal as PyDecimal
from datetime import date, time, datetime
from typing import Any, Dict, Union, Optional, Sequence as SequenceType
import sqlalchemy as sa
from itertools import chain
from sqlalchemy_dataflex import *
from sqlalchemy import orm, ext, sql
from sqlalchemy.ext import declarative, hybrid
from sqlalchemy.testing import fixtures, suite as sa_testing
from sqlalchemy.testing.suite import ComputedReflectionTest as _ComputedReflectionTest
from sqlalchemy.testing.suite import RowFetchTest as _RowFetchTest
from sqlalchemy.testing.suite import UnicodeVarcharTest as _UnicodeVarcharTest
from sqlalchemy.testing.suite import DateTimeCoercedToDateTimeTest as _DateTimeCoercedToDateTimeTest
from sqlalchemy.testing.suite import IsOrIsNotDistinctFromTest as _IsOrIsNotDistinctFromTest
from sqlalchemy.testing.suite import SimpleUpdateDeleteTest as _SimpleUpdateDeleteTest
from sqlalchemy.testing.suite import CollateTest as _CollateTest
from sqlalchemy.testing.suite import NormalizedNameTest as _NormalizedNameTest
from sqlalchemy.testing.suite import HasTableTest as _HasTableTest
from sqlalchemy.testing.suite import DateTimeHistoricTest as _DateTimeHistoricTest
from sqlalchemy.testing.suite import ComponentReflectionTest as _ComponentReflectionTest
from sqlalchemy.testing.suite import LastrowidTest as _LastrowidTest
from sqlalchemy.testing.suite import SequenceTest as _SequenceTest
from sqlalchemy.testing.suite import PercentSchemaNamesTest as _PercentSchemaNamesTest
from sqlalchemy.testing.suite import JSONStringCastIndexTest as _JSONStringCastIndexTest
from sqlalchemy.testing.suite import StringTest as _StringTest
from sqlalchemy.testing.suite import CompoundSelectTest as _CompoundSelectTest
from sqlalchemy.testing.suite import ReturningTest as _ReturningTest
from sqlalchemy.testing.suite import AutocommitTest as _AutocommitTest
from sqlalchemy.testing.suite import HasSequenceTest as _HasSequenceTest
from sqlalchemy.testing.suite import UnicodeTextTest as _UnicodeTextTest
from sqlalchemy.testing.suite import TimeMicrosecondsTest as _TimeMicrosecondsTest
from sqlalchemy.testing.suite import ExpandingBoundInTest as _ExpandingBoundInTest
from sqlalchemy.testing.suite import EscapingTest as _EscapingTest
from sqlalchemy.testing.suite import TableDDLTest as _TableDDLTest
from sqlalchemy.testing.suite import CompositeKeyReflectionTest as _CompositeKeyReflectionTest
from sqlalchemy.testing.suite import QuotedNameArgumentTest as _QuotedNameArgumentTest
from sqlalchemy.testing.suite import ExceptionTest as _ExceptionTest
from sqlalchemy.testing.suite import JSONTest as _JSONTest
from sqlalchemy.testing.suite import ExistsTest as _ExistsTest
from sqlalchemy.testing.suite import LimitOffsetTest as _LimitOffsetTest
from sqlalchemy.testing.suite import TimeTest as _TimeTest
from sqlalchemy.testing.suite import DateTest as _DateTest
from sqlalchemy.testing.suite import SequenceCompilerTest as _SequenceCompilerTest
from sqlalchemy.testing.suite import DateTimeMicrosecondsTest as _DateTimeMicrosecondsTest
from sqlalchemy.testing.suite import CTETest as _CTETest
from sqlalchemy.testing.suite import OrderByLabelTest as _OrderByLabelTest
from sqlalchemy.testing.suite import ComputedColumnTest as _ComputedColumnTest
from sqlalchemy.testing.suite import IntegerTest as _IntegerTest
from sqlalchemy.testing.suite import DateHistoricTest as _DateHistoricTest
from sqlalchemy.testing.suite import LikeFunctionsTest as _LikeFunctionsTest
from sqlalchemy.testing.suite import NumericTest as _NumericTest
from sqlalchemy.testing.suite import TimestampMicrosecondsTest as _TimestampMicrosecondsTest
from sqlalchemy.testing.suite import BooleanTest as _BooleanTest
from sqlalchemy.testing.suite import IsolationLevelTest as _IsolationLevelTest
from sqlalchemy.testing.suite import InsertBehaviorTest as _InsertBehaviorTest
from sqlalchemy.testing.suite import DateTimeTest as _DateTimeTest
from sqlalchemy.testing.suite import ServerSideCursorsTest as _ServerSideCursorsTest
from sqlalchemy.testing.suite import TextTest as _TextTest
# noinspection SpellCheckingInspection
class DFTestTable:
"""A handy organizer for the static DataFlex tables required to test the dialect."""
metadata: sa.MetaData
schema: Optional[Any] = None
def __init__(self, metadata: sa.MetaData, schema_=None) -> None:
self.metadata = metadata
self.schema = schema_
def __bool__(self) -> bool:
if getattr(self, "metadata", None) is not None:
return True
return False
def _return_table(self, table: sa.Table) -> sa.Table:
"""Ensure that the supplied table is added to the MetaData instance."""
self.metadata.create_all(tables=(table,))
return table
@property
def _test_table(self) -> sa.Table:
"""The `_test_table` table."""
return self._return_table(
sa.Table(
"_test_table",
self.metadata,
sa.Column("id", Integer, primary_key=True, nullable=True),
sa.Column("data", VarChar(50)),
schema=self.schema,
)
)
@property
def autoinc_pk(self) -> sa.Table:
"""The `autoinc_pk` table."""
return self._return_table(
sa.Table(
"autoinc_pk",
self.metadata,
sa.Column("id", Integer, primary_key=True, nullable=True),
sa.Column("data", VarChar(50)),
schema=self.schema,
)
)
@property
def boolean_table(self) -> sa.Table:
"""The `boolean_table` table."""
return self._return_table(
sa.Table(
"boolean_table",
self.metadata,
sa.Column("id", Integer, primary_key=True, nullable=True),
sa.Column("value", Logical),
sa.Column("uc_value", Logical),
schema=self.schema,
)
)
@property
def date_time_table(self) -> sa.Table:
"""The `date_time_table` table."""
return self._return_table(
sa.Table(
"date_time_table",
self.metadata,
sa.Column("id", Integer, primary_key=True, nullable=True),
sa.Column("date_data", Timestamp),
schema=self.schema,
)
)
@property
def date_table(self) -> sa.Table:
"""The `date_table` table."""
return self._return_table(
sa.Table(
"date_table",
self.metadata,
sa.Column("id", Integer, primary_key=True, nullable=True),
sa.Column("date_data", Date),
schema=self.schema,
)
)
@property
def integer_table(self) -> sa.Table:
"""The `integer_table` table."""
return self._return_table(
sa.Table(
"integer_table",
self.metadata,
sa.Column("id", Integer, primary_key=True, nullable=True),
sa.Column("integer_data", Integer),
schema=self.schema,
)
)
@property
def manual_pk(self) -> sa.Table:
"""The `manual_pk` table."""
return self._return_table(
sa.Table(
"manual_pk",
self.metadata,
sa.Column("id", Integer, primary_key=True, nullable=True),
sa.Column("data", VarChar(50)),
schema=self.schema,
)
)
@property
def plain_pk(self) -> sa.Table:
"""The `plain_pk` table."""
return self._return_table(
sa.Table(
"plain_pk",
self.metadata,
sa.Column("id", Integer, primary_key=True, nullable=True),
sa.Column("data", VarChar(50)),
schema=self.schema,
)
)
@property
def related(self) -> sa.Table:
"""The `related` table."""
return self._return_table(
sa.Table(
"related",
self.metadata,
sa.Column("id", Integer, primary_key=True, nullable=True),
sa.Column("related", Integer),
schema=self.schema,
)
)
@property
def some_int_table(self) -> sa.Table:
"""The `some_int_table` table."""
return self._return_table(
sa.Table(
"some_int_table",
self.metadata,
sa.Column("id", Integer, primary_key=True, nullable=True),
sa.Column("x", Integer),
sa.Column("y", Integer),
schema=self.schema,
)
)
@property
def some_table(self) -> sa.Table:
"""The `some_table` table."""
return self._return_table(
sa.Table(
"some_table",
self.metadata,
sa.Column("id", Integer, primary_key=True, nullable=True),
sa.Column("q", VarChar(50)),
sa.Column("p", VarChar(50)),
sa.Column("x", Integer),
sa.Column("y", Integer),
sa.Column("z", VarChar(50)),
sa.Column("data", VarChar(100)),
schema=self.schema,
)
)
@property
def stuff(self) -> sa.Table:
"""The `stuff` table."""
return self._return_table(
sa.Table(
"stuff",
self.metadata,
sa.Column("id", Integer, primary_key=True, nullable=True),
sa.Column("data", VarChar(50)),
schema=self.schema,
)
)
@property
def tb1(self) -> sa.Table:
"""The `tb1` table."""
return self._return_table(
sa.Table(
"tb1",
self.metadata,
sa.Column("id", Integer, primary_key=True, nullable=True),
sa.Column("attr", Integer),
sa.Column("name", VarChar(20)),
schema=self.schema,
)
)
@property
def tb2(self) -> sa.Table:
"""The `tb2` table."""
return self._return_table(
sa.Table(
"tb2",
self.metadata,
sa.Column("id", Integer, primary_key=True, nullable=True),
sa.Column("pid", Integer),
sa.Column("pattr", Integer),
sa.Column("pname", VarChar(20)),
ForeignKeyConstraint(
["pname", "pid", "pattr"],
[self.tb1.c.name, self.tb1.c.id, self.tb1.c.attr],
name="fk_tb1_name_id_attr",
),
schema=self.schema,
)
)
@property
def test_table(self) -> sa.Table:
"""The `test_table` table."""
return self._return_table(
sa.Table(
"test_table",
self.metadata,
sa.Column("id", Integer, primary_key=True, nullable=True),
sa.Column("data", VarChar(50)),
schema=self.schema,
)
)
@property
def unicode_table(self) -> sa.Table:
"""The `unicode_table` table."""
return self._return_table(
sa.Table(
"unicode_table",
self.metadata,
sa.Column("id", Integer, primary_key=True, nullable=True),
sa.Column("unicode_data", VarChar(255)),
schema=self.schema,
)
)
@property
def users(self) -> sa.Table:
"""The `users` table."""
return self._return_table(
sa.Table(
"users",
self.metadata,
sa.Column("id", Integer, primary_key=True, nullable=True),
sa.Column("test1", VarChar(5)),
sa.Column("test2", Double),
schema=self.schema,
)
)
@property
def foo(self) -> sa.Table:
"""The `foo` table."""
return self._return_table(sa.Table("foo", self.metadata, sa.Column("one", VarChar), schema=self.schema))
@property
def float_table(self) -> sa.Table:
"""The `float_table` table."""
return self._return_table(sa.Table("float_table", self.metadata, sa.Column("x", Double), schema=self.schema))
@property
def varchar_table(self) -> sa.Table:
"""The `varchar_table` table."""
return self._return_table(
sa.Table("varchar_table", self.metadata, sa.Column("x", VarChar), schema=self.schema)
)
@property
def numeric_table(self) -> sa.Table:
"""The `numeric_table` table."""
return self._return_table(
sa.Table("numeric_table", self.metadata, sa.Column("x", sa.Numeric), schema=self.schema)
)
@property
def int_table(self) -> sa.Table:
"""The `int_table` table."""
return self._return_table(sa.Table("int_table", self.metadata, sa.Column("x", Integer), schema=self.schema))
@property
def dingalings(self) -> sa.Table:
"""The `dingalings` table."""
return self._return_table(
sa.Table(
"dingalings",
self.metadata,
sa.Column("dingaling_id", Integer, primary_key=True, nullable=True),
sa.Column("address_id", Integer, sa.ForeignKey("email_addresses.address_id")),
sa.Column("data", VarChar(30)),
schema=self.schema,
)
)
@property
def email_addresses(self) -> sa.Table:
"""The `email_addresses` table."""
return self._return_table(
sa.Table(
"email_addresses",
self.metadata,
sa.Column("address_id", Integer),
sa.Column("remote_user_id", Integer, sa.ForeignKey("users.id")),
sa.Column("email_address", VarChar(20)),
sa.PrimaryKeyConstraint("address_id", name="email_ad_pk"),
schema=self.schema,
)
)
@property
def comment_test(self) -> sa.Table:
"""The `comment_test` table."""
return self._return_table(
sa.Table(
"comment_test",
self.metadata,
sa.Column("id", Integer, primary_key=True, nullable=True, comment="id comment"),
sa.Column("data", VarChar(20), comment="data % comment"),
sa.Column(
"d2",
VarChar(20),
comment=r"""Comment types type speedily ' " \ '' Fun!""",
),
schema=self.schema,
comment=r"""the test % ' " \ table comment""",
)
)
@property
def noncol_idx_test_nopk(self) -> sa.Table:
"""The `noncol_idx_test_nopk` table."""
return self._return_table(
sa.Table(
"noncol_idx_test_nopk",
self.metadata,
sa.Column("q", VarChar(5)),
schema=self.schema,
)
)
@property
def noncol_idx_test_pk(self) -> sa.Table:
"""The `noncol_idx_test_pk` table."""
return self._return_table(
sa.Table(
"noncol_idx_test_pk",
self.metadata,
sa.Column("id", Integer, primary_key=True, nullable=True),
sa.Column("q", VarChar(5)),
schema=self.schema,
)
)
@property
def testtbl(self) -> sa.Table:
"""The `testtbl` table."""
return self._return_table(
sa.Table(
"testtbl",
self.metadata,
sa.Column("a", VarChar(20)),
sa.Column("b", VarChar(30)),
sa.Column("c", Integer),
# reserved identifiers
sa.Column("asc", VarChar(30)),
sa.Column("key", VarChar(30)),
schema=self.schema,
)
)
@property
def types_table(self) -> sa.Table:
"""The `types_table` table."""
return self._return_table(
sa.Table(
"types_table",
self.metadata,
sa.Column("id", Integer, primary_key=True, nullable=True, autoincrement=False),
sa.Column("ASCII", VarChar(255)),
sa.Column("BIGINT", BigInt),
sa.Column("BINARY", LongVarBinary(2624)),
sa.Column("BOOLEAN", Logical),
sa.Column("CHAR", Char(255)),
sa.Column("DATE", Date),
sa.Column("DECIMAL", Decimal),
sa.Column("DOUBLE", DoublePrecision),
sa.Column("FLOAT", DoublePrecision),
sa.Column("INTEGER", Integer),
sa.Column("LOGICAL", Logical),
sa.Column("LONGVARBINARY", LongVarBinary(2624)),
sa.Column("LONGVARCHAR", LongVarChar(2624)),
sa.Column("NUMERIC", Decimal),
sa.Column("TEXT", LongVarChar(2624)),
sa.Column("TIME", Time),
sa.Column("TIMESTAMP", Timestamp),
sa.Column("VARBINARY", LongVarBinary(2624)),
sa.Column("VARCHAR", LongVarChar(2624)),
schema=self.schema,
)
)
@property
def t(self) -> sa.Table:
"""The `t` table."""
return self._return_table(
sa.Table(
"t",
self.metadata,
# This may or may not work correctly,
# as it's unclear if DataFlex cares about
# nullability
sa.Column("a", Integer, nullable=True),
sa.Column("b", Integer, nullable=False),
sa.Column("data", VarChar(50), nullable=True),
schema=self.schema,
)
)
@property
def includes_defaults(self) -> sa.Table:
"""The `includes_defaults` table."""
return self._return_table(
sa.Table(
"includes_defaults",
self.metadata,
sa.Column("id", Integer, primary_key=True, nullable=True, autoincrement=True),
sa.Column("data", VarChar(50)),
sa.Column("x", Integer, default=5),
sa.Column(
"y",
Integer,
default=sa.literal_column("2", type_=Integer) + sa.literal(2),
),
schema=self.schema,
)
)
@property
def scalar_select(self) -> sa.Table:
"""The `scalar_select` table."""
return self._return_table(
sa.Table(
"scalar_select",
self.metadata,
sa.Column("data", VarChar(50), nullable=True),
schema=self.schema,
)
)
def df_literal_round_trip(self, type_, input_, output, filter_=None):
"""Test literal value rendering."""
# The SQLAlchemy test suite usually creates a table for this
# test on the fly. The FlexODBC driver can't do that though,
# so we'll have to use a specially created table with one
# column of each type, named accordingly.
column_name = getattr(
type_, "__type_name__", getattr(type_, "__visit_name__", getattr(type_, "__dataflex_name__", "VARCHAR"))
).upper()
# For literals, we test the literal render in an INSERT
# into a typed column. We can then SELECT it back as its
# "official" type.
t = DFTestTable(getattr(self, "metadata", sa.MetaData())).types_table
t.delete().execute()
with sa_testing.testing.db.connect() as conn:
for pos, value in enumerate(input_):
statement = (
t.insert()
.values(**{"id": pos + 1, column_name: value})
.compile(dialect=sa_testing.testing.db.dialect, compile_kwargs=dict(literal_binds=True))
)
conn.execute(statement)
if self.supports_whereclause:
stmt = sa.select([t.c.id, getattr(t.c, column_name, t.c.VARCHAR)]).where(
getattr(t.c, column_name, t.c.VARCHAR) == value
)
else:
stmt = sa.select([t.c.id, getattr(t.c, column_name, t.c.VARCHAR)])
stmt = stmt.compile(dialect=sa_testing.testing.db.dialect, compile_kwargs=dict(literal_binds=True))
for row in conn.execute(stmt):
value = row[1]
if filter_ is not None:
value = filter_(value)
assert value in output
@pytest.mark.skip(reason="Unsupported by FlexODBC driver.")
class AutocommitTest(_AutocommitTest):
"""Test the dialect's handling of autocommit."""
class BooleanTest(_BooleanTest):
"""Test the dialect's handling of boolean values."""
__backend__ = True
@classmethod
def define_tables(cls, metadata: sa.MetaData):
"""Define the table(s) required by the test(s)."""
assert DFTestTable(metadata).boolean_table is not None
@sa_testing.testing.provide_metadata
def _literal_round_trip(self, type_, input_, output, filter_=None):
"""test literal rendering """
df_literal_round_trip(self, type_, input_, output, filter_)
def test_render_literal_bool(self):
self._literal_round_trip(Logical, [True, False], [True, False])
def test_round_trip(self):
boolean_table = self.tables.boolean_table
sa_testing.config.db.execute(boolean_table.insert({"id": 1, "value": True, "uc_value": False}))
row = sa_testing.config.db.execute(sa.select([boolean_table.c.value, boolean_table.c.uc_value])).first()
sa_testing.eq_(row, (True, False))
assert isinstance(row[0], bool)
def test_whereclause(self):
# testing "WHERE <column>" renders a compatible expression
boolean_table = self.tables.boolean_table
with sa_testing.config.db.connect() as conn:
conn.execute(boolean_table.insert({"id": 1, "value": True, "uc_value": True}))
conn.execute(boolean_table.insert({"id": 2, "value": False, "uc_value": False}))
sa_testing.eq_(
conn.scalar(sa.select([boolean_table.c.id]).where(boolean_table.c.value)),
1,
)
sa_testing.eq_(
conn.scalar(sa.select([boolean_table.c.id]).where(boolean_table.c.uc_value)),
1,
)
sa_testing.eq_(
conn.scalar(sa.select([boolean_table.c.id]).where(~boolean_table.c.value)),
2,
)
sa_testing.eq_(
conn.scalar(sa.select([boolean_table.c.id]).where(~boolean_table.c.uc_value)),
2,
)
@pytest.mark.skip(reason="Unsupported by FlexODBC driver.")
class CTETest(_CTETest):
"""Test the dialect's handling of CTE."""
class CollateTest(_CollateTest):
"""Test the dialect's handling of collation."""
@classmethod
def define_tables(cls, metadata):
"""Define the table(s) required by the test(s)."""
assert DFTestTable(metadata).some_table is not None
@classmethod
def insert_data(cls, connection):
"""Insert the data required by the test(s)."""
table = cls.tables.some_table
inserts = (
table.insert({"id": 1, "data": "collate data1"}),
table.insert({"id": 2, "data": "collate data2"}),
)
for query in inserts:
connection.execute(query)
@sa_testing.testing.requires.order_by_collation
def test_collate_order_by(self):
collation = sa_testing.testing.requires.get_order_by_collation(sa_testing.testing.config)
table = self.tables.some_table
query = sa.select([table.c.id, table.c.data]).order_by(table.c.data.collate(collation).asc())
expected = [(1, "collate data1"), (2, "collate data2")]
result = sa_testing.config.db.execute(query).fetchall()
sa_testing.eq_(result, expected)
class ComponentReflectionTest(_ComponentReflectionTest):
"""Test the dialect's handling of component reflection."""
@classmethod
def define_reflected_tables(cls, metadata, schema_):
"""Define the tables required by the reflection test(s)."""
df_tables = DFTestTable(metadata, schema_)
for table in (
"users",
"dingalings",
"comment_test",
"email_addresses",
"noncol_idx_test_pk",
"noncol_idx_test_nopk",
):
assert getattr(df_tables, table, None) is not None
@sa_testing.testing.provide_metadata
def _type_round_trip(self, *types):
df_tables = DFTestTable(self.metadata)
assert df_tables.types_table is not None
type_names = set(
chain.from_iterable(
(
filter(
None,
(
f"""{getattr(item, f"__{name}_name__", None)}({getattr(item, "length", None)})"""
if getattr(item, "length", None)
else getattr(item, f"__{name}_name__", None)
for name in ("dataflex", "type", "visit")
),
)
)
for item in types
)
)
def type_filter(item: Dict[str, Any]) -> bool:
"""Filter out requested types."""
item_type = item.get("type", None)
if item_type is None:
return False
item_type_names = set(
filter(
None,
(
f"""{getattr(item_type, f"__{name}_name__", None)}({getattr(item_type, "length", None)})"""
if getattr(item_type, "length", None)
else getattr(item_type, f"__{name}_name__", None)
for name in ("dataflex", "type", "visit")
),
)
)
return bool(type_names.intersection(item_type_names))
return list(
filter(
None,
(
c.get("type", None)
for c in filter(type_filter, sa.inspect(self.metadata.bind).get_columns("types_table"))
),
)
)
@sa_testing.testing.requires.table_reflection
@sa_testing.testing.provide_metadata
def test_autoincrement_col(self):
"""test that 'autoincrement' is reflected according to sqla's policy.
Don't mark this test as unsupported for any backend !
(technically it fails with MySQL InnoDB since "id" comes before "id2")
A backend is better off not returning "autoincrement" at all,
instead of potentially returning "False" for an auto-incrementing
primary key column.
"""
meta = self.metadata
insp = sa.inspect(meta.bind)
for tname, cname in [
("users", "id"),
("email_addresses", "id"),
("dingalings", "id"),
]:
cols = insp.get_columns(tname)
id_ = {c["name"]: c for c in cols}[cname]
assert id_.get("autoincrement", True)
@pytest.mark.skip(reason="DataFlex check constraint support currently unclear.")
def test_get_check_constraints(self):
"""DocString."""
@sa_testing.testing.provide_metadata
def _test_get_columns(self, schema_=None, table_type="table"):
"""Test column reflection."""
df_tables = DFTestTable(self.metadata, schema_)
users, addresses = (df_tables.users, df_tables.email_addresses)
table_names = ["users", "email_addresses"]
insp = sa.inspect(self.metadata.bind)
for table_name, table in zip(table_names, (users, addresses)):
schema_name = sa_testing.schema
cols = insp.get_columns(table_name, schema=schema_name)
self.assert_(len(cols) > 0, len(cols))
# should be in order
expected_data = {"name", "type", "nullable", "default", "autoincrement"}
for i, col in enumerate(table.columns):
assert cols[i]["name"] in col.name
# The built=in SQLAlchemy test checks for a whole bunch
# of other things, most importantly that the column types
# match up as expected. Because of DataFlex's limited
# set of column types, that's... not feasible. So we'll
# reduce the SQLAlchemy check to simply ensuring that
# the dialect's `get_columns` method returned the expected
# information
difference = expected_data.difference(set(cols[i].keys()))
self.assert_(len(difference) == 0, f"Missing column data: {difference}")
if not col.primary_key:
assert cols[i]["default"] is None
@sa_testing.testing.provide_metadata
def _test_get_indexes(self, schema_=None):
"""DocString."""
meta = self.metadata
# The database may decide to create indexes for foreign keys, etc.
# so there may be more indexes than expected.
insp = sa.inspect(meta.bind)
indexes = insp.get_indexes("users", schema=schema_)
expected_indexes = [
{"name": "INDEX2", "unique": True, "column_names": ["test1", "test2"]},
{"name": "INDEX1", "unique": True, "column_names": ["id", "test2", "test1"]},
]
self._assert_insp_indexes(indexes, expected_indexes)
@pytest.mark.skip(reason="FlexODBC driver doesn't support primary key reflection.")
def test_get_pk_constraint(self):
"""DocString."""
pass
@sa_testing.testing.provide_metadata
def _test_get_noncol_index(self, tname, ixname):
# tname = "noncol_idx_test_nopk"
# ixname = "noncol_idx_nopk"
meta = self.metadata
insp = sa.inspect(meta.bind)
indexes = insp.get_indexes(tname)
# reflecting an index that has "x DESC" in it as the column.
# the DB may or may not give us "x", but make sure we get the index
# back, it has a name, it's connected to the table.
expected_indexes = [{"unique": True, "name": ixname}]
self._assert_insp_indexes(indexes, expected_indexes)
t = sa.Table(tname, meta, autoload_with=meta.bind)
sa_testing.eq_(len(t.indexes), 1)
assert list(t.indexes)[0].table is t
sa_testing.eq_(list(t.indexes)[0].name, ixname)
@sa_testing.testing.requires.index_reflection
@sa_testing.testing.requires.indexes_with_ascdesc
def test_get_noncol_index_no_pk(self):
self._test_get_noncol_index("noncol_idx_test_nopk", "INDEX1")
@sa_testing.testing.requires.index_reflection
@sa_testing.testing.requires.indexes_with_ascdesc
def test_get_noncol_index_pk(self):
self._test_get_noncol_index("noncol_idx_test_pk", "INDEX1")
@sa_testing.testing.provide_metadata
def _test_get_table_names(self, schema_=None, table_type="table", order_by=None):
_ignore_tables = [
"comment_test",
"noncol_idx_test_pk",
"noncol_idx_test_nopk",
"local_table",
"remote_table",
"remote_table_2",
]
meta = self.metadata
insp = sa.inspect(meta.bind)
tables = insp.get_table_names(schema_)
table_names = [t for t in tables if t not in _ignore_tables]
answer = ["dingalings", "email_addresses", "users"]
for table_name in answer:
assert table_name in table_names
@sa_testing.testing.provide_metadata
def _test_get_unique_constraints(self, schema_=None):
# DataFlex doesn't allow for named indexes, it enforces
# its own naming scheme (INDEX + sequential number).
uniques = sorted(
[
{"name": "INDEX1", "unique": True, "column_names": ["a"]},
{"name": "INDEX2", "unique": True, "column_names": ["a", "b", "c"]},
{"name": "INDEX3", "unique": True, "column_names": ["c", "a", "b"]},
{"name": "INDEX4", "unique": True, "column_names": ["asc", "key"]},
{"name": "INDEX5", "unique": True, "column_names": ["b"]},
{"name": "INDEX6", "unique": True, "column_names": ["c"]},
],
key=operator.itemgetter("name"),
)
orig_meta = self.metadata
assert DFTestTable(orig_meta, schema_).testtbl is not None
inspector = sa.inspect(orig_meta.bind)
reflected = sorted(
inspector.get_unique_constraints("testtbl", schema=schema_),
key=operator.itemgetter("name"),
)
names_that_duplicate_index = set()
for orig, refl in zip(uniques, reflected):
# Different dialects handle duplicate index and constraints
# differently, so ignore this flag
dupe = refl.pop("duplicates_index", None)
if dupe:
names_that_duplicate_index.add(dupe)
sa_testing.eq_(orig, refl)
reflected_metadata = sa.MetaData()
reflected = sa.Table("testtbl", reflected_metadata, autoload_with=orig_meta.bind, schema=schema_)
# Test to ensure that the reflected index names are exactly what
# we expected, nothing more or less
reflected_names = {idx.name for idx in reflected.indexes}
expected_names = {idx.get("name") for idx in uniques}
assert len(expected_names.difference(reflected_names)) == 0
assert len(reflected_names.difference(expected_names)) == 0
assert reflected_names == expected_names
@sa_testing.testing.requires.table_reflection
@sa_testing.testing.provide_metadata
def test_nullable_reflection(self):
assert DFTestTable(self.metadata).t is not None
columns = sa.inspect(self.metadata.bind).get_columns("t")
# Due to the way that DataFlex does its indexing, and the fact that DataFlex
# tables are discrete flat-files, all columns are technically nullable
expected = {"a": True, "b": True, "data": True}
result = dict((col["name"], col["nullable"]) for col in columns)
sa_testing.eq_(result, expected)
@sa_testing.testing.requires.table_reflection
def test_varchar_reflection(self):
round_trip_types = self._type_round_trip(VarChar(255))
typ = round_trip_types[0]
assert isinstance(typ, (VarChar, LongVarChar))
sa_testing.eq_(typ.length, 255)
@pytest.mark.skip(reason="Unsupported by FlexODBC driver.")
class CompositeKeyReflectionTest(_CompositeKeyReflectionTest):
"""Test the dialect's handling of composite key reflection."""
# The FlexODBC driver doesn't support primary or foreign key reflection
@pytest.mark.skip(reason="Unsupported by FlexODBC driver.")
class CompoundSelectTest(_CompoundSelectTest):
"""Test the dialect's handling of compound select clauses."""
# FlexODBC driver doesn't support UNION, JOIN or any other form of compound select.
@pytest.mark.skip(reason="Unsupported by FlexODBC driver.")
class ComputedColumnTest(_ComputedColumnTest):
"""Test the dialect's handling of computed columns."""
@pytest.mark.skip(reason="Unsupported by FlexODBC driver.")
class ComputedReflectionTest(_ComputedReflectionTest):
"""Test the dialect's handling of computed reflection."""
class DateHistoricTest(_DateHistoricTest):
"""Test the dialect's handling of historic date data."""
@classmethod
def define_tables(cls, metadata):
"""Define the table(s) required to run the test(s)."""
df_tables = DFTestTable(metadata)
assert df_tables.date_table is not None
@sa_testing.testing.provide_metadata
def _literal_round_trip(self, type_, input_, output, filter_=None):
"""test literal rendering """
df_literal_round_trip(self, type_, input_, output, filter_)
def test_null(self):
date_table = self.tables.date_table
sa_testing.config.db.execute(date_table.insert({"id": 1, "date_data": None}))
row = sa_testing.config.db.execute(sa.select([date_table.c.date_data]).where(date_table.c.id == 1)).first()
sa_testing.eq_(row, (None,))
def test_round_trip(self):
date_table = self.tables.date_table
sa_testing.config.db.execute(date_table.insert({"id": 2, "date_data": self.data}))
row = sa_testing.config.db.execute(sa.select([date_table.c.date_data]).where(date_table.c.id == 2)).first()