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