summaryrefslogtreecommitdiff
path: root/glance/db/sqlalchemy/migrate_repo/versions/012_id_to_uuid.py
blob: 0701f14f0a111d87c478ef77a03a57e5ca51be80 (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
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
# Copyright 2013 IBM Corp.
# Copyright 2011 OpenStack Foundation
# All Rights Reserved.
#
#    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
#
#         http://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.

"""
While SQLAlchemy/sqlalchemy-migrate should abstract this correctly,
there are known issues with these libraries so SQLite and non-SQLite
migrations must be done separately.
"""

import uuid

import migrate
import sqlalchemy


and_ = sqlalchemy.and_
or_ = sqlalchemy.or_


def upgrade(migrate_engine):
    """
    Call the correct dialect-specific upgrade.
    """
    meta = sqlalchemy.MetaData()
    meta.bind = migrate_engine

    t_images = _get_table('images', meta)
    t_image_members = _get_table('image_members', meta)
    t_image_properties = _get_table('image_properties', meta)

    dialect = migrate_engine.url.get_dialect().name
    if dialect == "sqlite":
        _upgrade_sqlite(meta, t_images, t_image_members, t_image_properties)
        _update_all_ids_to_uuids(t_images, t_image_members, t_image_properties)
    elif dialect == "ibm_db_sa":
        _upgrade_db2(meta, t_images, t_image_members, t_image_properties)
        _update_all_ids_to_uuids(t_images, t_image_members, t_image_properties)
        _add_db2_constraints(meta)
    else:
        _upgrade_other(t_images, t_image_members, t_image_properties, dialect)


def _upgrade_sqlite(meta, t_images, t_image_members, t_image_properties):
    """
    Upgrade 011 -> 012 with special SQLite-compatible logic.
    """

    sql_commands = [
        """CREATE TABLE images_backup (
           id VARCHAR(36) NOT NULL,
           name VARCHAR(255),
           size INTEGER,
           status VARCHAR(30) NOT NULL,
           is_public BOOLEAN NOT NULL,
           location TEXT,
           created_at DATETIME NOT NULL,
           updated_at DATETIME,
           deleted_at DATETIME,
           deleted BOOLEAN NOT NULL,
           disk_format VARCHAR(20),
           container_format VARCHAR(20),
           checksum VARCHAR(32),
           owner VARCHAR(255),
           min_disk INTEGER NOT NULL,
           min_ram INTEGER NOT NULL,
           PRIMARY KEY (id),
           CHECK (is_public IN (0, 1)),
           CHECK (deleted IN (0, 1))
        );""",
        """INSERT INTO images_backup
           SELECT * FROM images;""",
        """CREATE TABLE image_members_backup (
            id INTEGER NOT NULL,
            image_id VARCHAR(36) NOT NULL,
            member VARCHAR(255) NOT NULL,
            can_share BOOLEAN NOT NULL,
            created_at DATETIME NOT NULL,
            updated_at DATETIME,
            deleted_at DATETIME,
            deleted BOOLEAN NOT NULL,
            PRIMARY KEY (id),
            UNIQUE (image_id, member),
            CHECK (can_share IN (0, 1)),
            CHECK (deleted IN (0, 1)),
            FOREIGN KEY(image_id) REFERENCES images (id)
        );""",
        """INSERT INTO image_members_backup
            SELECT * FROM image_members;""",
        """CREATE TABLE image_properties_backup (
            id INTEGER NOT NULL,
            image_id VARCHAR(36) NOT NULL,
            name VARCHAR(255) NOT NULL,
            value TEXT,
            created_at DATETIME NOT NULL,
            updated_at DATETIME,
            deleted_at DATETIME,
            deleted BOOLEAN NOT NULL,
            PRIMARY KEY (id),
            CHECK (deleted IN (0, 1)),
            UNIQUE (image_id, name),
            FOREIGN KEY(image_id) REFERENCES images (id)
        );""",
        """INSERT INTO image_properties_backup
            SELECT * FROM image_properties;""",
    ]

    for command in sql_commands:
        meta.bind.execute(command)

    _sqlite_table_swap(meta, t_image_members, t_image_properties, t_images)


def _upgrade_db2(meta, t_images, t_image_members, t_image_properties):
    """
    Upgrade for DB2.
    """
    t_images.c.id.alter(sqlalchemy.String(36), primary_key=True)

    image_members_backup = sqlalchemy.Table(
        'image_members_backup',
        meta,
        sqlalchemy.Column('id',
                          sqlalchemy.Integer(),
                          primary_key=True,
                          nullable=False),
        sqlalchemy.Column('image_id',
                          sqlalchemy.String(36),
                          nullable=False,
                          index=True),
        sqlalchemy.Column('member',
                          sqlalchemy.String(255),
                          nullable=False),
        sqlalchemy.Column('can_share',
                          sqlalchemy.Boolean(),
                          nullable=False,
                          default=False),
        sqlalchemy.Column('created_at',
                          sqlalchemy.DateTime(),
                          nullable=False),
        sqlalchemy.Column('updated_at',
                          sqlalchemy.DateTime()),
        sqlalchemy.Column('deleted_at',
                          sqlalchemy.DateTime()),
        sqlalchemy.Column('deleted',
                          sqlalchemy.Boolean(),
                          nullable=False,
                          default=False,
                          index=True),
        sqlalchemy.UniqueConstraint('image_id', 'member'),
        extend_existing=True)

    image_properties_backup = sqlalchemy.Table(
        'image_properties_backup',
        meta,
        sqlalchemy.Column('id',
                          sqlalchemy.Integer(),
                          primary_key=True,
                          nullable=False),
        sqlalchemy.Column('image_id',
                          sqlalchemy.String(36),
                          nullable=False,
                          index=True),
        sqlalchemy.Column('name',
                          sqlalchemy.String(255),
                          nullable=False),
        sqlalchemy.Column('value',
                          sqlalchemy.Text()),
        sqlalchemy.Column('created_at',
                          sqlalchemy.DateTime(),
                          nullable=False),
        sqlalchemy.Column('updated_at',
                          sqlalchemy.DateTime()),
        sqlalchemy.Column('deleted_at',
                          sqlalchemy.DateTime()),
        sqlalchemy.Column('deleted',
                          sqlalchemy.Boolean(),
                          nullable=False,
                          default=False,
                          index=True),
        sqlalchemy.UniqueConstraint(
            'image_id', 'name',
            name='ix_image_properties_image_id_name'),
        extend_existing=True)

    image_members_backup.create()
    image_properties_backup.create()

    sql_commands = [
        """INSERT INTO image_members_backup
            SELECT * FROM image_members;""",
        """INSERT INTO image_properties_backup
            SELECT * FROM image_properties;""",
    ]

    for command in sql_commands:
        meta.bind.execute(command)

    t_image_members.drop()
    t_image_properties.drop()

    image_members_backup.rename(name='image_members')
    image_properties_backup.rename(name='image_properties')


def _add_db2_constraints(meta):
    # Create the foreign keys
    sql_commands = [
        """ALTER TABLE image_members ADD CONSTRAINT member_image_id
            FOREIGN KEY (image_id)
            REFERENCES images (id);""",
        """ALTER TABLE image_properties ADD CONSTRAINT property_image_id
            FOREIGN KEY (image_id)
            REFERENCES images (id);""",
    ]
    for command in sql_commands:
        meta.bind.execute(command)


def _upgrade_other(t_images, t_image_members, t_image_properties, dialect):
    """
    Upgrade 011 -> 012 with logic for non-SQLite databases.
    """
    foreign_keys = _get_foreign_keys(t_images,
                                     t_image_members,
                                     t_image_properties, dialect)

    for fk in foreign_keys:
        fk.drop()

    t_images.c.id.alter(sqlalchemy.String(36), primary_key=True)
    t_image_members.c.image_id.alter(sqlalchemy.String(36))
    t_image_properties.c.image_id.alter(sqlalchemy.String(36))

    _update_all_ids_to_uuids(t_images, t_image_members, t_image_properties)

    for fk in foreign_keys:
        fk.create()


def _sqlite_table_swap(meta, t_image_members, t_image_properties, t_images):
    t_image_members.drop()
    t_image_properties.drop()
    t_images.drop()

    meta.bind.execute("ALTER TABLE images_backup "
                      "RENAME TO images")
    meta.bind.execute("ALTER TABLE image_members_backup "
                      "RENAME TO image_members")
    meta.bind.execute("ALTER TABLE image_properties_backup "
                      "RENAME TO image_properties")
    meta.bind.execute("""CREATE INDEX ix_image_properties_deleted
                          ON image_properties (deleted);""")
    meta.bind.execute("""CREATE INDEX ix_image_properties_name
                          ON image_properties (name);""")


def _get_table(table_name, metadata):
    """Return a sqlalchemy Table definition with associated metadata."""
    return sqlalchemy.Table(table_name, metadata, autoload=True)


def _get_foreign_keys(t_images, t_image_members, t_image_properties, dialect):
    """Retrieve and return foreign keys for members/properties tables."""
    foreign_keys = []
    if t_image_members.foreign_keys:
        img_members_fk_name = list(t_image_members.foreign_keys)[0].name
        if dialect == 'mysql':
            fk1 = migrate.ForeignKeyConstraint([t_image_members.c.image_id],
                                               [t_images.c.id],
                                               name=img_members_fk_name)
        else:
            fk1 = migrate.ForeignKeyConstraint([t_image_members.c.image_id],
                                               [t_images.c.id])
        foreign_keys.append(fk1)

    if t_image_properties.foreign_keys:
        img_properties_fk_name = list(t_image_properties.foreign_keys)[0].name
        if dialect == 'mysql':
            fk2 = migrate.ForeignKeyConstraint([t_image_properties.c.image_id],
                                               [t_images.c.id],
                                               name=img_properties_fk_name)
        else:
            fk2 = migrate.ForeignKeyConstraint([t_image_properties.c.image_id],
                                               [t_images.c.id])
        foreign_keys.append(fk2)

    return foreign_keys


def _update_all_ids_to_uuids(t_images, t_image_members, t_image_properties):
    """Transition from INTEGER id to VARCHAR(36) id."""
    images = list(t_images.select().execute())

    for image in images:
        old_id = image["id"]
        new_id = str(uuid.uuid4())

        t_images.update().where(
            t_images.c.id == old_id).values(id=new_id).execute()

        t_image_members.update().where(
            t_image_members.c.image_id == old_id).values(
                image_id=new_id).execute()

        t_image_properties.update().where(
            t_image_properties.c.image_id == old_id).values(
                image_id=new_id).execute()

        t_image_properties.update().where(
            and_(or_(t_image_properties.c.name == 'kernel_id',
                     t_image_properties.c.name == 'ramdisk_id'),
                 t_image_properties.c.value == old_id)).values(
                     value=new_id).execute()


def _update_all_uuids_to_ids(t_images, t_image_members, t_image_properties):
    """Transition from VARCHAR(36) id to INTEGER id."""
    images = list(t_images.select().execute())

    new_id = 1
    for image in images:
        old_id = image["id"]

        t_images.update().where(
            t_images.c.id == old_id).values(
                id=str(new_id)).execute()

        t_image_members.update().where(
            t_image_members.c.image_id == old_id).values(
                image_id=str(new_id)).execute()

        t_image_properties.update().where(
            t_image_properties.c.image_id == old_id).values(
                image_id=str(new_id)).execute()

        t_image_properties.update().where(
            and_(or_(t_image_properties.c.name == 'kernel_id',
                     t_image_properties.c.name == 'ramdisk_id'),
                 t_image_properties.c.value == old_id)).values(
                     value=str(new_id)).execute()

        new_id += 1