summaryrefslogtreecommitdiff
path: root/tests/test_sqlite.py
blob: b8edeaaf1a18fcb0513a7a01338540e59d86ba5a (plain)
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
from sqlalchemy import Boolean
from sqlalchemy import Column
from sqlalchemy import DateTime
from sqlalchemy import Float
from sqlalchemy import func
from sqlalchemy import inspect
from sqlalchemy import Integer
from sqlalchemy import MetaData
from sqlalchemy import String
from sqlalchemy import Table
from sqlalchemy import text
from sqlalchemy.sql import column

from alembic import autogenerate
from alembic import op
from alembic.autogenerate import api
from alembic.autogenerate.compare import _compare_server_default
from alembic.migration import MigrationContext
from alembic.operations import ops
from alembic.testing import assert_raises_message
from alembic.testing import config
from alembic.testing import eq_
from alembic.testing import eq_ignore_whitespace
from alembic.testing.env import clear_staging_env
from alembic.testing.env import staging_env
from alembic.testing.fixtures import op_fixture
from alembic.testing.fixtures import TestBase


class SQLiteTest(TestBase):
    def test_add_column(self):
        context = op_fixture("sqlite")
        op.add_column("t1", Column("c1", Integer))
        context.assert_("ALTER TABLE t1 ADD COLUMN c1 INTEGER")

    def test_add_column_implicit_constraint(self):
        context = op_fixture("sqlite")
        op.add_column("t1", Column("c1", Boolean))
        context.assert_("ALTER TABLE t1 ADD COLUMN c1 BOOLEAN")

    def test_add_explicit_constraint(self):
        op_fixture("sqlite")
        assert_raises_message(
            NotImplementedError,
            "No support for ALTER of constraints in SQLite dialect",
            op.create_check_constraint,
            "foo",
            "sometable",
            column("name") > 5,
        )

    def test_drop_explicit_constraint(self):
        op_fixture("sqlite")
        assert_raises_message(
            NotImplementedError,
            "No support for ALTER of constraints in SQLite dialect",
            op.drop_constraint,
            "foo",
            "sometable",
        )

    @config.requirements.comments
    def test_create_table_with_comment_ignored(self):

        context = op_fixture("sqlite")
        op.create_table(
            "t2",
            Column("c1", Integer, primary_key=True),
            Column("c2", Integer),
            comment="This is a table comment",
        )
        context.assert_(
            "CREATE TABLE t2 (c1 INTEGER NOT NULL, "
            "c2 INTEGER, PRIMARY KEY (c1))"
        )

    @config.requirements.comments
    def test_add_column_with_comment_ignored(self):

        context = op_fixture("sqlite")
        op.add_column("t1", Column("c1", Integer, comment="c1 comment"))
        context.assert_("ALTER TABLE t1 ADD COLUMN c1 INTEGER")

    def test_rename_table_w_schema(self):
        context = op_fixture("sqlite")
        op.rename_table("old_name", "new_name", schema="my_schema")
        context.assert_("ALTER TABLE my_schema.old_name RENAME TO new_name")


class SQLiteDefaultCompareTest(TestBase):
    __only_on__ = "sqlite"
    __backend__ = True

    @classmethod
    def setup_class(cls):
        cls.bind = config.db
        staging_env()
        cls.migration_context = MigrationContext.configure(
            connection=cls.bind.connect(),
            opts={"compare_type": True, "compare_server_default": True},
        )

    def setUp(self):
        self.metadata = MetaData()
        self.autogen_context = api.AutogenContext(self.migration_context)

    @classmethod
    def teardown_class(cls):
        clear_staging_env()

    def tearDown(self):
        self.metadata.drop_all(config.db)

    def _compare_default_roundtrip(
        self, type_, orig_default, alternate=None, diff_expected=None
    ):
        diff_expected = (
            diff_expected
            if diff_expected is not None
            else 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 = inspect(self.bind)
        cols = insp.get_columns(t1.name)
        insp_col = Column(
            "somecol", cols[0]["type"], server_default=text(cols[0]["default"])
        )
        op = ops.AlterColumnOp("test", "somecol")
        _compare_server_default(
            self.autogen_context,
            op,
            None,
            "test",
            "somecol",
            insp_col,
            t2.c.somecol,
        )

        diffs = op.to_diff_tuple()
        eq_(bool(diffs), diff_expected)

    def _compare_default(self, t1, t2, col, rendered):
        t1.create(self.bind, checkfirst=True)
        insp = inspect(self.bind)
        cols = insp.get_columns(t1.name)
        ctx = self.autogen_context.migration_context

        return ctx.impl.compare_server_default(
            None, col, rendered, cols[0]["default"]
        )

    def test_compare_current_timestamp_func(self):
        self._compare_default_roundtrip(
            DateTime(), func.datetime("now", "localtime")
        )

    def test_compare_current_timestamp_func_now(self):
        self._compare_default_roundtrip(DateTime(), func.now())

    def test_compare_current_timestamp_text(self):
        # SQLAlchemy doesn't render the parenthesis for a
        # SQLite server default specified as text(), so users will be doing
        # this; sqlite comparison needs to accommodate for these.
        self._compare_default_roundtrip(
            DateTime(), text("(datetime('now', 'localtime'))")
        )

    def test_compare_integer_str(self):
        self._compare_default_roundtrip(Integer(), "5")

    def test_compare_integer_str_diff(self):
        self._compare_default_roundtrip(Integer(), "5", "7")

    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_float_str(self):
        self._compare_default_roundtrip(Float(), "5.2")

    def test_compare_float_str_diff(self):
        self._compare_default_roundtrip(Float(), "5.2", "5.3")

    def test_compare_float_text(self):
        self._compare_default_roundtrip(Float(), text("5.2"))

    def test_compare_float_text_diff(self):
        self._compare_default_roundtrip(Float(), text("5.2"), "5.3")

    def test_compare_string_literal(self):
        self._compare_default_roundtrip(String(), "im a default")

    def test_compare_string_literal_diff(self):
        self._compare_default_roundtrip(String(), "im a default", "me too")


class SQLiteAutogenRenderTest(TestBase):
    def setUp(self):
        ctx_opts = {
            "sqlalchemy_module_prefix": "sa.",
            "alembic_module_prefix": "op.",
            "target_metadata": MetaData(),
        }
        context = MigrationContext.configure(
            dialect_name="sqlite", opts=ctx_opts
        )

        self.autogen_context = api.AutogenContext(context)

    def test_render_server_default_expr_needs_parens(self):
        c = Column(
            "date_value",
            DateTime(),
            server_default=func.datetime("now", "localtime"),
        )

        result = autogenerate.render._render_column(c, self.autogen_context)
        eq_ignore_whitespace(
            result,
            "sa.Column('date_value', sa.DateTime(), "
            "server_default=sa.text(\"(datetime('now', 'localtime'))\"), "
            "nullable=True)",
        )

    def test_render_server_default_text_expr_needs_parens(self):
        c = Column(
            "date_value",
            DateTime(),
            server_default=text("(datetime('now', 'localtime'))"),
        )

        result = autogenerate.render._render_column(c, self.autogen_context)
        eq_ignore_whitespace(
            result,
            "sa.Column('date_value', sa.DateTime(), "
            "server_default=sa.text(\"(datetime('now', 'localtime'))\"), "
            "nullable=True)",
        )

    def test_render_server_default_const(self):
        c = Column("int_value", Integer, server_default="5")

        result = autogenerate.render._render_column(c, self.autogen_context)
        eq_ignore_whitespace(
            result,
            "sa.Column('int_value', sa.Integer(), server_default='5', "
            "nullable=True)",
        )

    @config.requirements.sqlalchemy_13
    def test_render_add_column_w_on_conflict(self):
        c = Column("int_value", Integer, sqlite_on_conflict_not_null="FAIL")

        result = autogenerate.render._render_column(c, self.autogen_context)
        eq_ignore_whitespace(
            result,
            "sa.Column('int_value', sa.Integer(), "
            "nullable=True, sqlite_on_conflict_not_null='FAIL')",
        )