schemadiff 16.1 KB
Newer Older
1 2
#!/usr/bin/perl -w

Leigh B. Stoller's avatar
Leigh B. Stoller committed
3
#
4
# Copyright (c) 2000-2013 University of Utah and the Flux Group.
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
# 
# {{{EMULAB-LICENSE
# 
# This file is part of the Emulab network testbed software.
# 
# This file is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or (at
# your option) any later version.
# 
# This file is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public
# License for more details.
# 
# You should have received a copy of the GNU Affero General Public License
# along with this file.  If not, see <http://www.gnu.org/licenses/>.
# 
# }}}
Leigh B. Stoller's avatar
Leigh B. Stoller committed
24 25 26
#


27 28 29 30 31 32 33 34 35
#
# schemadiff - Find the differences between two database schemas, as reported
# by mysqldump. Can print out a summary of changes, or SQL commands to make
# the necessary changes
#

use strict;
use Getopt::Std; 

36 37 38 39 40 41 42 43 44 45 46
#
# Functions
#
sub read_schema($);
sub compare_tables($$);
sub compare_keys($$@);
sub compare_columns($$@);
sub diff_keys($$);
sub usage();
sub debug(@);

47 48 49 50 51
#
# Default settings for the options
#
my $debug = 0;
my $sql = 1;
52
my $quiet = 0;
53
my $ignore_tables = 0;
54 55 56 57 58

#
# Return value - number of differences between the two files
#
my $diff = 0;
59 60 61 62 63

#
# Process command-line args
#
my %opt;
64
getopts('hdsqt', \%opt); 
65 66 67 68 69 70 71 72 73
if ($opt{h}) {
    exit &usage;
}
if ($opt{d}) {
    $debug = 1;
}
if ($opt{s}) {
    $sql = 0;
}
74 75 76 77 78
if ($opt{q}) {
    $quiet = 1;
    $sql = 0;
    $debug = 0;
}
79 80 81
if ($opt{t}) {
    $ignore_tables = 1;
}
82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120

if (@ARGV != 2) {
    exit &usage
}

my ($file1,$file2) = @ARGV;


#
# Read in the two schemas. They are returned as references to hashes, as
# documented below in the read_schema function
#
my $schema1 = read_schema($file1);
my $schema2 = read_schema($file2);

#
# Find out which tables have been created or deleted. We get back a list
# of tables that are common to both schemas, which we can use to tell
# the other functions which tables to operate on.
#
my @common_tables = compare_tables($schema1,$schema2);

#
# Next, we compare the columns in each of the columns
#
compare_columns($schema1,$schema2,@common_tables);

#
# Finally, we check to see if they have the same keys
#
compare_keys($schema1,$schema2,@common_tables);

#
# XXX: We could also compare the table types - however, it seems somewhat
# dangerous to go around changing table types. We can easily add this feature 
# in if we ever need it (for example, if we start using the special features
# of InnoDB tables)
#

121 122 123 124 125 126 127 128 129
#
# Give our caller back some useful information
#
if ($diff > 0) {
    exit(1);
} else {
    exit(0);
}

130 131 132 133 134 135 136 137 138
######################################################################
# Subs
######################################################################

#
# Given a filename, read the schema into a structure. This structure consists 
# of a hash, indexed by table name. Each table is a hash ref containing:
# PRIMARY: A hash containing the primary keys. Indexed by key, value is
#       set to 1 for all keys that are primary
139
# KEYS: Indexed by key name, value is the columns used by the key
140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157
# COLUMNS: A hash reference, indexed by column, containing the create 
#       definition for that column
# ORDERED_COLUMNS: An array reference, containing all of the columns in
#       their original order, so that we can try to keep the column order
#       the same for table creation and column addition. Each column is
#       an array reference, the first element being the column name, and the
#       second being the create definition
# TYPE: A scalar, containing the type of the table
sub read_schema($) {
    #
    # Open up the file
    #
    my $filename = shift;
    open(FH,"<$filename") or die "Unable to open $filename: $!\n";

    my $create_table = 0;
    my $table_name = "";
    my %tables = ();
158
    my $skip_table = 0; # Indicates that we should skip this table
159 160 161 162 163 164 165 166

    while (<FH>) {
	chomp;
	#
	# Determine which type of line this is. Our (really simple) parsing
	# differs depending on whether or not we're in a create definition.
	#
	if (!$create_table) {
167
	    if (/^\s*$/i || /^\s*#/i || /^--/i || /^INSERT INTO/i) {
168
		# An insert statement, a comment, or a blank line. Do nothing.
169
	    }
170
	    elsif (/^\/\*.*\*\/[;]+$/i) {
171 172
		# Also a comment
	    }
173
	    elsif (/^DROP TABLE /i) {
174 175
		# mysql 5.0 add these now.
	    }
176
	    elsif (/^CREATE TABLE `?(\w+)`? \($/i) {
177 178 179
		# Start of a new table definition
		$create_table = 1;
		$table_name = $1;
180 181 182 183 184 185 186 187 188 189 190

		#
		# We have to skip any tables that get dynamically generated
		#
		if ($table_name =~ /^[\w-]+_[\w-]+_events$/) {
		    debug("Skipping table $table_name\n");
		    $skip_table = 1;
		} else {
		    $skip_table = 0;
		}

191 192 193 194 195 196 197 198 199 200 201 202 203
		debug("Entering table $table_name\n");

	    } else {

		warn "Found a line I don't know what to do with!\n";
		die "$_\n";

	    }
	} else {
	    #
	    # If we are in a table creation statement, we need to find out
	    # what this line is trying to do...
	    #
204 205 206
	    if (/^\) TYPE\s*=\s*(\w+);/i ||
		/^\) ENGINE\s*=\s*(\w+)\s*DEFAULT\s*CHARSET=(\w+);/i ||
		/^\) ENGINE\s*=\s*(\w+)\s*AUTO_INCREMENT=\d*\s*DEFAULT\s*CHARSET=(\w+);/i) {
207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222

		# The end of the table definition
		my $type = $1;
		$create_table = 0;
		debug("Leaving table $table_name (type $type)\n");
		if (!$skip_table) {
		    $tables{$table_name}{TYPE} = $type;
		}

	    } elsif ($skip_table) {
		#
		# Don't bother processing this line
		#
		next;
	    } # NOTE - elsif below

223
	    #
224
	    # Some cases of things we don't handle yet. None of these
225 226 227 228
	    # are used by the testbed software yet, but we should support
	    # them someday for completeness. For now, we have check for them
	    # so that we don't accidentally treat them as columns
	    #
229
	    elsif (/^\s*.*\s+FOREIGN KEY\s+/i) {
230
		die "Found a FOREIGN KEY line, which we don't handle yet\n";
231
	    } elsif (/^\s*CHECK\s*\((.+)\),?$/i) {
232
		die "Found a CHECK line, which we don't handle yet\n";
233
	    } elsif (/^\s*UNIQUE (INDEX)?\s+(\w+)?\s+\((.+[^,])\),?$/i) {
234
		die "Found a UNIQUE (INDEX) line, which we don't handle yet\n";
235 236 237 238 239 240 241 242 243 244 245 246 247 248 249
	    } elsif (/^\s*FULLTEXT (KEY|INDEX)?\s+`?(\w+)?`?\s+\((.+[^,])\),?$/i) {
		
		# A key/index (synonmyms)
		my ($name, $key) = ($1, $2);
		# Strip whitespace
		$key =~ s/\s+//g;
		# Strip backquotes
		$key =~ s/\`//g;
  		debug("Putting key $key in table $table_name\n");

  	 	if ($name) {
		    $tables{$table_name}{KEYS}{$name} = $key;
		} else { 
		    die "Found a key without a name: $key\n";
		}
250

251
	    } elsif (/^\s*PRIMARY KEY\s*\((.+)\),?$/i) {
252 253 254

		# A primary key
		my $key = $1;
255 256
		# Strip whitespace
		$key =~ s/\s+//g;
257 258
		# Strip backquotes
		$key =~ s/\`//g;
259 260 261
		debug("Putting primary key $key in table $table_name\n");
		$tables{$table_name}{PRIMARY}{$key} = 1;

262
	    } elsif (/^\s*(UNIQUE)?\s+(KEY|INDEX)\s+`?(\w+)?`?\s+\((.+[^,])\),?$/i) {
263 264 265

		# A key/index (synonmyms)
		my ($name, $key) = ($2, $3);
266 267
		# Strip whitespace
		$key =~ s/\s+//g;
268 269 270
		# Strip backquotes
		$key =~ s/\`//g;
  		debug("Putting key $key in table $table_name\n");
271

272
  	 	if ($name) {
273
		    $tables{$table_name}{KEYS}{$name} = $key;
274 275 276 277
		} else { 
		    die "Found a key without a name: $key\n";
		}

278
	    } elsif (/^\s*`?(\w+)`?\s+(.+[^,\s]),?\s*$/i) {
279 280 281 282

		# A column definition
		my ($name, $definition) = ($1, $2);
		debug("Found column $name with type $definition\n");
283

284 285 286 287 288 289
		# Canonicalize. 
		if ($definition eq "text") {
		    debug("  Converting to 'text default NULL'\n");
		    $definition = "text default NULL";
		}

290 291 292 293
		# Case issues
		$definition =~ s/ DEFAULT / default /g;
		$definition =~ s/ AUTO_INCREMENT/ auto_increment/g;

294 295 296 297
		# Change timestamp(14) to timestamp!
		$definition =~ s/timestamp NOT NULL default.*/timestamp NOT NULL/g;
		$definition =~ s/timestamp\(14\)/timestamp/g;
		
298 299 300 301 302
		$tables{$table_name}{COLUMNS}{$name} = $definition;

		push @{ $tables{$table_name}{ORDERED_COLUMNS} },
		    [$name, $definition];

303
	    }  else {
304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334

		warn "Found a line I don't know what to do with!\n";
		die "$_\n";

	    }
	}
    }

    #
    # Whew, all done!
    #
    close (FH);
    return \%tables;
}

#
# Compare the list of tables in the two given schemas. Returns a list of
# tables that are in both schemas
#
sub compare_tables($$) {
    my ($schema1,$schema2) = @_;

    #
    # Find the difference in tables
    #
    my ($removed, $added, $common) = diff_keys($schema1,$schema2);

    #
    # Removed tables are easy to handle 
    #
    foreach my $table (@$removed) {
335 336
	$diff++
	    if (!$ignore_tables);
337 338
	if (!$quiet) { print "# Table $table was removed\n"; }
	if ($sql) { print "DROP TABLE $table;\n\n"; }
339 340 341 342 343 344
    }

    #
    #
    #
    foreach my $table (@$added) {
345 346
	$diff++
	    if (!$ignore_tables);
347
	if (!$quiet) { print "# Table $table was added\n"; }
348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370
	if ($sql) {
	    print "CREATE TABLE $table (\n";

	    #
	    # We put all of the lines in an array, so that we can use a join
	    # to put them together (otherwise, it's awkward to figure out 
	    # which is the last, for comma-seperarating purposes)
	    #
	    my @out = ();

	    #
	    # We use the ORDERED_COLUMNS member so that we end up with the
	    # same column order as the original table
	    #
	    foreach my $aref (@{ $schema2->{$table}{ORDERED_COLUMNS} }) {
		my ($name, $def) = @$aref;
		push @out, "  $name $def";
	    }

	    foreach my $primary (keys %{$schema2->{$table}{PRIMARY}}) {
		push @out, "  PRIMARY KEY (" . $primary . ")";
	    }

371 372
	    foreach my $name (keys %{$schema2->{$table}{KEYS}}) {
		my $key = $schema2->{$table}{KEYS}{$name};
373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402
		push @out, "  KEY $name (" . $key . ")";
	    }

	    # XXX: Could include type here
	    print join(",\n",@out), "\n);\n\n"
	}
    }

    #
    # Let the caller know which tables were in both schemas
    #
    return @$common;
}

#
# Compare the keys (indexes) of two schemas. Only operates on tables given
# in the third argument, so that tables that have been added or removed can
# be ignored
#
sub compare_keys($$@) {
    my ($schema1,$schema2,@tables) = @_;

    #
    # Check the primary keys
    #
    foreach my $table (@tables) {
	my ($removed, $added, $common) =
	    diff_keys($schema1->{$table}{PRIMARY},$schema2->{$table}{PRIMARY});

	foreach my $key (@$removed) {
403 404 405 406
	    $diff++;
	    if (!$quiet) {
		print "# Primary key ($key) was removed from table $table\n";
	    }
407 408 409 410 411 412
	    if ($sql) {
		print "ALTER TABLE $table DROP PRIMARY KEY;\n\n";
	    }
	}

	foreach my $key (@$added) {
413 414 415 416
	    $diff++;
	    if (!$quiet) {
		print "# Primary key ($key) was added to table $table\n";
	    }
417 418 419 420 421 422 423 424 425 426 427
	    if ($sql) {
		print "ALTER TABLE $table ADD PRIMARY KEY ($key);\n\n";
	    }
	}

    }

    #
    # Check the regular keys
    #
    foreach my $table (@tables) {
428
	my ($removed, $added, $common) =
429 430
	    diff_keys($schema1->{$table}{KEYS},$schema2->{$table}{KEYS});

431
	foreach my $name (@$added) {
432
	    $diff++;
433
	    my $key = $schema2->{$table}{KEYS}{$name};
434 435 436
	    if (!$quiet) { 
		print "# Key $name ($key) was added to table $table\n";
	    }
437
	    if ($sql) {
438
		print "ALTER TABLE $table ADD INDEX $name ($key);\n\n";
439 440 441
	    }
	}

442
	foreach my $name (@$removed) {
443
	    $diff++;
444
	    my $key = $schema1->{$table}{KEYS}{$name};
445 446 447
	    if (!$quiet) {
		print "# Key $name ($key) was removed from table $table\n";
	    }
448
	    if ($sql) {
449
		print "ALTER TABLE $table DROP INDEX $name;\n\n";
450 451 452 453 454 455
	    }
	}

    }
}

456 457 458 459 460 461 462
#
# Compare the columns of two schemas. Only operates on tables given
# in the third argument, so that tables that have been added or removed can
# be ignored. In addition to added and removed columns, it detects changed
# (same name but different definitions) and renamed (same definition but 
# different names) columns
#
463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487
sub compare_columns($$@) {
    my ($schema1,$schema2,@tables) = @_;

    #
    # Check the regular keys
    #
    foreach my $table (@tables) {
	my ($removed, $added, $common) =
	    diff_keys($schema1->{$table}{COLUMNS},$schema2->{$table}{COLUMNS});

	#
	# Look for columns that may have had their names changed. This
	# involves finding two tables that have identical definitions, but
	# different names. These will be in @$added and @$removed.
	#
	my $i = 0; # We have to iterate by index, so we can remove elements
	ADDED: while ($i < @$added) {

	    my $new_definition = $schema2->{$table}{COLUMNS}{$added->[$i]};

	    my $j = 0;
	    while ($j < @$removed) {
		my $old_definition =
		    $schema1->{$table}{COLUMNS}{$removed->[$j]};

488
		if (lc($old_definition) eq lc($new_definition)) {
489 490
		    $diff++;

491 492 493 494 495 496
		    #
		    # Found a renamed column
		    #
		    my $oldname = $removed->[$j];
		    my $newname = $added->[$i];

497 498 499
		    if (!$quiet) {
			print "# Column $oldname was renamed to $newname\n";
		    }
500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542
		    if ($sql) {
			print "ALTER TABLE $table CHANGE COLUMN $oldname " .
			    "$newname $new_definition;\n\n";
		    }

		    #
		    # Pull this element out of the two lists, since it wasn't
		    # really added or removed
		    #
		    splice(@$added,$i);
		    splice(@$removed,$j);
		    next ADDED;

		} else {
		    $j++;
		}
	    }

	    $i++;
	}

	debug("Added is: ",join(',',@$added),"\n");
	debug("Removed is: ",join(',',@$removed),"\n");

	#
	# Make hashes of the added and removed lists to make for quick
	# lookup
	#
	my %added;
	foreach my $column (@$added) { $added{$column} = 1; }
	my %removed;
	foreach my $column (@$removed) { $removed{$column} = 1; }

	#
	# Handle columns that were added.
	# Go through the columns in order, so that we (1) preserve the order,
	# and (2) don't attempt to use an AFTER clause referencing a table
	# that does not exist.
	#
	my $last_column = undef;
	foreach my $column (@{ $schema2->{$table}{ORDERED_COLUMNS} }) {
	    my ($name, $definition) = @$column;
	    if ($added{$name}) {
543 544 545 546
		$diff++;
		if (!$quiet) {
		    print "# Column $name was added to table $table\n";
		}
547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564
		if ($sql) {
		    my $location;
		    if ($last_column) {
			$location = "AFTER $last_column";
		    } else {
			$location = "FIRST";
		    }
		    print "ALTER TABLE $table ADD COLUMN $name " . 
		    	"$definition $location;\n\n";
		}
	    }
	    $last_column = $name;
	}

	#
	# Handle columns that were removed
	#
	foreach my $column (@$removed) {
565 566 567 568
	    $diff++;
	    if (!$quiet) {
		print "# Column $column was removed from table $table\n";
	    }
569 570 571 572 573 574 575 576 577 578 579 580
	    if ($sql) {
		print "ALTER TABLE $table DROP COLUMN $column;\n\n";
	    }
	}
	
	#
	# Look through the columns that are in both, so that we can tell
	# if the definition for any have changed
	#
	foreach my $column (@$common) {
	    if ($schema1->{$table}{COLUMNS}{$column} ne
		    $schema2->{$table}{COLUMNS}{$column} ) {
581 582 583 584
		$diff++;
		if (!$quiet) {
		    print "# Column $column in table $table has changed\n";
		}
585 586 587 588 589 590 591 592 593 594 595
		if ($sql) {
		    print "ALTER TABLE $table MODIFY $column ",
		    $schema2->{$table}{COLUMNS}{$column}, ";\n\n";
		}
	    }
	}

    }
}

#
596
# Given two different hash references, return refereces to three arrays:
597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638
# The keys that are in the first hash, but not the second
# The keys that are in the second hash, but not the first
# They keys that are in both hashes
#
sub diff_keys($$) {
    my ($hash1,$hash2) = (@_);
    my (@first_only,@second_only,@common);

    #
    # Go through the first hash, looking for both keys that aren't in the
    # second, and keys that both have in common
    #
    foreach my $key (keys %$hash1) {
	if (!exists($hash2->{$key})) {
	    push @first_only, $key;
	} else {
	    push @common, $key;
	}
    }

    #
    # Make a pass through the second, looking for keys that are unique to it
    #
    foreach my $key (keys %$hash2) {
	if (!exists($hash1->{$key})) {
	    push @second_only, $key;
	}
    }

    return (\@first_only,\@second_only,\@common);
}

#
# Usage message
#
sub usage() {
    print "usage: $0 [-h] [-s] [-d] <file1> <file2>\n";
    print "Prints on stdout a set of SQL commands to change the database\n";
    print "from file1 so that it has the same schema as the database from\n";
    print "file2 (same argument order as diff)\n\n";
    print "-h    This message\n";
    print "-s    Summary: Don't print SQL statments to apply changes\n";
639
    print "-q    Quiet: Don't print anything, just return a value\n";
640
    print "-t    Ignore table creates and drops\n";
641 642 643 644 645 646 647 648 649 650 651 652
    print "-d    Turn on debugging output\n";
    return 1;
}

#
# Print the message, only if the gloabal $debug variable is set
#
sub debug(@) {
    if ($debug) {
	print @_;
    }
}