Support latest schema changes.
[lhc/web/wiklou.git] / maintenance / postgres / compare_schemas.pl
1 #!/usr/bin/perl
2
3 ## Rough check that the base and postgres "tables.sql" are in sync
4 ## Should be run from maintenance/postgres
5 ## Checks a few other things as well...
6
7 use strict;
8 use warnings;
9 use Data::Dumper;
10
11 check_includes_dir();
12
13 my @old = ('../tables.sql');
14 my $new = 'tables.sql';
15 my @xfile;
16
17 ## Read in exceptions and other metadata
18 my %ok;
19 while (<DATA>) {
20 next unless /^(\w+)\s*:\s*([^#]+)/;
21 my ($name,$val) = ($1,$2);
22 chomp $val;
23 if ($name eq 'RENAME') {
24 die "Invalid rename\n" unless $val =~ /(\w+)\s+(\w+)/;
25 $ok{OLD}{$1} = $2;
26 $ok{NEW}{$2} = $1;
27 next;
28 }
29 if ($name eq 'XFILE') {
30 push @xfile, $val;
31 next;
32 }
33 for (split /\s+/ => $val) {
34 $ok{$name}{$_} = 0;
35 }
36 }
37
38 my $datatype = join '|' => qw(
39 bool
40 tinyint int bigint real float
41 tinytext mediumtext text char varchar varbinary binary
42 timestamp datetime
43 tinyblob mediumblob blob
44 );
45 $datatype .= q{|ENUM\([\"\w, ]+\)};
46 $datatype = qr{($datatype)};
47
48 my $typeval = qr{(\(\d+\))?};
49
50 my $typeval2 = qr{ signed| unsigned| binary| NOT NULL| NULL| auto_increment| default ['\-\d\w"]+| REFERENCES .+CASCADE};
51
52 my $indextype = join '|' => qw(INDEX KEY FULLTEXT), 'PRIMARY KEY', 'UNIQUE INDEX', 'UNIQUE KEY';
53 $indextype = qr{$indextype};
54
55 my $engine = qr{TYPE|ENGINE};
56
57 my $tabletype = qr{InnoDB|MyISAM|HEAP|HEAP MAX_ROWS=\d+|InnoDB MAX_ROWS=\d+ AVG_ROW_LENGTH=\d+};
58
59 my $charset = qr{utf8|binary};
60
61 open my $newfh, '<', $new or die qq{Could not open $new: $!\n};
62
63
64 my ($table,%old);
65
66 ## Read in the xfiles
67 my %xinfo;
68 for my $xfile (@xfile) {
69 print "Loading $xfile\n";
70 my $info = parse_sql($xfile);
71 for (keys %$info) {
72 $xinfo{$_} = $info->{$_};
73 }
74 }
75
76 for my $oldfile (@old) {
77 print "Loading $oldfile\n";
78 my $info = parse_sql($oldfile);
79 for (keys %xinfo) {
80 $info->{$_} = $xinfo{$_};
81 }
82 $old{$oldfile} = $info;
83 }
84
85 sub parse_sql {
86
87 my $oldfile = shift;
88
89 open my $oldfh, '<', $oldfile or die qq{Could not open $oldfile: $!\n};
90
91 my %info;
92 while (<$oldfh>) {
93 next if /^\s*\-\-/ or /^\s+$/;
94 s/\s*\-\- [\w ]+$//;
95 chomp;
96
97 if (/CREATE\s*TABLE/i) {
98 m{^CREATE TABLE /\*\$wgDBprefix\*/(\w+) \($}
99 or die qq{Invalid CREATE TABLE at line $. of $oldfile\n};
100 $table = $1;
101 $info{$table}{name}=$table;
102 }
103 elsif (m{^\) /\*\$wgDBTableOptions\*/}) {
104 $info{$table}{engine} = 'TYPE';
105 $info{$table}{type} = 'variable';
106 }
107 elsif (/^\) ($engine)=($tabletype);$/) {
108 $info{$table}{engine}=$1;
109 $info{$table}{type}=$2;
110 }
111 elsif (/^\) ($engine)=($tabletype), DEFAULT CHARSET=($charset);$/) {
112 $info{$table}{engine}=$1;
113 $info{$table}{type}=$2;
114 $info{$table}{charset}=$3;
115 }
116 elsif (/^ (\w+) $datatype$typeval$typeval2{0,3},?$/) {
117 $info{$table}{column}{$1} = $2;
118 my $extra = $3 || '';
119 $info{$table}{columnfull}{$1} = "$2$extra";
120 }
121 elsif (/^ ($indextype)(?: (\w+))? \(([\w, \(\)]+)\),?$/) {
122 $info{$table}{lc $1.'_name'} = $2 ? $2 : '';
123 $info{$table}{lc $1.'pk_target'} = $3;
124 }
125 else {
126 die "Cannot parse line $. of $oldfile:\n$_\n";
127 }
128
129 }
130 close $oldfh or die qq{Could not close "$oldfile": $!\n};
131
132 return \%info;
133
134 } ## end of parse_sql
135
136 ## Read in the parser test information
137 my $parsefile = '../parserTests.inc';
138 open my $pfh, '<', $parsefile or die qq{Could not open "$parsefile": $!\n};
139 my $stat = 0;
140 my %ptable;
141 while (<$pfh>) {
142 if (!$stat) {
143 if (/function listTables/) {
144 $stat = 1;
145 }
146 next;
147 }
148 $ptable{$1}=2 while m{'(\w+)'}g;
149 last if /\);/;
150 }
151 close $pfh or die qq{Could not close "$parsefile": $!\n};
152
153 my $OK_NOT_IN_PTABLE = '
154 filearchive
155 logging
156 profiling
157 querycache_info
158 searchindex
159 trackbacks
160 transcache
161 user_newtalk
162 updatelog
163 ';
164
165 ## Make sure all tables in main tables.sql are accounted for int the parsertest.
166 for my $table (sort keys %{$old{'../tables.sql'}}) {
167 $ptable{$table}++;
168 next if $ptable{$table} > 2;
169 next if $OK_NOT_IN_PTABLE =~ /\b$table\b/;
170 print qq{Table "$table" is in the schema, but not used inside of parserTest.inc\n};
171 }
172 ## Any that are used in ptables but no longer exist in the schema?
173 for my $table (sort grep { $ptable{$_} == 2 } keys %ptable) {
174 print qq{Table "$table" ($ptable{$table}) used in parserTest.inc, but not found in schema\n};
175 }
176
177 for my $oldfile (@old) {
178
179 ## Begin non-standard indent
180
181 ## MySQL sanity checks
182 for my $table (sort keys %{$old{$oldfile}}) {
183 my $t = $old{$oldfile}{$table};
184 if (($oldfile =~ /5/ and $t->{engine} ne 'ENGINE')
185 or
186 ($oldfile !~ /5/ and $t->{engine} ne 'TYPE')) {
187 die "Invalid engine for $oldfile: $t->{engine}\n" unless $t->{name} eq 'profiling';
188 }
189 my $charset = $t->{charset} || '';
190 if ($oldfile !~ /binary/ and $charset eq 'binary') {
191 die "Invalid charset for $oldfile: $charset\n";
192 }
193 }
194
195 my $dtype = join '|' => qw(
196 SMALLINT INTEGER BIGINT NUMERIC SERIAL
197 TEXT CHAR VARCHAR
198 BYTEA
199 TIMESTAMPTZ
200 CIDR
201 );
202 $dtype = qr{($dtype)};
203 my %new;
204 my ($infunction,$inview,$inrule,$lastcomma) = (0,0,0,0);
205 seek $newfh, 0, 0;
206 while (<$newfh>) {
207 next if /^\s*\-\-/ or /^\s*$/;
208 s/\s*\-\- [\w ']+$//;
209 next if /^BEGIN;/ or /^SET / or /^COMMIT;/;
210 next if /^CREATE SEQUENCE/;
211 next if /^CREATE(?: UNIQUE)? INDEX/;
212 next if /^CREATE FUNCTION/;
213 next if /^CREATE TRIGGER/ or /^ FOR EACH ROW/;
214 next if /^INSERT INTO/ or /^ VALUES \(/;
215 next if /^ALTER TABLE/;
216 chomp;
217
218 if (/^\$mw\$;?$/) {
219 $infunction = $infunction ? 0 : 1;
220 next;
221 }
222 next if $infunction;
223
224 next if /^CREATE VIEW/ and $inview = 1;
225 if ($inview) {
226 /;$/ and $inview = 0;
227 next;
228 }
229
230 next if /^CREATE RULE/ and $inrule = 1;
231 if ($inrule) {
232 /;$/ and $inrule = 0;
233 next;
234 }
235
236 if (/^CREATE TABLE "?(\w+)"? \($/) {
237 $table = $1;
238 $new{$table}{name}=$table;
239 $lastcomma = 1;
240 }
241 elsif (/^\);$/) {
242 if ($lastcomma) {
243 warn "Stray comma before line $.\n";
244 }
245 }
246 elsif (/^ (\w+) +$dtype.*?(,?)(?: --.*)?$/) {
247 $new{$table}{column}{$1} = $2;
248 if (!$lastcomma) {
249 print "Missing comma before line $. of $new\n";
250 }
251 $lastcomma = $3 ? 1 : 0;
252 }
253 else {
254 die "Cannot parse line $. of $new:\n$_\n";
255 }
256 }
257
258 ## Which column types are okay to map from mysql to postgres?
259 my $COLMAP = q{
260 ## INTS:
261 tinyint SMALLINT
262 int INTEGER SERIAL
263 bigint BIGINT
264 real NUMERIC
265 float NUMERIC
266
267 ## TEXT:
268 varchar(15) TEXT
269 varchar(32) TEXT
270 varchar(70) TEXT
271 varchar(255) TEXT
272 varchar TEXT
273 text TEXT
274 tinytext TEXT
275 ENUM TEXT
276
277 ## TIMESTAMPS:
278 varbinary(14) TIMESTAMPTZ
279 binary(14) TIMESTAMPTZ
280 datetime TIMESTAMPTZ
281 timestamp TIMESTAMPTZ
282
283 ## BYTEA:
284 mediumblob BYTEA
285
286 ## OTHER:
287 bool SMALLINT # Sigh
288
289 };
290 ## Allow specific exceptions to the above
291 my $COLMAPOK = q{
292 ## User inputted text strings:
293 ar_comment tinyblob TEXT
294 fa_description tinyblob TEXT
295 img_description tinyblob TEXT
296 ipb_reason tinyblob TEXT
297 log_action varbinary(10) TEXT
298 oi_description tinyblob TEXT
299 rev_comment tinyblob TEXT
300 rc_log_action varbinary(255) TEXT
301 rc_log_type varbinary(255) TEXT
302
303 ## Simple text-only strings:
304 ar_flags tinyblob TEXT
305 fa_minor_mime varbinary(32) TEXT
306 fa_storage_group varbinary(16) TEXT # Just 'deleted' for now, should stay plain text
307 fa_storage_key varbinary(64) TEXT # sha1 plus text extension
308 ipb_address tinyblob TEXT # IP address or username
309 ipb_range_end tinyblob TEXT # hexadecimal
310 ipb_range_start tinyblob TEXT # hexadecimal
311 img_minor_mime varbinary(32) TEXT
312 img_sha1 varbinary(32) TEXT
313 job_cmd varbinary(60) TEXT # Should we limit to 60 as well?
314 keyname varbinary(255) TEXT # No tablename prefix (objectcache)
315 ll_lang varbinary(20) TEXT # Language code
316 log_params blob TEXT # LF separated list of args
317 log_type varbinary(10) TEXT
318 oi_minor_mime varbinary(32) TEXT
319 oi_sha1 varbinary(32) TEXT
320 old_flags tinyblob TEXT
321 old_text mediumblob TEXT
322 pp_propname varbinary(60) TEXT
323 pp_value blob TEXT
324 page_restrictions tinyblob TEXT # CSV string
325 pf_server varchar(30) TEXT
326 pr_level varbinary(60) TEXT
327 pr_type varbinary(60) TEXT
328 pt_create_perm varbinary(60) TEXT
329 pt_reason tinyblob TEXT
330 qc_type varbinary(32) TEXT
331 qcc_type varbinary(32) TEXT
332 qci_type varbinary(32) TEXT
333 rc_params blob TEXT
334 rlc_to_blob blob TEXT
335 ug_group varbinary(16) TEXT
336 user_email_token binary(32) TEXT
337 user_ip varbinary(40) TEXT
338 user_newpassword tinyblob TEXT
339 user_options blob TEXT
340 user_password tinyblob TEXT
341 user_token binary(32) TEXT
342
343 ## Text URLs:
344 el_index blob TEXT
345 el_to blob TEXT
346 iw_url blob TEXT
347 tb_url blob TEXT
348 tc_url varbinary(255) TEXT
349
350 ## Deprecated or not yet used:
351 ar_text mediumblob TEXT
352 job_params blob TEXT
353 log_deleted tinyint INTEGER # Not used yet, but keep it INTEGER for safety
354 rc_type tinyint CHAR
355
356 ## Number tweaking:
357 fa_bits int SMALLINT # bits per pixel
358 fa_height int SMALLINT
359 fa_width int SMALLINT # Hope we don't see an image this wide...
360 hc_id int BIGINT # Odd that site_stats is all bigint...
361 img_bits int SMALLINT # bits per image should stay sane
362 oi_bits int SMALLINT
363
364 ## True binary fields, usually due to gzdeflate and/or serialize:
365 math_inputhash varbinary(16) BYTEA
366 math_outputhash varbinary(16) BYTEA
367
368 ## Namespaces: not need for such a high range
369 ar_namespace int SMALLINT
370 job_namespace int SMALLINT
371 log_namespace int SMALLINT
372 page_namespace int SMALLINT
373 pl_namespace int SMALLINT
374 pt_namespace int SMALLINT
375 qc_namespace int SMALLINT
376 rc_namespace int SMALLINT
377 rd_namespace int SMALLINT
378 rlc_to_namespace int SMALLINT
379 tl_namespace int SMALLINT
380 wl_namespace int SMALLINT
381
382 ## Easy enough to change if a wiki ever does grow this big:
383 ss_good_articles bigint INTEGER
384 ss_total_edits bigint INTEGER
385 ss_total_pages bigint INTEGER
386 ss_total_views bigint INTEGER
387 ss_users bigint INTEGER
388
389 ## True IP - keep an eye on these, coders tend to make textual assumptions
390 rc_ip varbinary(40) CIDR # Want to keep an eye on this
391
392 ## Others:
393 tc_time int TIMESTAMPTZ
394
395
396 };
397
398 my %colmap;
399 for (split /\n/ => $COLMAP) {
400 next unless /^\w/;
401 s/(.*?)#.*/$1/;
402 my ($col,@maps) = split / +/, $_;
403 for (@maps) {
404 $colmap{$col}{$_} = 1;
405 }
406 }
407
408 my %colmapok;
409 for (split /\n/ => $COLMAPOK) {
410 next unless /^\w/;
411 my ($col,$old,$new) = split / +/, $_;
412 $colmapok{$col}{$old}{$new} = 1;
413 }
414
415 ## Old but not new
416 for my $t (sort keys %{$old{$oldfile}}) {
417 if (!exists $new{$t} and !exists $ok{OLD}{$t}) {
418 print "Table not in $new: $t\n";
419 next;
420 }
421 next if exists $ok{OLD}{$t} and !$ok{OLD}{$t};
422 my $newt = exists $ok{OLD}{$t} ? $ok{OLD}{$t} : $t;
423 my $oldcol = $old{$oldfile}{$t}{column};
424 my $oldcolfull = $old{$oldfile}{$t}{columnfull};
425 my $newcol = $new{$newt}{column};
426 for my $c (keys %$oldcol) {
427 if (!exists $newcol->{$c}) {
428 print "Column $t.$c not in $new\n";
429 next;
430 }
431 }
432 for my $c (sort keys %$newcol) {
433 if (!exists $oldcol->{$c}) {
434 print "Column $t.$c not in $oldfile\n";
435 next;
436 }
437 ## Column types (roughly) match up?
438 my $new = $newcol->{$c};
439 my $old = $oldcolfull->{$c};
440
441 ## Known exceptions:
442 next if exists $colmapok{$c}{$old}{$new};
443
444 $old =~ s/ENUM.*/ENUM/;
445 if (! exists $colmap{$old}{$new}) {
446 print "Column types for $t.$c do not match: $old does not map to $new\n";
447 }
448 }
449 }
450 ## New but not old:
451 for (sort keys %new) {
452 if (!exists $old{$oldfile}{$_} and !exists $ok{NEW}{$_}) {
453 print "Not in $oldfile: $_\n";
454 next;
455 }
456 }
457
458
459 } ## end each file to be parsed
460
461
462 sub check_includes_dir {
463
464 ## Check for some common errors in the files in the includes directory
465
466 print "Checking files in includes directory...\n";
467 my $dir = '../../includes';
468 opendir my $dh, $dir or die qq{Could not opendir $dir: $!\n};
469 for my $file (grep { -f "$dir/$_" and /\.php$/ } readdir $dh) {
470 $file = "$dir/$file";
471 open my $fh, '<', $file or die qq{Could not open "$file": $!\n};
472 while (<$fh>) {
473 if (/FORCE INDEX/ and $file !~ /Database.php/) {
474 warn "Found FORCE INDEX string at line $. of $file\n";
475 }
476 if (/REPLACE INTO/ and $file !~ /Database/) {
477 warn "Found REPLACE INTO string at line $. of $file\n";
478 }
479 if (/\bIF\s*\(/ and $file !~ /Database.php/) {
480 warn "Found IF string at line $. of $file\n";
481 }
482 if (/\bCONCAT\b/ and $file !~ /Database.php/) {
483 warn "Found CONCAT string at line $. of $file\n";
484 }
485 }
486 close $fh or die qq{Could not close "$file": $!\n};
487 }
488 closedir $dh or die qq{Closedir failed?!\n};
489
490 return;
491
492 } ## end of check_includes_dir
493
494 __DATA__
495 ## Known exceptions
496 OLD: searchindex ## We use tsearch2 directly on the page table instead
497 RENAME: user mwuser ## Reserved word causing lots of problems
498 RENAME: text pagecontent ## Reserved word
499 NEW: mediawiki_version ## Just us, for now
500 XFILE: ../archives/patch-profiling.sql