-
Notifications
You must be signed in to change notification settings - Fork 136
/
migrator.py
583 lines (548 loc) · 24.2 KB
/
migrator.py
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
import copy
import datetime
import locale
import os
import pickle
import sys
from ._compat import PY2, string_types, pjoin, iteritems, to_bytes, exists
from ._load import portalocker
from .helpers.classes import SQLCustomType, DatabaseStoredFile
class Migrator(object):
def __init__(self, adapter):
self.adapter = adapter
@property
def db(self):
return self.adapter.db
@property
def dialect(self):
return self.adapter.dialect
@property
def dbengine(self):
return self.adapter.dbengine
def create_table(self, table, migrate=True, fake_migrate=False, polymodel=None):
db = table._db
table._migrate = migrate
fields = []
# PostGIS geo fields are added after the table has been created
postcreation_fields = []
sql_fields = {}
sql_fields_aux = {}
TFK = {}
tablename = table._tablename
types = self.adapter.types
for sortable, field in enumerate(table, start=1):
if self.db._ignore_field_case:
field_name = field.name.lower()
else:
field_name = field.name
field_type = field.type
if isinstance(field_type, SQLCustomType):
ftype = field_type.native or field_type.type
elif field_type.startswith(("reference", "big-reference")):
if field_type.startswith("reference"):
referenced = field_type[10:].strip()
type_name = "reference"
else:
referenced = field_type[14:].strip()
type_name = "big-reference"
if referenced == ".":
referenced = tablename
constraint_name = self.dialect.constraint_name(
table._raw_rname, field._raw_rname
)
# if not '.' in referenced \
# and referenced != tablename \
# and hasattr(table,'_primarykey'):
# ftype = types['integer']
# else:
try:
rtable = db[referenced]
rfield = rtable._id
rfieldname = rfield.name
rtablename = referenced
except (KeyError, ValueError, AttributeError) as e:
self.db.logger.debug("Error: %s" % e)
try:
rtablename, rfieldname = referenced.split(".")
rtable = db[rtablename]
rfield = rtable[rfieldname]
except Exception as e:
self.db.logger.debug("Error: %s" % e)
raise KeyError(
"Cannot resolve reference %s in %s definition"
% (referenced, table._tablename)
)
# must be PK reference or unique
if (
not rfield.type.startswith(("reference", "big-reference"))
and getattr(rtable, "_primarykey", None)
and rfieldname in rtable._primarykey
or rfield.unique
):
ftype = types[rfield.type[:9]] % dict(length=rfield.length)
# multicolumn primary key reference?
if not rfield.unique and len(rtable._primarykey) > 1:
# then it has to be a table level FK
if rtablename not in TFK:
TFK[rtablename] = {}
TFK[rtablename][rfieldname] = field_name
else:
fk = rtable._rname + " (" + rfield._rname + ")"
ftype = ftype + types["reference FK"] % dict(
# should be quoted
constraint_name=constraint_name,
foreign_key=fk,
table_name=table._rname,
field_name=field._rname,
on_delete_action=field.ondelete,
)
else:
# make a guess here for circular references
if referenced in db:
id_fieldname = db[referenced]._id._rname
elif referenced == tablename:
id_fieldname = table._id._rname
else: # make a guess
id_fieldname = self.dialect.quote("id")
# gotcha: the referenced table must be defined before
# the referencing one to be able to create the table
# Also if it's not recommended, we can still support
# references to tablenames without rname to make
# migrations and model relationship work also if tables
# are not defined in order
if referenced == tablename:
real_referenced = db[referenced]._rname
else:
real_referenced = (
referenced in db and db[referenced]._rname or referenced
)
rfield = db[referenced]._id
ftype_info = dict(
index_name=self.dialect.quote(field._raw_rname + "__idx"),
field_name=field._rname,
constraint_name=self.dialect.quote(constraint_name),
foreign_key="%s (%s)" % (real_referenced, rfield._rname),
on_delete_action=field.ondelete,
)
ftype_info["null"] = (
" NOT NULL" if field.notnull else self.dialect.allow_null
)
ftype_info["unique"] = " UNIQUE" if field.unique else ""
ftype = types[type_name] % ftype_info
elif field_type.startswith("list:reference"):
ftype = types[field_type[:14]]
elif field_type.startswith("decimal"):
precision, scale = map(int, field_type[8:-1].split(","))
ftype = types[field_type[:7]] % dict(precision=precision, scale=scale)
elif field_type.startswith("geo"):
if not hasattr(self.adapter, "srid"):
raise RuntimeError("Adapter does not support geometry")
srid = self.adapter.srid
geotype, parms = field_type[:-1].split("(")
if geotype not in types:
raise SyntaxError(
"Field: unknown field type: %s for %s"
% (field_type, field_name)
)
ftype = types[geotype]
if self.dbengine == "postgres" and geotype == "geometry":
if self.db._ignore_field_case is True:
field_name = field_name.lower()
# parameters: schema, srid, dimension
dimension = 2 # GIS.dimension ???
parms = parms.split(",")
if len(parms) == 3:
schema, srid, dimension = parms
elif len(parms) == 2:
schema, srid = parms
else:
schema = parms[0]
ftype = (
"SELECT AddGeometryColumn ('%%(schema)s', '%%(tablename)s', '%%(fieldname)s', %%(srid)s, '%s', %%(dimension)s);"
% types[geotype]
)
ftype = ftype % dict(
schema=schema,
tablename=table._raw_rname,
fieldname=field._raw_rname,
srid=srid,
dimension=dimension,
)
postcreation_fields.append(ftype)
elif field_type not in types:
raise SyntaxError(
"Field: unknown field type: %s for %s" % (field_type, field_name)
)
else:
ftype = types[field_type] % {"length": field.length}
if not field_type.startswith(("id", "reference", "big-reference")):
if field.notnull:
ftype += " NOT NULL"
else:
ftype += self.dialect.allow_null
if field.unique:
ftype += " UNIQUE"
if field.custom_qualifier:
ftype += " %s" % field.custom_qualifier
# add to list of fields
sql_fields[field_name] = dict(
length=field.length,
unique=field.unique,
notnull=field.notnull,
sortable=sortable,
type=str(field_type),
sql=ftype,
rname=field._rname,
raw_rname=field._raw_rname,
)
if field.notnull and field.default is not None:
# Caveat: sql_fields and sql_fields_aux
# differ for default values.
# sql_fields is used to trigger migrations and sql_fields_aux
# is used for create tables.
# The reason is that we do not want to trigger
# a migration simply because a default value changes.
not_null = self.dialect.not_null(field.default, field_type)
ftype = ftype.replace("NOT NULL", not_null)
sql_fields_aux[field_name] = dict(sql=ftype)
# Postgres - PostGIS:
# geometry fields are added after the table has been created, not now
if not (self.dbengine == "postgres" and field_type.startswith("geom")):
fields.append("%s %s" % (field._rname, ftype))
other = ";"
# backend-specific extensions to fields
if self.dbengine == "mysql":
if not hasattr(table, "_primarykey"):
fields.append("PRIMARY KEY (%s)" % (table._id._rname))
engine = self.adapter.adapter_args.get("engine", "InnoDB")
other = " ENGINE=%s CHARACTER SET utf8;" % engine
fields = ",\n ".join(fields)
for rtablename in TFK:
rtable = db[rtablename]
rfields = TFK[rtablename]
pkeys = [rtable[pk]._rname for pk in rtable._primarykey]
fk_fields = [table[rfields[k]] for k in rtable._primarykey]
fkeys = [f._rname for f in fk_fields]
constraint_name = self.dialect.constraint_name(
table._raw_rname, "_".join(f._raw_rname for f in fk_fields)
)
on_delete = list(set(f.ondelete for f in fk_fields))
if len(on_delete) > 1:
raise SyntaxError(
"Table %s has incompatible ON DELETE actions in multi-field foreign key."
% table._dalname
)
fields = (
fields
+ ",\n "
+ types["reference TFK"]
% dict(
constraint_name=constraint_name,
table_name=table._rname,
field_name=", ".join(fkeys),
foreign_table=rtable._rname,
foreign_key=", ".join(pkeys),
on_delete_action=on_delete[0],
)
)
if getattr(table, "_primarykey", None):
query = "CREATE TABLE %s(\n %s,\n %s) %s" % (
table._rname,
fields,
self.dialect.primary_key(
", ".join([table[pk]._rname for pk in table._primarykey])
),
other,
)
else:
query = "CREATE TABLE %s(\n %s\n)%s" % (table._rname, fields, other)
uri = self.adapter.uri
if uri.startswith("sqlite:///") or uri.startswith("spatialite:///"):
if PY2:
path_encoding = (
sys.getfilesystemencoding()
or locale.getdefaultlocale()[1]
or "utf8"
)
dbpath = uri[9 : uri.rfind("/")].decode("utf8").encode(path_encoding)
else:
dbpath = uri[9 : uri.rfind("/")]
else:
dbpath = self.adapter.folder
if not migrate:
return query
elif uri.startswith("sqlite:memory") or uri.startswith("spatialite:memory"):
table._dbt = None
elif isinstance(migrate, string_types):
table._dbt = pjoin(dbpath, migrate)
else:
table._dbt = pjoin(dbpath, "%s_%s.table" % (db._uri_hash, tablename))
if not table._dbt or not self.file_exists(table._dbt):
if table._dbt:
self.log(
"timestamp: %s\n%s\n"
% (datetime.datetime.today().isoformat(), query),
table,
)
if not fake_migrate:
self.adapter.create_sequence_and_triggers(query, table)
db.commit()
# Postgres geom fields are added now,
# after the table has been created
for query in postcreation_fields:
self.adapter.execute(query)
db.commit()
if table._dbt:
tfile = self.file_open(table._dbt, "wb")
pickle.dump(sql_fields, tfile)
self.file_close(tfile)
if fake_migrate:
self.log("faked!\n", table)
else:
self.log("success!\n", table)
else:
tfile = self.file_open(table._dbt, "rb")
try:
sql_fields_old = pickle.load(tfile)
except EOFError:
self.file_close(tfile)
raise RuntimeError("File %s appears corrupted" % table._dbt)
self.file_close(tfile)
# add missing rnames
for key, item in sql_fields_old.items():
tmp = sql_fields.get(key)
if tmp:
item.setdefault("rname", tmp["rname"])
item.setdefault("raw_rname", tmp["raw_rname"])
else:
item.setdefault("rname", self.dialect.quote(key))
item.setdefault("raw_rname", key)
if sql_fields != sql_fields_old:
self.migrate_table(
table,
sql_fields,
sql_fields_old,
sql_fields_aux,
None,
fake_migrate=fake_migrate,
)
return query
def _fix(self, item):
k, v = item
if not isinstance(v, dict):
v = dict(type="unknown", sql=v)
if self.db._ignore_field_case is not True:
return k, v
return k.lower(), v
def migrate_table(
self,
table,
sql_fields,
sql_fields_old,
sql_fields_aux,
logfile,
fake_migrate=False,
):
# logfile is deprecated (moved to adapter.log method)
db = table._db
db._migrated.append(table._tablename)
tablename = table._tablename
if self.dbengine in ("firebird",):
drop_expr = "ALTER TABLE %s DROP %s;"
else:
drop_expr = "ALTER TABLE %s DROP COLUMN %s;"
field_types = dict(
(x.lower(), table[x].type) for x in sql_fields.keys() if x in table
)
# make sure all field names are lower case to avoid
# migrations because of case change
sql_fields = dict(map(self._fix, iteritems(sql_fields)))
sql_fields_old = dict(map(self._fix, iteritems(sql_fields_old)))
sql_fields_aux = dict(map(self._fix, iteritems(sql_fields_aux)))
if db._debug:
db.logger.debug("migrating %s to %s" % (sql_fields_old, sql_fields))
keys = list(sql_fields.keys())
for key in sql_fields_old:
if key not in keys:
keys.append(key)
new_add = self.dialect.concat_add(table._rname)
metadata_change = False
sql_fields_current = copy.copy(sql_fields_old)
for key in keys:
query = None
if key not in sql_fields_old:
sql_fields_current[key] = sql_fields[key]
if self.dbengine in ("postgres",) and sql_fields[key][
"type"
].startswith("geometry"):
# 'sql' == ftype in sql
query = [sql_fields[key]["sql"]]
else:
query = [
"ALTER TABLE %s ADD %s %s;"
% (
table._rname,
sql_fields[key]["rname"],
sql_fields_aux[key]["sql"].replace(", ", new_add),
)
]
metadata_change = True
elif self.dbengine in ("sqlite", "spatialite"):
if key in sql_fields:
sql_fields_current[key] = sql_fields[key]
# Field rname has changes, add new column
if (
sql_fields[key]["raw_rname"].lower()
!= sql_fields_old[key]["raw_rname"].lower()
):
tt = sql_fields_aux[key]["sql"].replace(", ", new_add)
query = [
"ALTER TABLE %s ADD %s %s;"
% (table._rname, sql_fields[key]["rname"], tt),
"UPDATE %s SET %s=%s;"
% (
table._rname,
sql_fields[key]["rname"],
sql_fields_old[key]["rname"],
),
]
metadata_change = True
elif key not in sql_fields:
del sql_fields_current[key]
ftype = sql_fields_old[key]["type"]
if self.dbengine == "postgres" and ftype.startswith("geometry"):
geotype, parms = ftype[:-1].split("(")
schema = parms.split(",")[0]
query = [
"SELECT DropGeometryColumn ('%(schema)s', \
'%(table)s', '%(field)s');"
% dict(
schema=schema,
table=table._raw_rname,
field=sql_fields_old[key]["raw_rname"],
)
]
else:
query = [drop_expr % (table._rname, sql_fields_old[key]["rname"])]
metadata_change = True
# The field has a new rname, temp field is not needed
elif (
sql_fields[key]["raw_rname"].lower()
!= sql_fields_old[key]["raw_rname"].lower()
):
sql_fields_current[key] = sql_fields[key]
tt = sql_fields_aux[key]["sql"].replace(", ", new_add)
query = [
"ALTER TABLE %s ADD %s %s;"
% (table._rname, sql_fields[key]["rname"], tt),
"UPDATE %s SET %s=%s;"
% (
table._rname,
sql_fields[key]["rname"],
sql_fields_old[key]["rname"],
),
drop_expr % (table._rname, sql_fields_old[key]["rname"]),
]
metadata_change = True
elif (
sql_fields[key]["sql"] != sql_fields_old[key]["sql"]
and not isinstance(field_types.get(key), SQLCustomType)
and not sql_fields[key]["type"].startswith("reference")
and not sql_fields[key]["type"].startswith("double")
and not sql_fields[key]["type"].startswith("id")
):
sql_fields_current[key] = sql_fields[key]
tt = sql_fields_aux[key]["sql"].replace(", ", new_add)
key_tmp = self.dialect.quote(key + "__tmp")
query = [
"ALTER TABLE %s ADD %s %s;" % (table._rname, key_tmp, tt),
"UPDATE %s SET %s=%s;"
% (table._rname, key_tmp, sql_fields_old[key]["rname"]),
drop_expr % (table._rname, sql_fields_old[key]["rname"]),
"ALTER TABLE %s ADD %s %s;"
% (table._rname, sql_fields[key]["rname"], tt),
"UPDATE %s SET %s=%s;"
% (table._rname, sql_fields[key]["rname"], key_tmp),
drop_expr % (table._rname, key_tmp),
]
metadata_change = True
elif sql_fields[key] != sql_fields_old[key]:
sql_fields_current[key] = sql_fields[key]
metadata_change = True
if query:
self.log(
"timestamp: %s\n" % datetime.datetime.today().isoformat(), table
)
for sub_query in query:
self.log(sub_query + "\n", table)
if fake_migrate:
if db._adapter.commit_on_alter_table:
self.save_dbt(table, sql_fields_current)
self.log("faked!\n", table)
else:
self.adapter.execute(sub_query)
# Caveat: mysql, oracle and firebird
# do not allow multiple alter table
# in one transaction so we must commit
# partial transactions and
# update table._dbt after alter table.
if db._adapter.commit_on_alter_table:
db.commit()
self.save_dbt(table, sql_fields_current)
self.log("success!\n", table)
elif metadata_change:
self.save_dbt(table, sql_fields_current)
if metadata_change and not (query and db._adapter.commit_on_alter_table):
db.commit()
self.save_dbt(table, sql_fields_current)
self.log("success!\n", table)
def save_dbt(self, table, sql_fields_current):
tfile = self.file_open(table._dbt, "wb")
pickle.dump(sql_fields_current, tfile)
self.file_close(tfile)
def log(self, message, table=None):
isabs = None
logfilename = self.adapter.adapter_args.get("logfile", "sql.log")
writelog = bool(logfilename)
if writelog:
isabs = os.path.isabs(logfilename)
if table and table._dbt and writelog and self.adapter.folder:
if isabs:
table._loggername = logfilename
else:
table._loggername = pjoin(self.adapter.folder, logfilename)
logfile = self.file_open(table._loggername, "ab")
logfile.write(to_bytes(message))
self.file_close(logfile)
@staticmethod
def file_open(filename, mode="rb", lock=True):
# to be used ONLY for files that on GAE may not be on filesystem
if lock:
fileobj = portalocker.LockedFile(filename, mode)
else:
fileobj = open(filename, mode)
return fileobj
@staticmethod
def file_close(fileobj):
# to be used ONLY for files that on GAE may not be on filesystem
if fileobj:
fileobj.close()
@staticmethod
def file_delete(filename):
os.unlink(filename)
@staticmethod
def file_exists(filename):
# to be used ONLY for files that on GAE may not be on filesystem
return exists(filename)
class InDBMigrator(Migrator):
def file_exists(self, filename):
return DatabaseStoredFile.exists(self.db, filename)
def file_open(self, filename, mode="rb", lock=True):
return DatabaseStoredFile(self.db, filename, mode)
@staticmethod
def file_close(fileobj):
fileobj.close_connection()
def file_delete(self, filename):
query = "DELETE FROM web2py_filesystem WHERE path='%s'" % filename
self.db.executesql(query)
self.db.commit()