ac287c25717fded2add44803ad7bb288cbc1010b
[koha.git] / misc / maintenance / audit_database.pl
1 #!/usr/bin/perl
2
3 use Modern::Perl;
4 use SQL::Translator;
5 use SQL::Translator::Diff;
6 use Getopt::Long;
7
8 use C4::Context;
9
10 my $filename = "./installer/data/mysql/kohastructure.sql";
11
12 GetOptions(
13     "filename=s" => \$filename,
14 ) or die("Error in command line arguments\n");
15
16 if ( !-f $filename ) {
17     die("Filename '$filename' does not exist\n");
18 }
19
20 my $sql_schema = get_kohastructure( { filename => $filename, } );
21 my $db_schema  = get_db();
22
23 if ( $sql_schema && $db_schema ) {
24     my $diff = SQL::Translator::Diff->new(
25         {
26             output_db     => 'MySQL',
27             source_schema => $db_schema,
28             target_schema => $sql_schema,
29         }
30     )->compute_differences->produce_diff_sql;
31
32     print $diff;
33     print "\n";
34     print "WARNING!!!\n";
35     print "These commands are only suggestions! They are not a replacement for updatedatabase.pl!\n";
36     print "Review the database, updatedatabase.pl, and kohastructure.sql before making any changes!\n";
37     print "\n";
38 }
39
40 sub get_db {
41     my $database_name = C4::Context->config("database");
42     print "Parsing schema for database '$database_name'\n";
43     my $dbh    = C4::Context->dbh;
44     my $parser = SQL::Translator->new(
45         parser      => 'DBI',
46         parser_args => {
47             dbh => $dbh,
48         },
49     );
50     my $schema = $parser->translate();
51
52     #NOTE: Hack the schema to remove autoincrement
53     #Otherwise, that difference will cause options for all tables to be reset unnecessarily
54     my @tables = $schema->get_tables();
55     foreach my $table (@tables) {
56         my @new_options     = ();
57         my $replace_options = 0;
58         my $options         = $table->{options};
59         foreach my $hashref (@$options) {
60             if ( $hashref->{AUTO_INCREMENT} ) {
61                 $replace_options = 1;
62             } else {
63                 push( @new_options, $hashref );
64             }
65         }
66         if ($replace_options) {
67             @{ $table->{options} } = @new_options;
68         }
69     }
70     return $schema;
71 }
72
73 sub get_kohastructure {
74     my ($args) = @_;
75     my $filename = $args->{filename};
76     print "Parsing schema for file '$filename'\n";
77     my $translator = SQL::Translator->new();
78     $translator->parser("MySQL");
79     my $schema = $translator->translate($filename);
80     return $schema;
81 }