forked from smurfix/sqlmix
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsql_diff.g
2025 lines (1758 loc) · 50.6 KB
/
sql_diff.g
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
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright (C) 2008-2011 Matthias Urlichs <[email protected]>
#
# This program may be distributed under the terms of the GNU GPLv3.
#
## This file is formatted with tabs.
## Do NOT introduce leading spaces.
"""\
Transform SQL tables.
This tool analyzes SQL table definitions+contents and emits mostly-minimal
statements to transform one into the other.
For content analysis, an ID column is mandatory; a timestamp column is
strongly recommended.
This code needs to be preprocessed with yapps2 (a Python parser generator).
Specifically, with version 2.1.1 from Debian/Ubuntu, because
that contains a couple of crucial enhancements.
"""
import sys, os, copy, time, array
import MySQLdb.connections as mc
from traceback import format_exception_only
class DupTableError(ReferenceError):
pass
class DupFieldError(ReferenceError):
pass
class DupKeyError(ReferenceError):
pass
class NoSuchTableError(IndexError):
pass
verbose=1
_debug=None
keyseq = 0
had_output = 0
r="\r"+(" "*70)+"\r"
INTs = ("int","smallint","bigint","tinyint","mediumint")
FLOATs = ("float","double")
# Update-Trace
cnt=0
cntt = ""
ltm=int(time.time())-1
def bq(n):
"""Backquote table/field names"""
# We might be nice for readability and only quote keywords.
# However, right now we don't bother.
return '`'+n+'`'
def sqlquote(s):
if not isinstance(s,basestring):
s = str(s)
def _prep(p):
if p == "\0": return "\\0"
else: return "\\"+p
s = re.sub("(\\'\0)",_prep,s)
return "'"+s+"'"
def print_query(d):
res = ""
resl={}
for fd,val in d.items():
if res != "": res += " and "
res += bq(fd)+"="
if val is None:
res += "NULL"
else:
res += '${%s}' % (fd,)
resl[fd]=val
return (res,resl)
def print_update(d):
res = ""
resl={"_debug":_debug}
for fd,val in d.items():
if res: res += ", "
res += bq(fd)+"="
if val is None:
res += "NULL"
else:
if not isinstance(val,array.array):
val=str(val)
res += '${%s_}' % (fd,)
resl[fd+'_']=val
return (res,resl)
def print_insert(d):
res = ""
resg = ""
resl={"_debug":_debug}
for fd,val in d.items():
if res:
res += ", "
resg += ", "
res += bq(fd)
if val is None:
resg += "NULL"
else:
if not isinstance(val,array.array):
#try: val=int(val)
#except OverflowError: val=float(val)
#except ValueError: pass
#except TypeError: val=str(val)
val=str(val)
resg += '${%s_}' % (fd,)
resl[fd+'_']=val
return ('(%s) VALUES (%s)' % (res,resg), resl)
def posval2dict(fieldpos,ar,br=None):
for fd,idx in fieldpos.items():
val = ar[idx]
if br:
if val == br[idx]: continue
d[fd] = val
return d
def trace(*x):
if not verbose: return
print >>sys.stderr, r+" "+" ".join(map(str,x))+" \r",
sys.stderr.flush()
def tdump(n):
if n.__class__ == ().__class__:
r=""
for f in n: r += "'%s', " % (f,)
return "ENUM ("+r[:-2]+")"
else:
return n
class Uncommon(object): pass
def common(d1,*d):
"""
Return a dict with only those keys/values common to all.
The first argument needs to be a dict, others can also be lists.
If a list/tuple is passed, filter by keys.
>>> common({1:2,3:4,5:6,7:8},{1:3,5:6,7:8,9:10},[1,3,5,9])
{5:6}
"""
d1orig = d1
for d2 in d:
dn = {}
if isinstance(d2,(list,tuple)):
for k in d2:
try:
dn[k] = d1[k]
except KeyError:
pass # just ignore
else:
for k,v in d1.items():
if d2.get(k,Uncommon) == v:
dn[k]=v
d1 = dn
return d1
def notcommon(d1,*d):
"""
Return a dict with only those keys/values in the first dict that are
different from (or not present in) the rest.
>>> common({1:2,3:4,5:6,7:8},{1:3,5:6,7:8,9:10})
{1:2}
"""
res = dict(d1)
for d2 in d:
if isinstance(d2,(list,tuple)):
for k in d2:
try:
del res[k]
except KeyError:
pass # just ignore
else:
for k,v in res.items():
if d2.get(k,Uncommon) == v:
del res[k]
return res
def print_fkey_check(what=0):
global had_output
if had_output == what:
had_output=1
print "SET FOREIGN_KEY_CHECKS = ",what,";"
class curtime: pass
class NotGiven: pass
def valprint(x):
if x is None: return "NULL"
if x is curtime: return "CURRENT_TIMESTAMP"
return "'"+str(x)+"'" ## TODO: quote correctly
class Field(object):
"""Declare a table's column"""
def __init__(self,table,name,after=True):
self.name=name
self.old_name=name
self.table=table
self.tname=None
self.next_col=None
self.prev_col=None
self.nullable=True
self.len=None
self.len2=None
self.defval=NotGiven
self.updval=NotGiven
self.autoinc=False
self.unsigned=False
self.charset=None
self.collation=None
self._chained=False
self._tagged=False
table._new_field(self,after=after)
def clone(self,table):
f = Field(table,self.name)
f.tname=self.tname
f.nullable=self.nullable
f.len=self.len
f.len2=self.len2
f.defval=self.defval
f.updval=self.updval
f.autoinc=self.autoinc
f.unsigned=self.unsigned
f.charset=self.charset
f.collation=self.collation
table._new_field(f)
def create_done(self):
"""Fill in some defaults"""
if self.tname == 'bool': # mysql specific
self.tname = 'tinyint'
self.len = 1
if self.defval is NotGiven:
if self.autoinc or self.nullable:
self.defval = None
elif self.tname in INTs or self.tname in FLOATs:
self.defval = "0"
elif self.tname == "datetime":
self.defval = "0000-00-00 00:00:00"
else:
self.defval = ""
if self.len is None:
if self.tname == "char":
self.len = 1
elif self.tname == "tinyint":
self.len = 4
elif self.tname == "smallint":
self.len = 6
elif self.tname == "mediumint":
self.len = 9
elif self.tname == "int":
self.len = 11
elif self.tname == "bigint":
self.len = 20
elif self.tname in INTs:
raise RuntimeError("INT problem",self.tname)
if self.unsigned and self.len and self.len != 20:
self.len -= 1
if self.tname == "timestamp" and self.defval is curtime \
and not self.nullable:
self.nullable = True
if self.tname in INTs \
and self.autoinc and self.nullable:
self.nullable = False
def drop(self):
self.table._del_field(self)
def dump(s,*f,**k):
"""Dump myself, either completely or as a diff to column 'oc'"""
a,b=s.dump2(*f,**k)
return a
def is_text_column(self):
return (self.tname == "char" or self.tname == "varchar" or self.tname.endswith("text"))
def dump2(self,oc=None,in_create=False,skip_flags=""):
"""Dump myself, also return changes"""
if not self.charset: self.charset=self.table.charset
if not self.collation: self.collation=self.table.collation
if oc:
if not oc.charset: oc.charset=oc.table.charset
if not oc.collation: oc.collation=oc.table.collation
if not in_create:
if not oc:
r="ADD COLUMN "
elif not self._diffs(oc,skip_flags=skip_flags):
return None,None
elif self.name != oc.name:
r="CHANGE COLUMN `%s` " % (oc.name,)
else: # MySQL Special ??
r="MODIFY COLUMN "
else:
r=""
rp=[]
r += "`%s` %s" % (self.name,tdump(self.tname))
if self.len is not None:
if self.len2 is not None:
r += "(%d,%d)" % (self.len,self.len2)
else:
r += "(%d)" % (self.len,)
if oc:
if self.tname != oc.tname: rp.append(oc.tname)
if self.len != oc.len or self.len2 != oc.len2:
if oc.len is not None: rp.append("len=%d"%(oc.len,))
else: rp.append("!len")
if self.unsigned:
r += " UNSIGNED"
if oc:
if self.unsigned != oc.unsigned:
if oc.unsigned: rp.append("unsigned")
else: rp.append("signed")
do_cs=False
if self.is_text_column():
if 'c' not in skip_flags and self.charset:
if oc and oc.charset == "utf8":
charset = oc.charset
else:
charset = self.charset
if charset != self.table.charset or charset != self.charset or (oc and (charset != oc.charset or charset != oc.table.charset)):
r += " CHARACTER SET %s" % (charset,)
do_cs=True
if 'c' not in skip_flags and oc:
if self.charset != oc.charset:
rp.append("charset %s/%s"%(oc.charset,self.charset))
if 'c' not in skip_flags and self.collation and not do_cs:
if oc and oc.charset == "utf8" and oc.charset != self.charset:
collation = oc.collation
else:
collation = self.collation
r += " COLLATE %s" % (collation,)
if 'c' not in skip_flags and oc and not do_cs:
if oc.collation and (self.collation != oc.collation):
rp.append("collate %s/%s"%(oc.collation,self.collation))
if self.nullable:
if not in_create:
r += " NULL" # ist eh Default
else:
r += " NOT NULL"
if oc:
if self.nullable != oc.nullable:
if oc.nullable: rp.append("null")
else: rp.append("!null")
if self.autoinc:
r += " AUTO_INCREMENT"
if oc:
if self.autoinc != oc.autoinc:
if oc.autoinc: rp.append("autoinc")
else: rp.append("!autoinc")
if self.defval is not NotGiven:
r += " DEFAULT " + valprint(self.defval)
if oc:
if self.defval != oc.defval:
if oc.defval != NotGiven: rp.append("default "+valprint(oc.defval))
else: rp.append("!default")
if self.updval is not NotGiven:
r += " ON UPDATE " + valprint(self.updval)
if oc:
if self.updval != oc.updval:
if oc.updval != NotGiven: rp.append("updefault "+valprint(oc.updval))
else: rp.append("!updefault")
if 'a' not in skip_flags and oc and self.prev_col != oc.prev_col and not in_create:
if self.prev_col:
r += " AFTER %s" % (self.prev_col.name,)
else:
r += " FIRST"
if 'a' not in skip_flags and oc:
if self.prev_col != oc.prev_col:
if oc.prev_col: rp.append("after "+oc.prev_col.name)
else: rp.append("first")
return r,rp
def _diffs(s,o,skip_flags=""):
"""return TRUE if s and o differ"""
if 'a' not in skip_flags:
if s.prev_col: pa=s.prev_col.name
else: pa=None
if o.prev_col: pb=o.prev_col.name
else: pb=None
if pa != pb: return True
if s.name != o.name: return True
if s.tname != o.tname: return True
if s.len != o.len or s.len2 != o.len2:
if s.tname != "timestamp" or (s.len is not None and o.len is not None):
return True
if s.autoinc != o.autoinc: return True
if s.unsigned != o.unsigned: return True
if s.nullable != o.nullable: return True
if s.is_text_column():
if 'c' not in skip_flags and s.charset != o.charset and (s.charset == "utf8" or o.charset != "utf8"):
return True
if 'c' not in skip_flags and s.collation != o.collation:
if o.collation is not None and s.collation is not None and s.collation != o.collation and (s.charset == "utf8" or o.charset != "utf8"):
return True
if s.defval != o.defval:
if s.tname != "timestamp" or (s.defval is not NotGiven and s.defval is not curtime) or (o.defval is not NotGiven and o.defval is not curtime):
return True
if s.updval != o.updval:
if s.tname != "timestamp" or (s.updval is not NotGiven and s.updval is not curtime) or (o.updval is not NotGiven and o.updval is not curtime):
return True
# ignore: next_col
return False
def __hash__(self): return self.old_name.__hash__() # is immutable
def __str__(self): return "<%s:%s %s>" % (self.name,self.tname, self.table)
def __repr__(self): return "<%s.%s>" % (self.table.name,self.name)
def set_after(self,after=True,oc=None):
self.table._del_field(self)
self.table._new_field(self,after=after)
def __eq__(self,other):
if other is None: return False
return self.name.__eq__(other.name)
def __ne__(self,other):
if other is None: return True
return self.name.__ne__(other.name)
#def __cmp__(self,other): return self.name.__cmp__(other.name)
class Key(object):
def __init__(self,table,name,ktype,fields):
self.table=table
self.name=name
self.ktype=ktype
self.fields=fields
self.id = (ktype,fields)
def pref(self, pref_seq=False, pref_text=True):
"""Pref value for this key"""
pr=1000
if len(self.fields)==1 and self.ktype=="U":
k = self.fields[0][0]
if k.autoinc and pref_seq:
pr *= 10
if not k.autoinc and not pref_seq:
pr *= 10
if self.name is None: # primary key
pr += 20
for f in self.fields:
f = f[0]
if f.name in ("id","lfd"):
pr += 50
if f.tname in INTs:
if not pref_text:
pr *= 5
else:
if pref_text:
pr *= 5
if self.ktype!="U":
pr /= 10
return pr/len(self.fields)
def dump(self,ok=None,in_create=False,skip_flags=""):
"""Dump myself, either completely or as a diff to key 'ok'"""
if not in_create:
if not ok:
r="ADD"
elif not self._diffs(ok,skip_flags=skip_flags):
return None
else:
r=""
if ok.name is None:
r += "DROP PRIMARY KEY,\n "
else:
r += "DROP KEY `%s`,\n " % (ok.name,)
r+="ADD"
else:
r=""
if self.name is None:
r += " PRIMARY KEY"
else:
if self.ktype == "U": r+=" UNIQUE"
r += " KEY `%s`" % (self.name,)
r += "("
ra=""
for f in self.fields:
r += ra+"`"+f[0].name+"`"
if f[1]:
r += "("+str(f[1])+")"
ra=","
r += ")"
return r
def _diffs(self,ok,skip_flags=""):
if self.fields != ok.fields: return True
if 'i' not in skip_flags and self.name != ok.name: return True
if self.ktype != ok.ktype: return True
return False
def __str__(self):
n=self.name
if not n: n="PRIMARY"
return "<%s %s %s>" % (self.ktype,n,",".join(map(str,self.fields)))
def __repr__(self):
n=self.name
if not n: n="PRIMARY"
return "<%s %s.%s %s>" % (self.ktype,self.table.name,n,self.fields)
class FKey(object):
def __init__(self,name,table,fields,rtable,rfields, opt):
self.name=name
self.table=table
self.rtable=rtable
self.fields=fields
self.rfields=rfields
self.opt=opt
def dump(self,ok=None,in_create=False,skip_flags=""):
"""Dump myself, either completely or as a diff to key 'ok'"""
if not in_create:
if not ok:
r = "ADD"
elif not self._diffs(ok,skip_flags=skip_flags):
return None
else:
r = "ADD"
else:
r=""
r += " CONSTRAINT `%s` FOREIGN KEY (" % (self.name,)
ra=""
for f in self.fields:
r += ra+"`"+f.name+"`"
ra=","
r += ") REFERENCES `%s` (" % (self.rtable,)
ra=""
for f in self.rfields:
r += ra+"`"+f+"`"
ra=","
r += ")"
for a,b in self.opt.items():
r += " ON %s %s" % (a.upper(),b)
return r
def _diffs(self,ok,skip_flags=""):
if 'i' not in skip_flags and self.name != ok.name:
print "#FK Name:",self.name,ok.name
return True
if self.rtable != ok.rtable:
print "#FK",self.name,"rtable:",self.rtable,ok.rtable
return True
fs=[f.name for f in self.fields]
ofs=[f.name for f in ok.fields]
if fs != ofs:
print "#FK",self.name,"fields:",fs,ofs
return True
if self.rfields != ok.rfields:
print "#FK",self.name,"rfields:",self.rfields,ok.rfields
return True
for a,b in self.opt.items():
try: c=ok.opt[a]
except KeyError:
print "#FK",self.name,"k_opt",a,"??"
return True
else:
if b != c:
print "#FK",self.name,"k_opt",a,b,c
return True
for a,b in ok.opt.items():
try: c=self.opt[a]
except KeyError:
print "#FK",self.name,"ok_opt",a,"??"
return True
else:
if b != c:
print "#FK",self.name,"ok_opt",a,b,c
return True
return False
def __str__(self): return "<%s %s>" % \
(",".join([f.name for f in self.fields]),
",".join(self.rfields))
def __repr__(self): return "<%s.%s %s.%s>" % \
(self.table, ",".join([f.name for f in self.fields]),
self.rtable, ",".join(self.rfields))
class Table(object):
"""Declare a table"""
def __init__(self,name,db=None):
self.name=name
self.engine=None
self.charset="utf8"
self.collation="utf8_general_ci"
self.packing=None
self.maxrows=None
self.col={}
self.key={}
self.knames={}
self.dupkeys=[]
self.fkey={}
self.fknames={}
self.dupfkeys=[]
self.contents={}
if db:
db.tables[name]=self
self.tables = db.tables
self.first_col=None
self.last_col=None
self.db = db
def get(self,d):
"""Retrieve a dataset that has the same key as d"""
for k in self.possible_keys(d):
if k in self.contents:
return self.contents[k]
return None
def pop(self,d):
"""Retrieve a dataset that has the same key as d, and delete it"""
for k in self.possible_keys(d):
if k in self.contents:
dd = self.contents[k]
for k in self.possible_keys(dd):
if k in self.contents:
del self.contents[k]
return dd
return None
def update(self, d):
#from pprint import pprint
"""Insert a (possibly incomplete) dataset into this table"""
#print "UPDATE",self.name,"";pprint(self.contents)
#print "WITH","",;pprint(d)
dd = None
for k in self.possible_keys(d):
if k in self.contents:
dd = self.contents[k]
dd.update(d)
break
if not dd:
# not found ⇒ add (a copy)
dd = dict(d)
for k in self.possible_keys(dd):
self.contents[k] = dd
#print "GETS","",;pprint(self.contents)
def possible_keys(self, d):
"""Get all possible keys for a dataset"""
for bk in self.best_keys(False,True):
try:
yield tuple((bk,)+tuple( d[f[0].name] for f in bk.fields ))
except KeyError:
pass
def possible_key(self, d):
"""Return the best-possible key for a dataset"""
return self.possible_keys(d).next()
def clone(self,db):
t = Table(self.name)
t.engine = self.engine
t.charset = self.charset
t.collation = self.collation
t.packing = self.packing
t.maxrows = self.maxrows
f = self.first_col
while f:
f.clone(t)
f = f.next_col
t.key.update(self.key)
t.knames.update(self.knames)
t.dupkeys = self.dupkeys[:]
t.fkey.update(self.fkey)
t.fknames.update(self.fknames)
t.dupfkeys = self.dupfkeys[:]
t.first_col = self.first_col
t.last_col = self.last_col
t.tables = db.tables
t.db = db
return t
def best_keys(self, pref_seq=True, pref_text=True, only_unique = True):
"""Returns all indices on the table, sorted by preference."""
k=self.key.values()
if only_unique:
k = [x for x in k if x.ktype == 'U']
k.sort(lambda a,b: b.pref(pref_seq,pref_text)-a.pref(pref_seq,pref_text))
return k
def timestamp(self):
# Return the column with tiimestamp
for c in self.col.itervalues(): # new MySQL
if c.updval == curtime:
return c
for c in self.col.itervalues(): # one common possibility
if c.tname == "timestamp":
return c
for c in self.col.itervalues(): # another common possibility
if c.name == "tstamp":
return c
return None
def new_fkey(self,name,fl1,rtable,fl2,opt):
if name in self.fknames:
raise DupKeyError(name)
fl1=tuple(fl1)
fl2=tuple(fl2)
try:
k=self.fkey[fl1]
except KeyError:
k=FKey(name,self,fl1,rtable,fl2,opt)
self.fkey[fl1]=k
self.fknames[name]=k
try: self.dupfkeys = self.dupfkeys.remove(name)
except ValueError: pass
else:
if k.name is None: repl=False
elif name is None: repl=True
else: repl=False
if repl: # alten Key rauswerfen
self.dupfkeys.append(k.name)
del self.fknames[k.name]
k.name=name
self.fknames[name]=k
else:
if k.name < name:
self.dupfkeys.append(name)
else:
self.dupfkeys.append(k.name)
k.name = name
def del_fkey(self,name):
try:
k=self.fknames.pop(name)
except KeyError:
self.dupfkeys=self.dupfkeys.remove(name)
else:
del self.fkey[k.fields]
def new_key(self,name,ktype,fields):
if name == "":
global keyseq
keyseq += 1
name = "x_" + str(keyseq)
if name in self.knames:
raise DupKeyError(name)
fields=tuple(fields)
k=Key(self,name,ktype,fields)
try:
k=self.key[k.id]
except KeyError:
self.key[k.id]=k
self.knames[name]=k
try: self.dupkeys = self.dupkeys.remove(name)
except ValueError: pass
else:
if k.name is None: repl=False
elif name is None: repl=True
elif ktype != k.ktype: repl=True
else: repl=False
if repl: # kick the old key
self.dupkeys.append(k.name)
del self.knames[k.name]
k.name=name
self.knames[name]=k
else:
if k.name != name: self.dupkeys.append(name)
def del_key(self,name):
try:
k=self.knames.pop(name)
except KeyError:
self.dupkeys=self.dupkeys.remove(name)
else:
del self.key[k.id]
def drop(self):
del self.tables[self.name]
def columns(self):
c=self.first_col
while c:
cn=c.next_col
yield c
c=cn
def new_field(self,name,old_col):
"""add a new field to this table.
(May be a clone of some old field.)"""
if old_col:
if old_col is True:
old_col=name
old_col=self.col[old_col]
after = old_col.prev_col
old_col.drop()
old_col.name=name
old_col._chained=False
self._new_field(old_col,after=after)
return old_col
else:
if name in self.col:
raise DupFieldError(self,name)
return Field(self,name)
def _new_field(self,col,after=True):
if col._chained: return
col._chained=True
self.col[col.name]=col
if after is None:
col.prev_col=None
col.next_col=self.first_col
elif after is True:
col.next_col=None
col.prev_col=self.last_col
else:
col.prev_col=after
col.next_col=after.next_col
if col.prev_col: col.prev_col.next_col = col
else: self.first_col=col
if col.next_col: col.next_col.prev_col = col
else: self.last_col=col
def del_field(self,name):
self.col[name].drop()
def _del_field(self,col):
if self.col[col.name] != col: raise IndexError
if not col._chained: return
col._chained=False
del self.col[col.name]
if col.prev_col: col.prev_col.next_col=col.next_col
else: self.first_col=col.next_col
if col.next_col: col.next_col.prev_col=col.prev_col
else: self.last_col=col.prev_col
def dump(self,skip_flags=""):
r= "CREATE TABLE %s (\n " % (self.name,)
ra=""
for c in self.columns():
r += ra+c.dump(in_create=True,skip_flags=skip_flags)
ra=",\n "
for k in self.key.values():
r += ra+k.dump(in_create=True,skip_flags=skip_flags)
ra=",\n "
for k in self.fkey.values():
r += ra+k.dump(in_create=True,skip_flags=skip_flags)
ra=",\n "
r += ")"
if self.engine:
r += " ENGINE="+self.engine
if 'c' not in skip_flags and self.charset:
r += " CHARACTER SET="+self.charset
if 'c' not in skip_flags and self.collation:
r += " COLLATE="+self.collation
if 'm' not in skip_flags and self.maxrows:
r += " MAX_ROWS="+self.maxrows
if 'p' not in skip_flags and self.packing is not None:
r += " PACK_KEYS="+str(self.packing)
return r
def diff1(s,o,skip_flags=""):
r=""
ra="ALTER TABLE %s\n " % (s.name,)
for on in o.dupkeys:
if on == "":
r += ra+"DROP PRIMARY KEY"
else:
r += ra+"DROP KEY `%s`" % (on,)
ra=",\n "
if 'k' not in skip_flags:
for fk in o.fkey.values():
if fk.name not in s.fknames or s.fknames[fk.name]._diffs(fk,skip_flags=skip_flags):
r += ra+"DROP FOREIGN KEY `%s`" % (fk.name,)
ra=",\n "
if s.engine and s.engine != o.engine:
r += ra+" ENGINE="+s.engine
ra=""
if 'c' not in skip_flags and s.charset and s.charset != o.charset:
r += ra+" CHARACTER SET="+s.charset
ra=""
if 'c' not in skip_flags and o.collation and s.collation and s.collation != o.collation:
r += ra+" COLLATE="+s.collation
ra=""
if 'm' not in skip_flags and s.maxrows and s.maxrows != o.maxrows:
r += ra+" MAX_ROWS="+str(s.maxrows)
ra=""
if 'p' not in skip_flags and s.packing is not None and s.packing != o.packing:
r += ra+" PACK_KEYS="+str(s.packing)
ra=""
return r
def diff2(s,o,skip_flags=""):
r=""
ra="ALTER TABLE %s\n " % (s.name,)
rb=""
dels = []
for k in o.key.values():
if 'i' in skip_flags and k.name is not None:
if k.id in s.key: continue
else:
if k.name in s.knames: continue
r += ra+"DROP "
if k.name is None:
r +="PRIMARY KEY"
else:
r += "KEY `%s`" % (k.name,)
ra=",\n "
rb += "# %s \n" % (k,)
dels.append(k)
for k in dels:
del o.key[k.id]
del o.knames[k.name]
for k in o.key.values():
try:
if 'i' in skip_flags:
ok=s.key[k.id]
else:
ok=s.knames[k.name]
except KeyError:
r += ra+"DROP "
if k.name is None:
r +="PRIMARY KEY"
else:
r += "KEY `%s`" % (k.name,)
else:
continue
# First pass: add new columns
for c in s.columns():
nr=""
try: oc=o.col[c.old_name]
except KeyError:
r += ra+c.dump(skip_flags=skip_flags)
ra=",\n "
# Second pass: modify new columns
for c in s.columns():
nr=""
try: oc=o.col[c.old_name]
except KeyError: continue
else:
nr,onr = c.dump2(oc,skip_flags=skip_flags)
oc._tagged=True
if nr:
r += ra+nr
ra=",\n "
rb += "#%s: %s\n" % (c.name,", ".join(onr))
# Third pass: delete old columns
for c in o.columns():
if not c._tagged:
r += ra+"DROP COLUMN `%s`" % (c.name,)
ra=",\n "
else:
c._tagged=False
# Now fix the indices
for k in s.key.values():
try: