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
|
from sqlalchemy import DateTime, MetaData, Table, Column, text, Integer, \
String, Interval
from sqlalchemy.dialects.postgresql import ARRAY
from sqlalchemy.engine.reflection import Inspector
from alembic.operations import Operations
from sqlalchemy.sql import table, column
from alembic.autogenerate.compare import _compare_server_default
from alembic import command, util
from alembic.migration import MigrationContext
from alembic.script import ScriptDirectory
from alembic.testing import eq_
from alembic.testing.env import staging_env, clear_staging_env, \
_no_sql_testing_config, write_script
from alembic.testing.fixtures import capture_context_buffer
from alembic.testing.fixtures import TestBase
from alembic.testing import config
class PGOfflineEnumTest(TestBase):
def setUp(self):
staging_env()
self.cfg = cfg = _no_sql_testing_config()
self.rid = rid = util.rev_id()
self.script = script = ScriptDirectory.from_config(cfg)
script.generate_revision(rid, None, refresh=True)
def tearDown(self):
clear_staging_env()
def _inline_enum_script(self):
write_script(self.script, self.rid, """
revision = '%s'
down_revision = None
from alembic import op
from sqlalchemy.dialects.postgresql import ENUM
from sqlalchemy import Column
def upgrade():
op.create_table("sometable",
Column("data", ENUM("one", "two", "three", name="pgenum"))
)
def downgrade():
op.drop_table("sometable")
""" % self.rid)
def _distinct_enum_script(self):
write_script(self.script, self.rid, """
revision = '%s'
down_revision = None
from alembic import op
from sqlalchemy.dialects.postgresql import ENUM
from sqlalchemy import Column
def upgrade():
enum = ENUM("one", "two", "three", name="pgenum", create_type=False)
enum.create(op.get_bind(), checkfirst=False)
op.create_table("sometable",
Column("data", enum)
)
def downgrade():
op.drop_table("sometable")
ENUM(name="pgenum").drop(op.get_bind(), checkfirst=False)
""" % self.rid)
@config.requirements.sqlalchemy_09
def test_offline_inline_enum_create(self):
self._inline_enum_script()
with capture_context_buffer() as buf:
command.upgrade(self.cfg, self.rid, sql=True)
assert "CREATE TYPE pgenum AS "\
"ENUM ('one', 'two', 'three')" in buf.getvalue()
assert "CREATE TABLE sometable (\n data pgenum\n)" in buf.getvalue()
def test_offline_inline_enum_drop(self):
self._inline_enum_script()
with capture_context_buffer() as buf:
command.downgrade(self.cfg, "%s:base" % self.rid, sql=True)
assert "DROP TABLE sometable" in buf.getvalue()
# no drop since we didn't emit events
assert "DROP TYPE pgenum" not in buf.getvalue()
@config.requirements.sqlalchemy_09
def test_offline_distinct_enum_create(self):
self._distinct_enum_script()
with capture_context_buffer() as buf:
command.upgrade(self.cfg, self.rid, sql=True)
assert "CREATE TYPE pgenum AS ENUM "\
"('one', 'two', 'three')" in buf.getvalue()
assert "CREATE TABLE sometable (\n data pgenum\n)" in buf.getvalue()
def test_offline_distinct_enum_drop(self):
self._distinct_enum_script()
with capture_context_buffer() as buf:
command.downgrade(self.cfg, "%s:base" % self.rid, sql=True)
assert "DROP TABLE sometable" in buf.getvalue()
assert "DROP TYPE pgenum" in buf.getvalue()
class PostgresqlInlineLiteralTest(TestBase):
__only_on__ = 'postgresql'
@classmethod
def setup_class(cls):
cls.bind = config.db
cls.bind.execute("""
create table tab (
col varchar(50)
)
""")
cls.bind.execute("""
insert into tab (col) values
('old data 1'),
('old data 2.1'),
('old data 3')
""")
@classmethod
def teardown_class(cls):
cls.bind.execute("drop table tab")
def setUp(self):
self.conn = self.bind.connect()
ctx = MigrationContext.configure(self.conn)
self.op = Operations(ctx)
def tearDown(self):
self.conn.close()
def test_inline_percent(self):
# TODO: here's the issue, you need to escape this.
tab = table('tab', column('col'))
self.op.execute(
tab.update().where(
tab.c.col.like(self.op.inline_literal('%.%'))
).values(col=self.op.inline_literal('new data')),
execution_options={'no_parameters': True}
)
eq_(
self.conn.execute(
"select count(*) from tab where col='new data'").scalar(),
1,
)
class PostgresqlDefaultCompareTest(TestBase):
__only_on__ = 'postgresql'
@classmethod
def setup_class(cls):
cls.bind = config.db
staging_env()
context = MigrationContext.configure(
connection=cls.bind.connect(),
opts={
'compare_type': True,
'compare_server_default': True
}
)
connection = context.bind
cls.autogen_context = {
'imports': set(),
'connection': connection,
'dialect': connection.dialect,
'context': context
}
@classmethod
def teardown_class(cls):
clear_staging_env()
def setUp(self):
self.metadata = MetaData(self.bind)
def tearDown(self):
self.metadata.drop_all()
def _compare_default_roundtrip(self, type_, orig_default, alternate=None):
diff_expected = alternate is not None
if alternate is None:
alternate = orig_default
t1 = Table("test", self.metadata,
Column("somecol", type_, server_default=orig_default))
t2 = Table("test", MetaData(),
Column("somecol", type_, server_default=alternate))
t1.create(self.bind)
insp = Inspector.from_engine(self.bind)
cols = insp.get_columns(t1.name)
insp_col = Column("somecol", cols[0]['type'],
server_default=text(cols[0]['default']))
diffs = []
_compare_server_default(None, "test", "somecol", insp_col,
t2.c.somecol, diffs, self.autogen_context)
eq_(bool(diffs), diff_expected)
def _compare_default(
self,
t1, t2, col,
rendered
):
t1.create(self.bind, checkfirst=True)
insp = Inspector.from_engine(self.bind)
cols = insp.get_columns(t1.name)
ctx = self.autogen_context['context']
return ctx.impl.compare_server_default(
None,
col,
rendered,
cols[0]['default'])
def test_compare_interval_str(self):
# this form shouldn't be used but testing here
# for compatibility
self._compare_default_roundtrip(
Interval,
"14 days"
)
def test_compare_interval_text(self):
self._compare_default_roundtrip(
Interval,
text("'14 days'")
)
def test_compare_array_of_integer_text(self):
self._compare_default_roundtrip(
ARRAY(Integer),
text("(ARRAY[]::integer[])")
)
def test_compare_current_timestamp_text(self):
self._compare_default_roundtrip(
DateTime(),
text("TIMEZONE('utc', CURRENT_TIMESTAMP)"),
)
def test_compare_integer_str(self):
self._compare_default_roundtrip(
Integer(),
"5",
)
def test_compare_integer_text(self):
self._compare_default_roundtrip(
Integer(),
text("5"),
)
def test_compare_integer_text_diff(self):
self._compare_default_roundtrip(
Integer(),
text("5"), "7"
)
def test_compare_character_str(self):
self._compare_default_roundtrip(
String(),
"hello",
)
def test_compare_character_text(self):
self._compare_default_roundtrip(
String(),
text("'hello'"),
)
def test_compare_character_str_diff(self):
self._compare_default_roundtrip(
String(),
"hello",
"there"
)
def test_compare_character_text_diff(self):
self._compare_default_roundtrip(
String(),
text("'hello'"),
text("'there'")
)
def test_primary_key_skip(self):
"""Test that SERIAL cols are just skipped"""
t1 = Table("sometable", self.metadata,
Column("id", Integer, primary_key=True)
)
t2 = Table("sometable", MetaData(),
Column("id", Integer, primary_key=True)
)
assert not self._compare_default(
t1, t2, t2.c.id, ""
)
|