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