Sites are unlikely to have over 2 billion active users
[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| 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 m{^CREATE TABLE /\*\$wgDBprefix\*/(\w+) \($}
100 or die qq{Invalid CREATE TABLE at line $. of $oldfile\n};
101 $table = $1;
102 $info{$table}{name}=$table;
103 }
104 elsif (m{^\) /\*\$wgDBTableOptions\*/}) {
105 $info{$table}{engine} = 'ENGINE';
106 $info{$table}{type} = 'variable';
107 }
108 elsif (/^\) ($engine)=($tabletype);$/) {
109 $info{$table}{engine}=$1;
110 $info{$table}{type}=$2;
111 }
112 elsif (/^\) ($engine)=($tabletype), DEFAULT CHARSET=($charset);$/) {
113 $info{$table}{engine}=$1;
114 $info{$table}{type}=$2;
115 $info{$table}{charset}=$3;
116 }
117 elsif (/^ (\w+) $datatype$typeval$typeval2{0,3},?$/) {
118 $info{$table}{column}{$1} = $2;
119 my $extra = $3 || '';
120 $info{$table}{columnfull}{$1} = "$2$extra";
121 }
122 elsif (/^ ($indextype)(?: (\w+))? \(([\w, \(\)]+)\),?$/) {
123 $info{$table}{lc $1.'_name'} = $2 ? $2 : '';
124 $info{$table}{lc $1.'pk_target'} = $3;
125 }
126 else {
127 die "Cannot parse line $. of $oldfile:\n$_\n";
128 }
129
130 }
131 close $oldfh or die qq{Could not close "$oldfile": $!\n};
132
133 return \%info;
134
135 } ## end of parse_sql
136
137 ## Read in the parser test information
138 my $parsefile = '../parserTests.inc';
139 open my $pfh, '<', $parsefile or die qq{Could not open "$parsefile": $!\n};
140 my $stat = 0;
141 my %ptable;
142 while (<$pfh>) {
143 if (!$stat) {
144 if (/function listTables/) {
145 $stat = 1;
146 }
147 next;
148 }
149 $ptable{$1}=2 while m{'(\w+)'}g;
150 last if /\);/;
151 }
152 close $pfh or die qq{Could not close "$parsefile": $!\n};
153
154 my $OK_NOT_IN_PTABLE = '
155 filearchive
156 logging
157 profiling
158 querycache_info
159 searchindex
160 trackbacks
161 transcache
162 user_newtalk
163 updatelog
164 ';
165
166 ## Make sure all tables in main tables.sql are accounted for in the parsertest.
167 for my $table (sort keys %{$old{'../tables.sql'}}) {
168 $ptable{$table}++;
169 next if $ptable{$table} > 2;
170 next if $OK_NOT_IN_PTABLE =~ /\b$table\b/;
171 print qq{Table "$table" is in the schema, but not used inside of parserTest.inc\n};
172 }
173 ## Any that are used in ptables but no longer exist in the schema?
174 for my $table (sort grep { $ptable{$_} == 2 } keys %ptable) {
175 print qq{Table "$table" ($ptable{$table}) used in parserTest.inc, but not found in schema\n};
176 }
177
178 for my $oldfile (@old) {
179
180 ## Begin non-standard indent
181
182 ## MySQL sanity checks
183 for my $table (sort keys %{$old{$oldfile}}) {
184 my $t = $old{$oldfile}{$table};
185 if ($t->{engine} eq 'TYPE') {
186 die "Invalid engine for $oldfile: $t->{engine}\n" unless $t->{name} eq 'profiling';
187 }
188 my $charset = $t->{charset} || '';
189 if ($oldfile !~ /binary/ and $charset eq 'binary') {
190 die "Invalid charset for $oldfile: $charset\n";
191 }
192 }
193
194 my $dtype = join '|' => qw(
195 SMALLINT INTEGER BIGINT NUMERIC SERIAL
196 TEXT CHAR VARCHAR
197 BYTEA
198 TIMESTAMPTZ
199 CIDR
200 );
201 $dtype = qr{($dtype)};
202 my %new;
203 my ($infunction,$inview,$inrule,$lastcomma) = (0,0,0,0);
204 seek $newfh, 0, 0;
205 while (<$newfh>) {
206 next if /^\s*\-\-/ or /^\s*$/;
207 s/\s*\-\- [\w ']+$//;
208 next if /^BEGIN;/ or /^SET / or /^COMMIT;/;
209 next if /^CREATE SEQUENCE/;
210 next if /^CREATE(?: UNIQUE)? INDEX/;
211 next if /^CREATE FUNCTION/;
212 next if /^CREATE TRIGGER/ or /^ FOR EACH ROW/;
213 next if /^INSERT INTO/ or /^ VALUES \(/;
214 next if /^ALTER TABLE/;
215 chomp;
216
217 if (/^\$mw\$;?$/) {
218 $infunction = $infunction ? 0 : 1;
219 next;
220 }
221 next if $infunction;
222
223 next if /^CREATE VIEW/ and $inview = 1;
224 if ($inview) {
225 /;$/ and $inview = 0;
226 next;
227 }
228
229 next if /^CREATE RULE/ and $inrule = 1;
230 if ($inrule) {
231 /;$/ and $inrule = 0;
232 next;
233 }
234
235 if (/^CREATE TABLE "?(\w+)"? \($/) {
236 $table = $1;
237 $new{$table}{name}=$table;
238 $lastcomma = 1;
239 }
240 elsif (/^\);$/) {
241 if ($lastcomma) {
242 warn "Stray comma before line $.\n";
243 }
244 }
245 elsif (/^ (\w+) +$dtype.*?(,?)(?: --.*)?$/) {
246 $new{$table}{column}{$1} = $2;
247 if (!$lastcomma) {
248 print "Missing comma before line $. of $new\n";
249 }
250 $lastcomma = $3 ? 1 : 0;
251 }
252 else {
253 die "Cannot parse line $. of $new:\n$_\n";
254 }
255 }
256
257 ## Which column types are okay to map from mysql to postgres?
258 my $COLMAP = q{
259 ## INTS:
260 tinyint SMALLINT
261 int INTEGER SERIAL
262 bigint BIGINT
263 real NUMERIC
264 float NUMERIC
265
266 ## TEXT:
267 varchar(15) TEXT
268 varchar(32) TEXT
269 varchar(70) TEXT
270 varchar(255) TEXT
271 varchar TEXT
272 text TEXT
273 tinytext TEXT
274 ENUM TEXT
275
276 ## TIMESTAMPS:
277 varbinary(14) TIMESTAMPTZ
278 binary(14) TIMESTAMPTZ
279 datetime TIMESTAMPTZ
280 timestamp TIMESTAMPTZ
281
282 ## BYTEA:
283 mediumblob BYTEA
284
285 ## OTHER:
286 bool SMALLINT # Sigh
287
288 };
289 ## Allow specific exceptions to the above
290 my $COLMAPOK = q{
291 ## User inputted text strings:
292 ar_comment tinyblob TEXT
293 fa_description tinyblob TEXT
294 img_description tinyblob TEXT
295 ipb_reason tinyblob TEXT
296 log_action varbinary(10) TEXT
297 oi_description tinyblob TEXT
298 rev_comment tinyblob TEXT
299 rc_log_action varbinary(255) TEXT
300 rc_log_type varbinary(255) TEXT
301
302 ## Simple text-only strings:
303 ar_flags tinyblob TEXT
304 fa_minor_mime varbinary(32) TEXT
305 fa_storage_group varbinary(16) TEXT # Just 'deleted' for now, should stay plain text
306 fa_storage_key varbinary(64) TEXT # sha1 plus text extension
307 ipb_address tinyblob TEXT # IP address or username
308 ipb_range_end tinyblob TEXT # hexadecimal
309 ipb_range_start tinyblob TEXT # hexadecimal
310 img_minor_mime varbinary(32) TEXT
311 img_sha1 varbinary(32) TEXT
312 job_cmd varbinary(60) TEXT # Should we limit to 60 as well?
313 keyname varbinary(255) TEXT # No tablename prefix (objectcache)
314 ll_lang varbinary(20) TEXT # Language code
315 log_params blob TEXT # LF separated list of args
316 log_type varbinary(10) TEXT
317 oi_minor_mime varbinary(32) TEXT
318 oi_sha1 varbinary(32) TEXT
319 old_flags tinyblob TEXT
320 old_text mediumblob TEXT
321 pp_propname varbinary(60) TEXT
322 pp_value blob TEXT
323 page_restrictions tinyblob TEXT # CSV string
324 pf_server varchar(30) TEXT
325 pr_level varbinary(60) TEXT
326 pr_type varbinary(60) TEXT
327 pt_create_perm varbinary(60) TEXT
328 pt_reason tinyblob TEXT
329 qc_type varbinary(32) TEXT
330 qcc_type varbinary(32) TEXT
331 qci_type varbinary(32) TEXT
332 rc_params blob TEXT
333 rlc_to_blob blob TEXT
334 ug_group varbinary(16) TEXT
335 user_email_token binary(32) TEXT
336 user_ip varbinary(40) TEXT
337 user_newpassword tinyblob TEXT
338 user_options blob TEXT
339 user_password tinyblob TEXT
340 user_token binary(32) TEXT
341
342 ## Text URLs:
343 el_index blob TEXT
344 el_to blob TEXT
345 iw_url blob TEXT
346 tb_url blob TEXT
347 tc_url varbinary(255) TEXT
348
349 ## Deprecated or not yet used:
350 ar_text mediumblob TEXT
351 job_params blob TEXT
352 log_deleted tinyint INTEGER # Not used yet, but keep it INTEGER for safety
353 rc_type tinyint CHAR
354
355 ## Number tweaking:
356 fa_bits int SMALLINT # bits per pixel
357 fa_height int SMALLINT
358 fa_width int SMALLINT # Hope we don't see an image this wide...
359 hc_id int BIGINT # Odd that site_stats is all bigint...
360 img_bits int SMALLINT # bits per image should stay sane
361 oi_bits int SMALLINT
362
363 ## True binary fields, usually due to gzdeflate and/or serialize:
364 math_inputhash varbinary(16) BYTEA
365 math_outputhash varbinary(16) BYTEA
366
367 ## Namespaces: not need for such a high range
368 ar_namespace int SMALLINT
369 job_namespace int SMALLINT
370 log_namespace int SMALLINT
371 page_namespace int SMALLINT
372 pl_namespace int SMALLINT
373 pt_namespace int SMALLINT
374 qc_namespace int SMALLINT
375 rc_namespace int SMALLINT
376 rd_namespace int SMALLINT
377 rlc_to_namespace int SMALLINT
378 tl_namespace int SMALLINT
379 wl_namespace int SMALLINT
380
381 ## Easy enough to change if a wiki ever does grow this big:
382 ss_active_users bigint INTEGER
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_valid_sql {
463
464 ## Check for a few common problems in most php files
465
466 my $olddir = getcwd();
467 chdir("../..");
468 for my $basedir (qw/includes extensions/) {
469 scan_dir($basedir);
470 }
471 chdir $olddir;
472
473 return;
474
475 } ## end of check_valid_sql
476
477
478 sub scan_dir {
479
480 my $dir = shift;
481
482 opendir my $dh, $dir or die qq{Could not opendir $dir: $!\n};
483 #print "Scanning $dir...\n";
484 for my $file (grep { -f "$dir/$_" and /\.php$/ } readdir $dh) {
485 find_problems("$dir/$file");
486 }
487 rewinddir $dh;
488 for my $subdir (grep { -d "$dir/$_" and ! /\./ } readdir $dh) {
489 scan_dir("$dir/$subdir");
490 }
491 closedir $dh or die qq{Closedir failed: $!\n};
492 return;
493
494 } ## end of scan_dir
495
496 sub find_problems {
497
498 my $file = shift;
499 open my $fh, '<', $file or die qq{Could not open "$file": $!\n};
500 while (<$fh>) {
501 if (/FORCE INDEX/ and $file !~ /Database\w*\.php/) {
502 warn "Found FORCE INDEX string at line $. of $file\n";
503 }
504 if (/REPLACE INTO/ and $file !~ /Database\w*\.php/) {
505 warn "Found REPLACE INTO string at line $. of $file\n";
506 }
507 if (/\bIF\s*\(/ and $file !~ /DatabaseMySQL\.php/) {
508 warn "Found IF string at line $. of $file\n";
509 }
510 if (/\bCONCAT\b/ and $file !~ /Database\w*\.php/) {
511 warn "Found CONCAT string at line $. of $file\n";
512 }
513 if (/\bGROUP\s+BY\s*\d\b/i and $file !~ /Database\w*\.php/) {
514 warn "Found GROUP BY # at line $. of $file\n";
515 }
516 }
517 close $fh or die qq{Could not close "$file": $!\n};
518 return;
519
520 } ## end of find_problems
521
522
523 __DATA__
524 ## Known exceptions
525 OLD: searchindex ## We use tsearch2 directly on the page table instead
526 RENAME: user mwuser ## Reserved word causing lots of problems
527 RENAME: text pagecontent ## Reserved word
528 NEW: mediawiki_version ## Just us, for now
529 XFILE: ../archives/patch-profiling.sql