-
-
Notifications
You must be signed in to change notification settings - Fork 330
Expand file tree
/
Copy pathtest_batch.py
More file actions
2617 lines (2263 loc) · 86.4 KB
/
test_batch.py
File metadata and controls
2617 lines (2263 loc) · 86.4 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
from contextlib import contextmanager
import re
from sqlalchemy import Boolean
from sqlalchemy import CheckConstraint
from sqlalchemy import Column
from sqlalchemy import Computed
from sqlalchemy import DateTime
from sqlalchemy import Enum
from sqlalchemy import ForeignKey
from sqlalchemy import ForeignKeyConstraint
from sqlalchemy import func
from sqlalchemy import Identity
from sqlalchemy import Index
from sqlalchemy import inspect
from sqlalchemy import Integer
from sqlalchemy import JSON
from sqlalchemy import MetaData
from sqlalchemy import PrimaryKeyConstraint
from sqlalchemy import select
from sqlalchemy import String
from sqlalchemy import Table
from sqlalchemy import Text
from sqlalchemy import UniqueConstraint
from sqlalchemy.dialects import sqlite as sqlite_dialect
from sqlalchemy.schema import CreateIndex
from sqlalchemy.schema import CreateTable
from sqlalchemy.sql import column
from sqlalchemy.sql import text
from alembic import command
from alembic import testing
from alembic import util
from alembic.ddl import sqlite
from alembic.operations import Operations
from alembic.operations.batch import ApplyBatchImpl
from alembic.runtime.migration import MigrationContext
from alembic.script import ScriptDirectory
from alembic.testing import assert_raises_message
from alembic.testing import config
from alembic.testing import eq_
from alembic.testing import exclusions
from alembic.testing import expect_raises_message
from alembic.testing import is_
from alembic.testing import mock
from alembic.testing import TestBase
from alembic.testing.env import _no_sql_testing_config
from alembic.testing.env import clear_staging_env
from alembic.testing.env import staging_env
from alembic.testing.env import write_script
from alembic.testing.fixtures import capture_context_buffer
from alembic.testing.fixtures import op_fixture
from alembic.util import CommandError
from alembic.util import exc as alembic_exc
from alembic.util.sqla_compat import _NONE_NAME
from alembic.util.sqla_compat import _safe_commit_connection_transaction
class BatchApplyTest(TestBase):
def setUp(self):
self.op = Operations(mock.Mock(opts={}))
self.impl = sqlite.SQLiteImpl(
sqlite_dialect.dialect(), None, False, False, None, {}
)
def _simple_fixture(self, table_args=(), table_kwargs={}, **kw):
m = MetaData()
t = Table(
"tname",
m,
Column("id", Integer, primary_key=True),
Column("x", String(10)),
Column("y", Integer),
)
return ApplyBatchImpl(
self.impl, t, table_args, table_kwargs, False, **kw
)
def _uq_fixture(self, table_args=(), table_kwargs={}):
m = MetaData()
t = Table(
"tname",
m,
Column("id", Integer, primary_key=True),
Column("x", String()),
Column("y", Integer),
UniqueConstraint("y", name="uq1"),
)
return ApplyBatchImpl(self.impl, t, table_args, table_kwargs, False)
def _named_ck_table_fixture(self, table_args=(), table_kwargs={}):
m = MetaData()
t = Table(
"tname",
m,
Column("id", Integer, primary_key=True),
Column("x", String()),
Column("y", Integer),
CheckConstraint("y > 5", name="ck1"),
)
return ApplyBatchImpl(self.impl, t, table_args, table_kwargs, False)
def _named_ck_col_fixture(self, table_args=(), table_kwargs={}):
m = MetaData()
t = Table(
"tname",
m,
Column("id", Integer, primary_key=True),
Column("x", String()),
Column("y", Integer, CheckConstraint("y > 5", name="ck1")),
)
return ApplyBatchImpl(self.impl, t, table_args, table_kwargs, False)
def _ix_fixture(self, table_args=(), table_kwargs={}):
m = MetaData()
t = Table(
"tname",
m,
Column("id", Integer, primary_key=True),
Column("x", String()),
Column("y", Integer),
Index("ix1", "y"),
)
return ApplyBatchImpl(self.impl, t, table_args, table_kwargs, False)
def _pk_fixture(self):
m = MetaData()
t = Table(
"tname",
m,
Column("id", Integer),
Column("x", String()),
Column("y", Integer),
PrimaryKeyConstraint("id", name="mypk"),
)
return ApplyBatchImpl(self.impl, t, (), {}, False)
def _literal_ck_fixture(
self, copy_from=None, table_args=(), table_kwargs={}
):
m = MetaData()
if copy_from is not None:
t = copy_from
else:
t = Table(
"tname",
m,
Column("id", Integer, primary_key=True),
Column("email", String()),
CheckConstraint("email LIKE '%@%'"),
)
return ApplyBatchImpl(self.impl, t, table_args, table_kwargs, False)
def _sql_ck_fixture(self, table_args=(), table_kwargs={}):
m = MetaData()
t = Table(
"tname",
m,
Column("id", Integer, primary_key=True),
Column("email", String()),
)
t.append_constraint(CheckConstraint(t.c.email.like("%@%")))
return ApplyBatchImpl(self.impl, t, table_args, table_kwargs, False)
def _fk_fixture(self, table_args=(), table_kwargs={}):
m = MetaData()
t = Table(
"tname",
m,
Column("id", Integer, primary_key=True),
Column("email", String()),
Column("user_id", Integer, ForeignKey("user.id")),
)
return ApplyBatchImpl(self.impl, t, table_args, table_kwargs, False)
def _multi_fk_fixture(self, table_args=(), table_kwargs={}, schema=None):
m = MetaData()
if schema:
schemaarg = "%s." % schema
else:
schemaarg = ""
t = Table(
"tname",
m,
Column("id", Integer, primary_key=True),
Column("email", String()),
Column("user_id_1", Integer, ForeignKey("%suser.id" % schemaarg)),
Column("user_id_2", Integer, ForeignKey("%suser.id" % schemaarg)),
Column("user_id_3", Integer),
Column("user_id_version", Integer),
ForeignKeyConstraint(
["user_id_3", "user_id_version"],
["%suser.id" % schemaarg, "%suser.id_version" % schemaarg],
),
schema=schema,
)
return ApplyBatchImpl(self.impl, t, table_args, table_kwargs, False)
def _named_fk_fixture(self, table_args=(), table_kwargs={}):
m = MetaData()
t = Table(
"tname",
m,
Column("id", Integer, primary_key=True),
Column("email", String()),
Column("user_id", Integer, ForeignKey("user.id", name="ufk")),
)
return ApplyBatchImpl(self.impl, t, table_args, table_kwargs, False)
def _selfref_fk_fixture(self, table_args=(), table_kwargs={}):
m = MetaData()
t = Table(
"tname",
m,
Column("id", Integer, primary_key=True),
Column("parent_id", Integer, ForeignKey("tname.id")),
Column("data", String),
)
return ApplyBatchImpl(self.impl, t, table_args, table_kwargs, False)
def _boolean_fixture(self, table_args=(), table_kwargs={}):
m = MetaData()
t = Table(
"tname",
m,
Column("id", Integer, primary_key=True),
Column("flag", Boolean(create_constraint=True)),
)
return ApplyBatchImpl(self.impl, t, table_args, table_kwargs, False)
def _boolean_no_ck_fixture(self, table_args=(), table_kwargs={}):
m = MetaData()
t = Table(
"tname",
m,
Column("id", Integer, primary_key=True),
Column("flag", Boolean(create_constraint=False)),
)
return ApplyBatchImpl(self.impl, t, table_args, table_kwargs, False)
def _enum_fixture(self, table_args=(), table_kwargs={}):
m = MetaData()
t = Table(
"tname",
m,
Column("id", Integer, primary_key=True),
Column("thing", Enum("a", "b", "c", create_constraint=True)),
)
return ApplyBatchImpl(self.impl, t, table_args, table_kwargs, False)
def _server_default_fixture(self, table_args=(), table_kwargs={}):
m = MetaData()
t = Table(
"tname",
m,
Column("id", Integer, primary_key=True),
Column("thing", String(), server_default=""),
)
return ApplyBatchImpl(self.impl, t, table_args, table_kwargs, False)
def _assert_impl(
self,
impl,
colnames=None,
ddl_contains=None,
ddl_not_contains=None,
dialect="default",
schema=None,
):
context = op_fixture(dialect=dialect)
impl._create(context.impl)
if colnames is None:
colnames = ["id", "x", "y"]
eq_(impl.new_table.c.keys(), colnames)
pk_cols = [col for col in impl.new_table.c if col.primary_key]
eq_(list(impl.new_table.primary_key), pk_cols)
create_stmt = str(
CreateTable(impl.new_table).compile(dialect=context.dialect)
)
create_stmt = re.sub(r"[\n\t]", "", create_stmt)
idx_stmt = ""
# create indexes; these should be created in terms of the
# final table name
impl.new_table.name = impl.table.name
for idx in impl._gather_indexes_from_both_tables():
idx_stmt += str(CreateIndex(idx).compile(dialect=context.dialect))
idx_stmt = re.sub(r"[\n\t]", "", idx_stmt)
# revert new table name to the temp name, assertions below
# are looking for the temp name
impl.new_table.name = ApplyBatchImpl._calc_temp_name(impl.table.name)
if ddl_contains:
assert ddl_contains in create_stmt + idx_stmt
if ddl_not_contains:
assert ddl_not_contains not in create_stmt + idx_stmt
expected = [create_stmt]
if schema:
args = {"schema": "%s." % schema}
else:
args = {"schema": ""}
args["temp_name"] = impl.new_table.name
args["colnames"] = ", ".join(
[
impl.new_table.c[name].name
for name in colnames
if name in impl.table.c
]
)
args["tname_colnames"] = ", ".join(
(
"CAST(%(schema)stname.%(name)s AS %(type)s) AS %(cast_label)s"
% {
"schema": args["schema"],
"name": name,
"type": impl.new_table.c[name].type,
"cast_label": name,
}
if (
impl.new_table.c[name].type._type_affinity
is not impl.table.c[name].type._type_affinity
)
else "%(schema)stname.%(name)s"
% {"schema": args["schema"], "name": name}
)
for name in colnames
if name in impl.table.c
)
expected.extend(
[
"INSERT INTO %(schema)s%(temp_name)s (%(colnames)s) "
"SELECT %(tname_colnames)s FROM %(schema)stname" % args,
"DROP TABLE %(schema)stname" % args,
"ALTER TABLE %(schema)s%(temp_name)s RENAME TO %(schema)stname"
% args,
]
)
if idx_stmt:
expected.append(idx_stmt)
context.assert_(*expected)
return impl.new_table
def test_change_type(self):
impl = self._simple_fixture()
impl.alter_column("tname", "x", type_=String)
new_table = self._assert_impl(impl)
assert new_table.c.x.type._type_affinity is String
def test_rename_col(self):
impl = self._simple_fixture()
impl.alter_column("tname", "x", name="q")
new_table = self._assert_impl(impl)
eq_(new_table.c.x.name, "q")
def test_rename_col_w_index(self):
impl = self._ix_fixture()
impl.alter_column("tname", "y", name="y2")
new_table = self._assert_impl(
impl, ddl_contains="CREATE INDEX ix1 ON tname (y2)"
)
eq_(new_table.c.y.name, "y2")
def test_rename_col_w_uq(self):
impl = self._uq_fixture()
impl.alter_column("tname", "y", name="y2")
new_table = self._assert_impl(impl, ddl_contains="UNIQUE (y2)")
eq_(new_table.c.y.name, "y2")
def test_alter_column_comment(self):
impl = self._simple_fixture()
impl.alter_column("tname", "x", comment="some comment")
new_table = self._assert_impl(impl)
eq_(new_table.c.x.comment, "some comment")
def test_add_column_comment(self):
impl = self._simple_fixture()
impl.add_column("tname", Column("q", Integer, comment="some comment"))
new_table = self._assert_impl(impl, colnames=["id", "x", "y", "q"])
eq_(new_table.c.q.comment, "some comment")
def test_rename_col_boolean(self):
impl = self._boolean_fixture()
impl.alter_column("tname", "flag", name="bflag")
new_table = self._assert_impl(
impl,
ddl_contains="CHECK (bflag IN (0, 1)",
colnames=["id", "flag"],
)
eq_(new_table.c.flag.name, "bflag")
eq_(
len(
[
const
for const in new_table.constraints
if isinstance(const, CheckConstraint)
]
),
1,
)
def test_change_type_schematype_to_non(self):
impl = self._boolean_fixture()
impl.alter_column("tname", "flag", type_=Integer)
new_table = self._assert_impl(
impl, colnames=["id", "flag"], ddl_not_contains="CHECK"
)
assert new_table.c.flag.type._type_affinity is Integer
# NOTE: we can't do test_change_type_non_to_schematype
# at this level because the "add_constraint" part of this
# comes from toimpl.py, which we aren't testing here
def test_rename_col_boolean_no_ck(self):
impl = self._boolean_no_ck_fixture()
impl.alter_column("tname", "flag", name="bflag")
new_table = self._assert_impl(
impl, ddl_not_contains="CHECK", colnames=["id", "flag"]
)
eq_(new_table.c.flag.name, "bflag")
eq_(
len(
[
const
for const in new_table.constraints
if isinstance(const, CheckConstraint)
]
),
0,
)
def test_rename_col_enum(self):
impl = self._enum_fixture()
impl.alter_column("tname", "thing", name="thang")
new_table = self._assert_impl(
impl,
ddl_contains="CHECK (thang IN ('a', 'b', 'c')",
colnames=["id", "thing"],
)
eq_(new_table.c.thing.name, "thang")
eq_(
len(
[
const
for const in new_table.constraints
if isinstance(const, CheckConstraint)
]
),
1,
)
def test_rename_col_literal_ck(self):
impl = self._literal_ck_fixture()
impl.alter_column("tname", "email", name="emol")
new_table = self._assert_impl(
# note this is wrong, we don't dig into the SQL
impl,
ddl_contains="CHECK (email LIKE '%@%')",
colnames=["id", "email"],
)
eq_(
len(
[
c
for c in new_table.constraints
if isinstance(c, CheckConstraint)
]
),
1,
)
eq_(new_table.c.email.name, "emol")
def test_rename_col_literal_ck_workaround(self):
impl = self._literal_ck_fixture(
copy_from=Table(
"tname",
MetaData(),
Column("id", Integer, primary_key=True),
Column("email", String),
),
table_args=[CheckConstraint("emol LIKE '%@%'")],
)
impl.alter_column("tname", "email", name="emol")
new_table = self._assert_impl(
impl,
ddl_contains="CHECK (emol LIKE '%@%')",
colnames=["id", "email"],
)
eq_(
len(
[
c
for c in new_table.constraints
if isinstance(c, CheckConstraint)
]
),
1,
)
eq_(new_table.c.email.name, "emol")
def test_rename_col_sql_ck(self):
impl = self._sql_ck_fixture()
impl.alter_column("tname", "email", name="emol")
new_table = self._assert_impl(
impl,
ddl_contains="CHECK (emol LIKE '%@%')",
colnames=["id", "email"],
)
eq_(
len(
[
c
for c in new_table.constraints
if isinstance(c, CheckConstraint)
]
),
1,
)
eq_(new_table.c.email.name, "emol")
def test_add_col(self):
impl = self._simple_fixture()
col = Column("g", Integer)
# operations.add_column produces a table
t = self.op.schema_obj.table("tname", col) # noqa
impl.add_column("tname", col)
new_table = self._assert_impl(impl, colnames=["id", "x", "y", "g"])
eq_(new_table.c.g.name, "g")
def test_partial_reordering(self):
impl = self._simple_fixture(partial_reordering=[("x", "id", "y")])
new_table = self._assert_impl(impl, colnames=["x", "id", "y"])
eq_(new_table.c.x.name, "x")
def test_add_col_partial_reordering(self):
impl = self._simple_fixture(partial_reordering=[("id", "x", "g", "y")])
col = Column("g", Integer)
# operations.add_column produces a table
t = self.op.schema_obj.table("tname", col) # noqa
impl.add_column("tname", col)
new_table = self._assert_impl(impl, colnames=["id", "x", "g", "y"])
eq_(new_table.c.g.name, "g")
def test_add_col_insert_before(self):
impl = self._simple_fixture()
col = Column("g", Integer)
# operations.add_column produces a table
t = self.op.schema_obj.table("tname", col) # noqa
impl.add_column("tname", col, insert_before="x")
new_table = self._assert_impl(impl, colnames=["id", "g", "x", "y"])
eq_(new_table.c.g.name, "g")
def test_add_col_insert_before_beginning(self):
impl = self._simple_fixture()
impl.add_column("tname", Column("g", Integer), insert_before="id")
new_table = self._assert_impl(impl, colnames=["g", "id", "x", "y"])
eq_(new_table.c.g.name, "g")
def test_add_col_insert_before_middle(self):
impl = self._simple_fixture()
impl.add_column("tname", Column("g", Integer), insert_before="y")
new_table = self._assert_impl(impl, colnames=["id", "x", "g", "y"])
eq_(new_table.c.g.name, "g")
def test_add_col_insert_after_middle(self):
impl = self._simple_fixture()
impl.add_column("tname", Column("g", Integer), insert_after="id")
new_table = self._assert_impl(impl, colnames=["id", "g", "x", "y"])
eq_(new_table.c.g.name, "g")
def test_add_col_insert_after_penultimate(self):
impl = self._simple_fixture()
impl.add_column("tname", Column("g", Integer), insert_after="x")
self._assert_impl(impl, colnames=["id", "x", "g", "y"])
def test_add_col_insert_after_end(self):
impl = self._simple_fixture()
impl.add_column("tname", Column("g", Integer), insert_after="y")
new_table = self._assert_impl(impl, colnames=["id", "x", "y", "g"])
eq_(new_table.c.g.name, "g")
def test_add_col_insert_after_plus_no_order(self):
impl = self._simple_fixture()
# operations.add_column produces a table
impl.add_column("tname", Column("g", Integer), insert_after="id")
impl.add_column("tname", Column("q", Integer))
new_table = self._assert_impl(
impl, colnames=["id", "g", "x", "y", "q"]
)
eq_(new_table.c.g.name, "g")
def test_add_col_no_order_plus_insert_after(self):
impl = self._simple_fixture()
col = Column("g", Integer)
# operations.add_column produces a table
t = self.op.schema_obj.table("tname", col) # noqa
impl.add_column("tname", Column("q", Integer))
impl.add_column("tname", Column("g", Integer), insert_after="id")
new_table = self._assert_impl(
impl, colnames=["id", "g", "x", "y", "q"]
)
eq_(new_table.c.g.name, "g")
def test_add_col_insert_after_another_insert(self):
impl = self._simple_fixture()
impl.add_column("tname", Column("g", Integer), insert_after="id")
impl.add_column("tname", Column("q", Integer), insert_after="g")
new_table = self._assert_impl(
impl, colnames=["id", "g", "q", "x", "y"]
)
eq_(new_table.c.g.name, "g")
def test_add_col_insert_before_another_insert(self):
impl = self._simple_fixture()
impl.add_column("tname", Column("g", Integer), insert_after="id")
impl.add_column("tname", Column("q", Integer), insert_before="g")
new_table = self._assert_impl(
impl, colnames=["id", "q", "g", "x", "y"]
)
eq_(new_table.c.g.name, "g")
def test_add_server_default(self):
impl = self._simple_fixture()
impl.alter_column("tname", "y", server_default="10")
new_table = self._assert_impl(impl, ddl_contains="DEFAULT '10'")
eq_(new_table.c.y.server_default.arg, "10")
def test_drop_server_default(self):
impl = self._server_default_fixture()
impl.alter_column("tname", "thing", server_default=None)
new_table = self._assert_impl(
impl, colnames=["id", "thing"], ddl_not_contains="DEFAULT"
)
eq_(new_table.c.thing.server_default, None)
def test_rename_col_pk(self):
impl = self._simple_fixture()
impl.alter_column("tname", "id", name="foobar")
new_table = self._assert_impl(
impl, ddl_contains="PRIMARY KEY (foobar)"
)
eq_(new_table.c.id.name, "foobar")
eq_(list(new_table.primary_key), [new_table.c.id])
def test_rename_col_fk(self):
impl = self._fk_fixture()
impl.alter_column("tname", "user_id", name="foobar")
new_table = self._assert_impl(
impl,
colnames=["id", "email", "user_id"],
ddl_contains='FOREIGN KEY(foobar) REFERENCES "user" (id)',
)
eq_(new_table.c.user_id.name, "foobar")
eq_(
list(new_table.c.user_id.foreign_keys)[0]._get_colspec(), "user.id"
)
def test_regen_multi_fk(self):
impl = self._multi_fk_fixture()
self._assert_impl(
impl,
colnames=[
"id",
"email",
"user_id_1",
"user_id_2",
"user_id_3",
"user_id_version",
],
ddl_contains="FOREIGN KEY(user_id_3, user_id_version) "
'REFERENCES "user" (id, id_version)',
)
def test_regen_multi_fk_schema(self):
impl = self._multi_fk_fixture(schema="foo_schema")
self._assert_impl(
impl,
colnames=[
"id",
"email",
"user_id_1",
"user_id_2",
"user_id_3",
"user_id_version",
],
ddl_contains="FOREIGN KEY(user_id_3, user_id_version) "
'REFERENCES foo_schema."user" (id, id_version)',
schema="foo_schema",
)
def test_do_not_add_existing_columns_columns(self):
impl = self._multi_fk_fixture()
meta = impl.table.metadata
cid = Column("id", Integer())
user = Table("user", meta, cid)
fk = [
c
for c in impl.unnamed_constraints
if isinstance(c, ForeignKeyConstraint)
]
impl._setup_referent(meta, fk[0])
is_(user.c.id, cid)
def test_drop_col(self):
impl = self._simple_fixture()
impl.drop_column("tname", column("x"))
new_table = self._assert_impl(impl, colnames=["id", "y"])
assert "y" in new_table.c
assert "x" not in new_table.c
def test_drop_col_remove_pk(self):
impl = self._simple_fixture()
impl.drop_column("tname", column("id"))
new_table = self._assert_impl(
impl, colnames=["x", "y"], ddl_not_contains="PRIMARY KEY"
)
assert "y" in new_table.c
assert "id" not in new_table.c
assert not new_table.primary_key
def test_drop_col_remove_fk(self):
impl = self._fk_fixture()
impl.drop_column("tname", column("user_id"))
new_table = self._assert_impl(
impl, colnames=["id", "email"], ddl_not_contains="FOREIGN KEY"
)
assert "user_id" not in new_table.c
assert not new_table.foreign_keys
def test_drop_col_retain_fk(self):
impl = self._fk_fixture()
impl.drop_column("tname", column("email"))
new_table = self._assert_impl(
impl,
colnames=["id", "user_id"],
ddl_contains='FOREIGN KEY(user_id) REFERENCES "user" (id)',
)
assert "email" not in new_table.c
assert new_table.c.user_id.foreign_keys
def test_drop_col_retain_fk_selfref(self):
impl = self._selfref_fk_fixture()
impl.drop_column("tname", column("data"))
new_table = self._assert_impl(impl, colnames=["id", "parent_id"])
assert "data" not in new_table.c
assert new_table.c.parent_id.foreign_keys
def test_add_fk(self):
impl = self._simple_fixture()
impl.add_column("tname", Column("user_id", Integer))
fk = self.op.schema_obj.foreign_key_constraint(
"fk1", "tname", "user", ["user_id"], ["id"]
)
impl.add_constraint(fk)
new_table = self._assert_impl(
impl,
colnames=["id", "x", "y", "user_id"],
ddl_contains=(
"CONSTRAINT fk1 FOREIGN KEY(user_id) " 'REFERENCES "user" (id)'
),
)
eq_(
list(new_table.c.user_id.foreign_keys)[0]._get_colspec(), "user.id"
)
def test_drop_fk(self):
impl = self._named_fk_fixture()
fk = ForeignKeyConstraint([], [], name="ufk")
impl.drop_constraint(fk)
new_table = self._assert_impl(
impl,
colnames=["id", "email", "user_id"],
ddl_not_contains="CONSTRAINT ufk",
)
eq_(list(new_table.foreign_keys), [])
def test_add_uq(self):
impl = self._simple_fixture()
uq = self.op.schema_obj.unique_constraint("uq1", "tname", ["y"])
impl.add_constraint(uq)
self._assert_impl(
impl,
colnames=["id", "x", "y"],
ddl_contains="CONSTRAINT uq1 UNIQUE",
)
def test_drop_uq(self):
impl = self._uq_fixture()
uq = self.op.schema_obj.unique_constraint("uq1", "tname", ["y"])
impl.drop_constraint(uq)
self._assert_impl(
impl,
colnames=["id", "x", "y"],
ddl_not_contains="CONSTRAINT uq1 UNIQUE",
)
def test_add_ck_unnamed(self):
"""test for #1195"""
impl = self._simple_fixture()
ck = self.op.schema_obj.check_constraint(_NONE_NAME, "tname", "y > 5")
impl.add_constraint(ck)
self._assert_impl(
impl,
colnames=["id", "x", "y"],
ddl_contains="CHECK (y > 5)",
)
def test_add_ck(self):
impl = self._simple_fixture()
ck = self.op.schema_obj.check_constraint("ck1", "tname", "y > 5")
impl.add_constraint(ck)
self._assert_impl(
impl,
colnames=["id", "x", "y"],
ddl_contains="CONSTRAINT ck1 CHECK (y > 5)",
)
def test_drop_ck_table(self):
impl = self._named_ck_table_fixture()
ck = self.op.schema_obj.check_constraint("ck1", "tname", "y > 5")
impl.drop_constraint(ck)
self._assert_impl(
impl,
colnames=["id", "x", "y"],
ddl_not_contains="CONSTRAINT ck1 CHECK (y > 5)",
)
def test_drop_ck_col(self):
impl = self._named_ck_col_fixture()
ck = self.op.schema_obj.check_constraint("ck1", "tname", "y > 5")
impl.drop_constraint(ck)
self._assert_impl(
impl,
colnames=["id", "x", "y"],
ddl_not_contains="CONSTRAINT ck1 CHECK (y > 5)",
)
def test_create_index(self):
impl = self._simple_fixture()
ix = self.op.schema_obj.index("ix1", "tname", ["y"])
impl.create_index(ix)
self._assert_impl(
impl, colnames=["id", "x", "y"], ddl_contains="CREATE INDEX ix1"
)
def test_drop_index(self):
impl = self._ix_fixture()
ix = self.op.schema_obj.index("ix1", "tname", ["y"])
impl.drop_index(ix)
self._assert_impl(
impl,
colnames=["id", "x", "y"],
ddl_not_contains="CONSTRAINT uq1 UNIQUE",
)
def test_add_table_opts(self):
impl = self._simple_fixture(table_kwargs={"mysql_engine": "InnoDB"})
self._assert_impl(impl, ddl_contains="ENGINE=InnoDB", dialect="mysql")
def test_drop_pk(self):
impl = self._pk_fixture()
pk = self.op.schema_obj.primary_key_constraint("mypk", "tname", ["id"])
impl.drop_constraint(pk)
new_table = self._assert_impl(impl)
assert not new_table.c.id.primary_key
assert not len(new_table.primary_key)
class BatchAPITest(TestBase):
@contextmanager
def _fixture(self, schema=None):
migration_context = mock.Mock(
opts={},
impl=mock.MagicMock(__dialect__="sqlite", connection=object()),
)
op = Operations(migration_context)
batch = op.batch_alter_table(
"tname", recreate="never", schema=schema
).__enter__()
mock_schema = mock.MagicMock()
with mock.patch("alembic.operations.schemaobj.sa_schema", mock_schema):
yield batch
batch.impl.flush()
self.mock_schema = mock_schema
def test_drop_col(self):
with self._fixture() as batch:
batch.drop_column("q")
eq_(
batch.impl.operations.impl.mock_calls,
[
mock.call.drop_column(
"tname",
self.mock_schema.Column(),
schema=None,
if_exists=None,
)
],
)
def test_add_col(self):
column = Column("w", String(50))
with self._fixture() as batch:
batch.add_column(column)
assert (
mock.call.add_column(
"tname",
column,
schema=None,
if_not_exists=None,
inline_references=None,
inline_primary_key=None,
)
in batch.impl.operations.impl.mock_calls
)
def test_create_fk(self):
with self._fixture() as batch:
batch.create_foreign_key("myfk", "user", ["x"], ["y"])
eq_(
self.mock_schema.ForeignKeyConstraint.mock_calls,
[
mock.call(
["x"],
["user.y"],
onupdate=None,
ondelete=None,
name="myfk",
initially=None,
deferrable=None,
match=None,
)
],
)
eq_(
self.mock_schema.Table.mock_calls,
[
mock.call(
"user",
self.mock_schema.MetaData(),
self.mock_schema.Column(),
schema=None,
),
mock.call(
"tname",
self.mock_schema.MetaData(),
self.mock_schema.Column(),
schema=None,
),
mock.call().append_constraint(
self.mock_schema.ForeignKeyConstraint()
),
],
)
eq_(
batch.impl.operations.impl.mock_calls,
[
mock.call.add_constraint(
self.mock_schema.ForeignKeyConstraint()
)
],
)
def test_create_fk_schema(self):
with self._fixture(schema="foo") as batch:
batch.create_foreign_key("myfk", "user", ["x"], ["y"])