1f41fd8965d646f4d67e73794f91c8d0ee7b9189
[moon.git] /
1 # Licensed under the Apache License, Version 2.0 (the "License"); you may
2 # not use this file except in compliance with the License. You may obtain
3 # a copy of the License at
4 #
5 #      http://www.apache.org/licenses/LICENSE-2.0
6 #
7 # Unless required by applicable law or agreed to in writing, software
8 # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
9 # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
10 # License for the specific language governing permissions and limitations
11 # under the License.
12
13 import migrate
14 import sqlalchemy as sql
15 from sqlalchemy import func
16
17
18 def upgrade(migrate_engine):
19     meta = sql.MetaData()
20     meta.bind = migrate_engine
21
22     user_table = sql.Table('user', meta, autoload=True)
23     local_user_table = sql.Table('local_user', meta, autoload=True)
24     password_table = sql.Table('password', meta, autoload=True)
25
26     # migrate data to local_user table
27     local_user_values = []
28     for row in user_table.select().execute():
29         # skip the row that already exists in `local_user`, this could
30         # happen if run into a partially-migrated table due to the
31         # bug #1549705.
32         filter_by = local_user_table.c.user_id == row['id']
33         user_count = sql.select([func.count()]).select_from(
34             local_user_table).where(filter_by).execute().fetchone()[0]
35         if user_count == 0:
36             local_user_values.append({'user_id': row['id'],
37                                       'domain_id': row['domain_id'],
38                                       'name': row['name']})
39     if local_user_values:
40         local_user_table.insert().values(local_user_values).execute()
41
42     # migrate data to password table
43     sel = (
44         sql.select([user_table, local_user_table], use_labels=True)
45            .select_from(user_table.join(local_user_table, user_table.c.id ==
46                                         local_user_table.c.user_id))
47     )
48     user_rows = sel.execute()
49     password_values = []
50     for row in user_rows:
51         if row['user_password']:
52             password_values.append({'local_user_id': row['local_user_id'],
53                                     'password': row['user_password']})
54     if password_values:
55         password_table.insert().values(password_values).execute()
56
57     # remove domain_id and name unique constraint
58     if migrate_engine.name != 'sqlite':
59         migrate.UniqueConstraint(user_table.c.domain_id,
60                                  user_table.c.name,
61                                  name='ixu_user_name_domain_id').drop()
62
63     # drop user columns
64     user_table.c.domain_id.drop()
65     user_table.c.name.drop()
66     user_table.c.password.drop()