6   unshift(@INC, $FindBin::Bin . '/../modules/override'); # Use our own versions of various modules (e.g. YAML).
 
   7   push   (@INC, $FindBin::Bin . '/..');
 
  14 use English '-no_match_vars';
 
  25 SL::LxOfficeConf->read;
 
  26 our $lxdebug = LXDebug->new();
 
  40 my ($opt_list, $opt_tree, $opt_rtree, $opt_nodeps, $opt_graphviz, $opt_help);
 
  41 my ($opt_user, $opt_client, $opt_apply, $opt_applied, $opt_unapplied, $opt_format, $opt_test_utf8);
 
  42 my ($opt_dbhost, $opt_dbport, $opt_dbname, $opt_dbuser, $opt_dbpassword, $opt_create, $opt_type);
 
  43 my ($opt_description, @opt_depends, $opt_auth_db);
 
  45 our (%myconfig, $form, $user, $auth, $locale, $controls, $dbupgrader);
 
  48   return $auth if $auth;
 
  50   $auth = SL::Auth->new;
 
  51   if (!$auth->session_tables_present) {
 
  52     $form->error("The session and user management tables are not present in the authentication database. Please use the administration web interface to create them.");
 
  59   my $help_text = <<"END_HELP"
 
  60 dbupgrade2_tool.pl [options]
 
  62   A validation and information tool for the database upgrade scripts
 
  63   in \'sql/Pg-upgrade2\'.
 
  65   At startup dbupgrade2_tool.pl will always check the consistency
 
  66   of all database upgrade scripts (e.g. circular references, invalid
 
  67   formats, missing meta information). You can but don\'t have to specifiy
 
  71     --list               Lists all database upgrade tags
 
  72     --tree               Lists all database upgrades in tree form
 
  73     --rtree              Lists all database upgrades in reverse tree form
 
  74     --graphviz[=file]    Create a Postscript document showing a tree of
 
  75                          all database upgrades and their dependencies.
 
  76                          If no file name is given then the output is
 
  77                          written to \'db_dependencies.png\'.
 
  78     --format=...         Format for the graphviz output. Defaults to
 
  79                          \'png\'. All values that the command \'dot\' accepts
 
  80                          for it\'s option \'-T\' are acceptable.
 
  81     --nodeps             List all database upgrades that no other upgrade
 
  83     --create=tag         Creates a new upgrade with the supplied tag. This
 
  84                          action accepts several optional other options. See
 
  85                          the option section for those. After creating the
 
  86                          upgrade file your \$EDITOR will be called with it.
 
  87     --apply=tag          Applies the database upgrades \'tag\' and all
 
  88                          upgrades it depends on. If \'--apply\' is used
 
  89                          then the option \'--user\' and \'--client\' must be
 
  90                          used as well. Use \'--apply=ALL\' to apply all.
 
  91     --applied            List the applied database upgrades for the
 
  92                          database that the user given with \'--user\' uses.
 
  93     --unapplied          List the database upgrades that haven\'t been applied
 
  94                          yet to the database that the user given with
 
  96     --test-utf8          Tests a PostgreSQL cluster for proper UTF-8 support.
 
  97                          You have to specify the database to test with the
 
  98                          parameters --dbname, --dbhost, --dbport, --dbuser
 
 100     --help               Show this help and exit.
 
 103     --client=id-or-name  The name (or database ID) of the client to use for
 
 104                          database connectivity. You must provide both a client
 
 106     --user=name          The name of the user configuration to use for
 
 107                          database connectivity. You must provide both a client
 
 109     --auth-db            Work on the authentication database instead of a
 
 111     --dbname=name        Database connection options for the UTF-8
 
 112     --dbhost=host        handling test.
 
 117   Options for --create:
 
 118     --type               \'sql\' or \'pl\'. Defaults to sql.
 
 119     --description        The description field of the generated upgrade.
 
 120     --depends            Tags of upgrades which this upgrade depends upon.
 
 121                          Defaults to the latest stable release upgrade.
 
 122                          Multiple values possible.
 
 135 sub calc_rev_depends {
 
 136   map { $_->{rev_depends} = []; } values %{ $controls };
 
 138   foreach my $control (values %{ $controls }) {
 
 139     map { push @{ $controls->{$_}->{rev_depends} }, $control->{tag} } @{ $control->{depends} };
 
 144   my @sorted_controls = $dbupgrader->sort_dbupdate_controls;
 
 146   print "LIST VIEW\n\n" .
 
 147     "number tag depth priority\n";
 
 150   foreach (@sorted_controls) {
 
 151     print "$i $_->{tag} $_->{depth} $_->{priority}\n";
 
 159   my ($tag, $depth) = @_;
 
 161   print " " x $depth . $tag . "\n";
 
 163   foreach my $dep_tag (@{ $controls->{$tag}->{depends} }) {
 
 164     dump_node($dep_tag, $depth + 1);
 
 169   print "TREE VIEW\n\n";
 
 173   my @sorted_controls = $dbupgrader->sort_dbupdate_controls;
 
 175   foreach my $control (@sorted_controls) {
 
 176     dump_node($control->{tag}, "") unless (@{ $control->{rev_depends} });
 
 182 sub dump_node_reverse {
 
 183   my ($tag, $depth) = @_;
 
 185   print " " x $depth . $tag . "\n";
 
 187   foreach my $dep_tag (@{ $controls->{$tag}->{rev_depends} }) {
 
 188     dump_node_reverse($dep_tag, $depth + 1);
 
 192 sub dump_tree_reverse {
 
 193   print "REVERSE TREE VIEW\n\n";
 
 197   my @sorted_controls = $dbupgrader->sort_dbupdate_controls;
 
 199   foreach my $control (@sorted_controls) {
 
 200     last if ($control->{depth} > 1);
 
 201     dump_node_reverse($control->{tag}, "");
 
 210   my $format    = $params{format}    || "png";
 
 211   my $file_name = $params{file_name} || "db_dependencies.${format}";
 
 213   print "GRAPHVIZ OUTPUT -- format: ${format}\n\n";
 
 214   print "Output will be written to '${file_name}'\n";
 
 218   my $dot = "|dot -T${format} ";
 
 219   open OUT, "${dot}> \"${file_name}\"" || die;
 
 222     "digraph db_dependencies {\n" .
 
 223     "graph [size=\"16.53,11.69!\"];\n" .
 
 224     "node [shape=box style=filled fillcolor=white];\n";
 
 227   foreach my $c (values %{ $controls }) {
 
 228     $ranks{$c->{depth}} ||= [];
 
 230     my ($pre, $post) = @{ $c->{rev_depends} } ? ('')x2 :
 
 231       (map "node [fillcolor=$_] ", qw(lightgray white));
 
 233     push @{ $ranks{$c->{"depth"}} }, qq|${pre}"$c->{tag}"; ${post}|;
 
 236   foreach (sort keys %ranks) {
 
 237     print OUT "{ rank = same; ", join("", @{ $ranks{$_} }), " }\n";
 
 240   foreach my $c (values %{ $controls }) {
 
 241     print OUT qq|"$c->{tag}";\n|;
 
 243     foreach my $d (@{ $c->{depends} }) {
 
 244       print OUT qq|"$c->{tag}" -> "$d";\n|;
 
 255   print "SCRIPTS NO OTHER SCRIPTS DEPEND ON\n\n" .
 
 256     join("\n", map { $_->{tag} } grep { !scalar @{ $_->{rev_depends} } } values %{ $controls }) .
 
 263   my $filename    = $params{filename};
 
 264   my $dbupgrader  = $params{dbupgrader};
 
 265   my $type        = $params{type}        || 'sql';
 
 266   my $description = $params{description} || '';
 
 267   my @depends     = @{ $params{depends} };
 
 269   my $encoding    = 'utf-8';
 
 272     my @releases = grep { /^release_/ } keys %$controls;
 
 273     @depends = ((sort @releases)[-1]);
 
 277   if ($type eq 'sql') {
 
 279   } elsif ($type eq 'pl') {
 
 282     die 'Error: No --type was given but is required for --create.';
 
 284     die 'Error: Unknown --type. Try "sql" or "pl".';
 
 287   my $full_filename = $dbupgrader->path . '/' . $filename . '.' . $type;
 
 289   die "file '$full_filename' already exists, aborting" if -f $full_filename;
 
 292   open my $fh, ">:encoding($encoding)", $full_filename or die "can't open $full_filename";
 
 293   print $fh "$comment \@tag: $filename\n";
 
 294   print $fh "$comment \@description: $description\n";
 
 295   print $fh "$comment \@depends: @depends\n";
 
 298     print $fh "package SL::DBUpgrade2::$filename;\n";
 
 300     print $fh "use strict;\n";
 
 301     print $fh "use utf8;\n" if $encoding =~ /utf.?8/i;
 
 303     print $fh "use parent qw(SL::DBUpgrade2::Base);\n";
 
 305     print $fh "sub run {\n";
 
 306     print $fh "  my (\$self) = \@_;\n";
 
 315   print "File $full_filename created.\n";
 
 317   system("\$EDITOR $full_filename");
 
 324   my (@order, %tags, @all_tags);
 
 326   if ($name eq "ALL") {
 
 328     @all_tags = map { $_->{tag} } grep { !@{$_->{rev_depends}} } values %{ $controls };
 
 331     $form->error("Unknown dbupgrade tag '$name'") if (!$controls->{$name});
 
 335   foreach my $tag (@all_tags) {
 
 336     build_upgrade_order($tag, \@order, \%tags);
 
 339   my @upgradescripts = map { $controls->{$_}->{applied} = 0; $controls->{$_} } @order;
 
 341   my $dbh            = $opt_auth_db ? connect_auth()->dbconnect : SL::DB->client->dbh;
 
 343   $dbh->{PrintWarn}  = 0;
 
 344   $dbh->{PrintError} = 0;
 
 346   $user->create_schema_info_table($form, $dbh);
 
 348   my $query = qq|SELECT tag FROM schema_info|;
 
 349   my $sth = $dbh->prepare($query);
 
 350   $sth->execute() || $form->dberror($query);
 
 351   while (my ($tag) = $sth->fetchrow_array()) {
 
 352     $controls->{$tag}->{applied} = 1 if defined $controls->{$tag};
 
 356   @upgradescripts = sort { $a->{priority} <=> $b->{priority} } grep { !$_->{applied} } @upgradescripts;
 
 357   if (!@upgradescripts) {
 
 358     print "The upgrade has already been applied.\n";
 
 362   foreach my $control (@upgradescripts) {
 
 363     $control->{file} =~ /\.(sql|pl)$/;
 
 367     print "Applying upgrade $control->{file}\n";
 
 368     $dbupgrader->process_file($dbh, "sql/Pg-upgrade2/$control->{file}", $control);
 
 371   $dbh->disconnect unless $opt_auth_db;
 
 374 sub dump_sql_result {
 
 375   my ($results, $column_order) = @_;
 
 377   my %column_lengths = map { $_, length $_ } keys %{ $results->[0] };
 
 379   foreach my $row (@{ $results }) {
 
 380     map { $column_lengths{$_} = length $row->{$_} if (length $row->{$_} > $column_lengths{$_}) } keys %{ $row };
 
 384   if ($column_order && scalar @{ $column_order }) {
 
 385     @sorted_names = @{ $column_order };
 
 387     @sorted_names = sort keys %column_lengths;
 
 390   my $format       = join('|', map { '%-' . $column_lengths{$_} . 's' } @sorted_names) . "\n";
 
 392   printf $format, @sorted_names;
 
 393   print  join('+', map { '-' x $column_lengths{$_} } @sorted_names) . "\n";
 
 395   foreach my $row (@{ $results }) {
 
 396     printf $format, map { $row->{$_} } @sorted_names;
 
 398   printf "(\%d row\%s)\n", scalar @{ $results }, scalar @{ $results } > 1 ? 's' : '';
 
 404   my $dbh            = $opt_auth_db ? connect_auth()->dbconnect : SL::DB->client->dbh;
 
 405   $dbh->{AutoCommit} = 0;
 
 407   $dbh->{PrintWarn}  = 0;
 
 408   $dbh->{PrintError} = 0;
 
 410   $user->create_schema_info_table($form, $dbh);
 
 412   my $query = qq|SELECT tag, login, itime FROM schema_info ORDER BY itime|;
 
 413   my $sth = $dbh->prepare($query);
 
 414   $sth->execute() || $form->dberror($query);
 
 415   while (my $ref = $sth->fetchrow_hashref()) {
 
 420   $dbh->disconnect unless $opt_auth_db;
 
 422   if (!scalar @results) {
 
 423     print "No database upgrades have been applied yet.\n";
 
 425     dump_sql_result(\@results, [qw(tag login itime)]);
 
 432   my $dbh = $opt_auth_db ? connect_auth()->dbconnect : SL::DB->client->dbh;
 
 434   $dbh->{PrintWarn}  = 0;
 
 435   $dbh->{PrintError} = 0;
 
 437   my @unapplied = $dbupgrader->unapplied_upgrade_scripts($dbh);
 
 439   $dbh->disconnect unless $opt_auth_db;
 
 441   if (!scalar @unapplied) {
 
 442     print "All database upgrades have been applied.\n";
 
 444     print map { $_->{tag} . "\n" } @unapplied;
 
 448 sub build_upgrade_order {
 
 453   my $control = $controls->{$name};
 
 455   foreach my $dependency (@{ $control->{depends} }) {
 
 456     next if $tags->{$dependency};
 
 457     $tags->{$dependency} = 1;
 
 458     build_upgrade_order($dependency, $order, $tags);
 
 461   push @{ $order }, $name;
 
 469 $locale    = Locale->new;
 
 471 $::request = SL::Request->new(
 
 473   layout => SL::Layout::None->new,
 
 480 GetOptions("list"         => \$opt_list,
 
 481            "tree"         => \$opt_tree,
 
 482            "rtree"        => \$opt_rtree,
 
 483            "nodeps"       => \$opt_nodeps,
 
 484            "graphviz:s"   => \$opt_graphviz,
 
 485            "format:s"     => \$opt_format,
 
 486            "user=s"       => \$opt_user,
 
 487            "client=s"     => \$opt_client,
 
 488            "apply=s"      => \$opt_apply,
 
 489            "applied"      => \$opt_applied,
 
 490            "create=s"     => \$opt_create,
 
 491            "type=s"       => \$opt_type,
 
 492            "description=s" => \$opt_description,
 
 493            "depends=s"    => \@opt_depends,
 
 494            "unapplied"    => \$opt_unapplied,
 
 495            "test-utf8"    => \$opt_test_utf8,
 
 496            "dbhost:s"     => \$opt_dbhost,
 
 497            "dbport:s"     => \$opt_dbport,
 
 498            "dbname:s"     => \$opt_dbname,
 
 499            "dbuser:s"     => \$opt_dbuser,
 
 500            "dbpassword:s" => \$opt_dbpassword,
 
 501            "auth-db"      => \$opt_auth_db,
 
 502            "help"         => \$opt_help,
 
 505 show_help() if ($opt_help);
 
 507 $dbupgrader = SL::DBUpgrade2->new(form => $form, auth => $opt_auth_db);
 
 508 $controls   = $dbupgrader->parse_dbupdate_controls->{all_controls};
 
 510 dump_list()                                 if ($opt_list);
 
 511 dump_tree()                                 if ($opt_tree);
 
 512 dump_tree_reverse()                         if ($opt_rtree);
 
 513 dump_graphviz('file_name' => $opt_graphviz,
 
 514               'format'    => $opt_format)   if (defined $opt_graphviz);
 
 515 dump_nodeps()                               if ($opt_nodeps);
 
 516 create_upgrade(filename   => $opt_create,
 
 517                dbupgrader  => $dbupgrader,
 
 519                description => $opt_description,
 
 520                depends     => \@opt_depends) if ($opt_create);
 
 522 if ($opt_client && !connect_auth()->set_client($opt_client)) {
 
 523   $form->error($form->format_string("The client '#1' does not exist.", $opt_client));
 
 527   $form->error("Need a client, too.") if !$auth || !$auth->client;
 
 529   %myconfig = connect_auth()->read_user(login => $opt_user);
 
 531   if (!$myconfig{login}) {
 
 532     $form->error($form->format_string("The user '#1' does not exist.", $opt_user));
 
 535   $locale = new Locale($myconfig{countrycode}, "all");
 
 536   $user   = new User(login => $opt_user);
 
 538   map { $form->{$_} = $myconfig{$_} } keys %myconfig;
 
 542   $form->error("--apply used but no user name given with --user.") if !$user && !$opt_auth_db;
 
 543   apply_upgrade($opt_apply);
 
 547   $form->error("--applied used but no user name given with --user.") if !$user && !$opt_auth_db;
 
 551 if ($opt_unapplied) {
 
 552   $form->error("--unapplied used but no user name given with --user.") if !$user && !$opt_auth_db;
 
 557 if ($opt_test_utf8) {
 
 558   $form->error("--test-utf8 used but no database name given with --dbname.") if (!$opt_dbname);
 
 560   my $umlaut_upper       = 'Ä';
 
 562   my $dbconnect          = "dbi:Pg:dbname=${opt_dbname}";
 
 563   $dbconnect            .= ";host=${opt_dbhost}" if ($opt_dbhost);
 
 564   $dbconnect            .= ";port=${opt_dbport}" if ($opt_dbport);
 
 566   my $dbh                = DBI->connect($dbconnect, $opt_dbuser, $opt_dbpassword, { pg_enable_utf8 => 1 });
 
 568   $form->error("UTF-8 test: Database connect failed (" . $DBI::errstr . ")") if (!$dbh);
 
 570   my ($umlaut_lower) = $dbh->selectrow_array(qq|SELECT lower(?)|, undef, $umlaut_upper);
 
 574   if ($umlaut_lower eq 'ä') {
 
 575     print "UTF-8 test was successful.\n";
 
 576   } elsif ($umlaut_lower eq 'Ä') {
 
 577     print "UTF-8 test was NOT successful: Umlauts are not modified (this might be partially ok, but you should probably not use UTF-8 on this cluster).\n";
 
 579     print "UTF-8 test was NOT successful: Umlauts are destroyed. Do not use UTF-8 on this cluster.\n";