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