1 package SL::DBUpgrade2;
 
   4 use List::MoreUtils qw(any);
 
   7 use SL::DBUpgrade2::Base;
 
  16   return bless({}, $package)->init(@_);
 
  20   my ($self, %params) = @_;
 
  23     $params{path_suffix} = "-auth";
 
  24     $params{schema}      = "auth.";
 
  27   $params{path_suffix} ||= '';
 
  28   $params{schema}      ||= '';
 
  29   $params{path}          = "sql/" . $params{dbdriver} . "-upgrade2" . $params{path_suffix};
 
  31   map { $self->{$_} = $params{$_} } keys %params;
 
  40 sub parse_dbupdate_controls {
 
  41   $::lxdebug->enter_sub();
 
  45   my $form   = $self->{form};
 
  46   my $locale = $::locale;
 
  51   my $path = $self->path;
 
  53   foreach my $file_name (<$path/*.sql>, <$path/*.pl>) {
 
  54     next unless (open(IN, $file_name));
 
  56     my $file = $file_name;
 
  66       next unless (/^(--|\#)\s*\@/);
 
  71       my @fields = split(/\s*:\s*/, $_, 2);
 
  72       next unless (scalar(@fields) == 2);
 
  74       if ($fields[0] eq "depends") {
 
  75         push(@{$control->{"depends"}}, split(/\s+/, $fields[1]));
 
  77         $control->{$fields[0]} = $fields[1];
 
  81     next if ($control->{ignore});
 
  83     $control->{charset} = 'UTF-8' if $file =~ m/\.pl$/;
 
  84     $control->{charset} = $control->{charset} || $control->{encoding} || Common::DEFAULT_CHARSET;
 
  86     if (!$control->{"tag"}) {
 
  87       _control_error($form, $file_name, $locale->text("Missing 'tag' field.")) ;
 
  90     if ($control->{"tag"} =~ /[^a-zA-Z0-9_\(\)\-]/) {
 
  91       _control_error($form, $file_name, $locale->text("The 'tag' field must only consist of alphanumeric characters or the carachters - _ ( )"))
 
  94     if (defined($all_controls{$control->{"tag"}})) {
 
  95       _control_error($form, $file_name, sprintf($locale->text("More than one control file with the tag '%s' exist."), $control->{"tag"}))
 
  98     if (!$control->{"description"}) {
 
  99       _control_error($form, $file_name, sprintf($locale->text("Missing 'description' field."))) ;
 
 102     $control->{"priority"}  *= 1;
 
 103     $control->{"priority"} ||= 1000;
 
 104     $control->{"file"}       = $file;
 
 106     delete @{$control}{qw(depth applied)};
 
 108     $all_controls{$control->{"tag"}} = $control;
 
 113   foreach my $control (values(%all_controls)) {
 
 114     foreach my $dependency (@{$control->{"depends"}}) {
 
 115       _control_error($form, $control->{"file"}, sprintf($locale->text("Unknown dependency '%s'."), $dependency)) if (!defined($all_controls{$dependency}));
 
 118     map({ $_->{"loop"} = 0; } values(%all_controls));
 
 119     _check_for_loops($form, $control->{"file"}, \%all_controls, $control->{"tag"});
 
 122   map({ _dbupdate2_calculate_depth(\%all_controls, $_->{"tag"}) }
 
 123       values(%all_controls));
 
 125   $self->{all_controls} = \%all_controls;
 
 127   $::lxdebug->leave_sub();
 
 133   $::lxdebug->enter_sub();
 
 135   my ($self, $dbh, $filename, $version_or_control, $db_charset) = @_;
 
 137   my $form  = $self->{form};
 
 138   my $fh    = IO::File->new($filename, "r") or $form->error("$filename : $!\n");
 
 143   my $file_charset = Common::DEFAULT_CHARSET;
 
 146     next if !/^--\s*\@(?:charset|encoding):\s*(.+)/;
 
 150   $fh->seek(0, SEEK_SET);
 
 152   $db_charset ||= Common::DEFAULT_CHARSET;
 
 157     $_ = SL::Iconv::convert($file_charset, $db_charset, $_);
 
 159     # Remove DOS and Unix style line endings.
 
 165     for (my $i = 0; $i < length($_); $i++) {
 
 166       my $char = substr($_, $i, 1);
 
 168       # Are we inside a string?
 
 170         if ($char eq $quote_chars[-1]) {
 
 172         } elsif (length $quote_chars[-1] > 1
 
 173              &&  substr($_, $i, length $quote_chars[-1]) eq $quote_chars[-1]) {
 
 174           $i   += length($quote_chars[-1]) - 1;
 
 175           $char = $quote_chars[-1];
 
 182         if (($char eq "'") || ($char eq "\"")) {
 
 183           push(@quote_chars, $char);
 
 185         } elsif ($char eq '$'                                            # start of dollar quoting
 
 186              && ($tag_end  = index($_, '$', $i + 1)) > -1                # ends on same line
 
 187              && (do { $tag = substr($_, $i + 1, $tag_end - $i - 1); 1 }) # extract tag
 
 188              &&  $tag      =~ /^ (?= [A-Za-z_] [A-Za-z0-9_]* | ) $/x) {  # tag is identifier
 
 189           push @quote_chars, $char = '$' . $tag . '$';
 
 191         } elsif ($char eq ";") {
 
 193           # Query is complete. Send it.
 
 195           $sth = $dbh->prepare($query);
 
 196           if (!$sth->execute()) {
 
 197             my $errstr = $dbh->errstr;
 
 200             $form->dberror("The database update/creation did not succeed. " .
 
 201                            "The file ${filename} containing the following " .
 
 202                            "query failed:<br>${query}<br>" .
 
 203                            "The error message was: ${errstr}<br>" .
 
 204                            "All changes in that file have been reverted.");
 
 216     # Insert a space at the end of each line so that queries split
 
 217     # over multiple lines work properly.
 
 219       $query .= @quote_chars ? "\n" : ' ';
 
 223   if (ref($version_or_control) eq "HASH") {
 
 224     $dbh->do("INSERT INTO " . $self->{schema} . "schema_info (tag, login) VALUES (" . $dbh->quote($version_or_control->{"tag"}) . ", " . $dbh->quote($form->{"login"}) . ")");
 
 225   } elsif ($version_or_control) {
 
 226     $dbh->do("UPDATE defaults SET version = " . $dbh->quote($version_or_control));
 
 232   $::lxdebug->leave_sub();
 
 235 # Process a Perl script which updates the database.
 
 236 # If the script returns 1 then the update was successful.
 
 237 # Return code "2" means "needs more interaction; remove
 
 238 # users/nologin and end current request".
 
 239 # All other return codes are fatal errors.
 
 240 sub process_perl_script {
 
 241   $::lxdebug->enter_sub();
 
 243   my ($self, $dbh, $filename, $version_or_control, $db_charset) = @_;
 
 247   # setup dbup_ export vars & run script
 
 248   my %dbup_myconfig = map { ($_ => $::form->{$_}) } qw(dbname dbuser dbpasswd dbhost dbport dbconnect);
 
 249   my $result        = SL::DBUpgrade2::Base::execute_script(
 
 250     file_name => $filename,
 
 251     tag       => $version_or_control->{tag},
 
 253     myconfig  => \%dbup_myconfig,
 
 256   if (1 != ($result // 1)) {
 
 260   if (!defined($result)) {
 
 261     print $::form->parse_html_template("dbupgrade/error", { file  => $filename, error => $@ });
 
 263   } elsif (1 != $result) {
 
 264     unlink("users/nologin") if (2 == $result);
 
 268   if (ref($version_or_control) eq "HASH") {
 
 269     $dbh->do("INSERT INTO " . $self->{schema} . "schema_info (tag, login) VALUES (" . $dbh->quote($version_or_control->{tag}) . ", " . $dbh->quote($::form->{login}) . ")");
 
 270   } elsif ($version_or_control) {
 
 271     $dbh->do("UPDATE defaults SET version = " . $dbh->quote($version_or_control));
 
 275   $::lxdebug->leave_sub();
 
 279   my ($self, $dbh, $filename, $version_or_control, $db_charset) = @_;
 
 281   if ($filename =~ m/sql$/) {
 
 282     $self->process_query($dbh, $filename, $version_or_control, $db_charset);
 
 284     $self->process_perl_script($dbh, $filename, $version_or_control, $db_charset);
 
 288 sub update_available {
 
 289   my ($self, $cur_version) = @_;
 
 293   my $dbdriver = $self->{dbdriver};
 
 294   opendir SQLDIR, "sql/${dbdriver}-upgrade" || error("", "sql/${dbdriver}-upgrade: $!");
 
 295   my @upgradescripts = grep /${dbdriver}-upgrade-\Q$cur_version\E.*\.(sql|pl)$/, readdir SQLDIR;
 
 298   return ($#upgradescripts > -1);
 
 301 sub update2_available {
 
 302   $::lxdebug->enter_sub();
 
 304   my ($self, $dbh) = @_;
 
 306   map { $_->{applied} = 0; } values %{ $self->{all_controls} };
 
 308   my $sth = $dbh->prepare(qq|SELECT tag FROM | . $self->{schema} . qq|schema_info|);
 
 310     while (my ($tag) = $sth->fetchrow_array) {
 
 311       $self->{all_controls}->{$tag}->{applied} = 1 if defined $self->{all_controls}->{$tag};
 
 316   my $needs_update = any { !$_->{applied} } values %{ $self->{all_controls} };
 
 318   $::lxdebug->leave_sub();
 
 320   return $needs_update;
 
 323 sub unapplied_upgrade_scripts {
 
 324   my ($self, $dbh) = @_;
 
 326   my @all_scripts = map { $_->{applied} = 0; $_ } $self->sort_dbupdate_controls;
 
 328   my $query = qq|SELECT tag FROM | . $self->{schema} . qq|schema_info|;
 
 329   my $sth   = $dbh->prepare($query);
 
 330   $sth->execute || $self->{form}->dberror($query);
 
 331   while (my ($tag) = $sth->fetchrow_array()) {
 
 332     $self->{all_controls}->{$tag}->{applied} = 1 if defined $self->{all_controls}->{$tag};
 
 336   return grep { !$_->{applied} } @all_scripts;
 
 339 sub apply_admin_dbupgrade_scripts {
 
 340   my ($self, $called_from_admin) = @_;
 
 342   return 0 if !$self->{auth};
 
 344   my $dbh               = $::auth->dbconnect;
 
 345   my @unapplied_scripts = $self->unapplied_upgrade_scripts($dbh);
 
 347   return 0 if !@unapplied_scripts;
 
 349   my $db_charset           = $::lx_office_conf{system}->{dbcharset} || Common::DEFAULT_CHARSET;
 
 350   $self->{form}->{login} ||= 'admin';
 
 352   map { $_->{description} = SL::Iconv::convert($_->{charset}, $db_charset, $_->{description}) } values %{ $self->{all_controls} };
 
 354   if ($called_from_admin) {
 
 355     $self->{form}->{title} = $::locale->text('Dataset upgrade');
 
 356     $self->{form}->header;
 
 359   print $self->{form}->parse_html_template("dbupgrade/header", { dbname => $::auth->{DB_config}->{db} });
 
 361   foreach my $control (@unapplied_scripts) {
 
 362     $::lxdebug->message(LXDebug->DEBUG2(), "Applying Update $control->{file}");
 
 363     print $self->{form}->parse_html_template("dbupgrade/upgrade_message2", $control);
 
 365     $self->process_file($dbh, "sql/$self->{dbdriver}-upgrade2-auth/$control->{file}", $control, $db_charset);
 
 368   print $self->{form}->parse_html_template("dbupgrade/footer", { is_admin => 1 }) if $called_from_admin;
 
 373 sub _check_for_loops {
 
 374   my ($form, $file_name, $controls, $tag, @path) = @_;
 
 378   my $ctrl = $controls->{$tag};
 
 380   if ($ctrl->{"loop"} == 1) {
 
 382     _control_error($form, $file_name, $::locale->text("Dependency loop detected:") . " " . join(" -> ", @path))
 
 384   } elsif ($ctrl->{"loop"} == 0) {
 
 387     map({ _check_for_loops($form, $file_name, $controls, $_, @path); } @{ $ctrl->{"depends"} });
 
 393   my ($form, $file_name, $message) = @_;
 
 396   my $locale = $::locale;
 
 398   $form->error(sprintf($locale->text("Error in database control file '%s': %s"), $file_name, $message));
 
 401 sub _dbupdate2_calculate_depth {
 
 402   $::lxdebug->enter_sub(2);
 
 404   my ($tree, $tag) = @_;
 
 406   my $node = $tree->{$tag};
 
 408   return $::lxdebug->leave_sub(2) if (defined($node->{"depth"}));
 
 412   foreach $tag (@{$node->{"depends"}}) {
 
 413     _dbupdate2_calculate_depth($tree, $tag);
 
 414     my $value = $tree->{$tag}->{"depth"};
 
 415     $max_depth = $value if ($value > $max_depth);
 
 418   $node->{"depth"} = $max_depth + 1;
 
 420   $::lxdebug->leave_sub(2);
 
 423 sub sort_dbupdate_controls {
 
 426   $self->parse_dbupdate_controls unless $self->{all_controls};
 
 428   return sort { ($a->{depth} <=> $b->{depth}) || ($a->{priority} <=> $b->{priority}) || ($a->{tag} cmp $b->{tag}) } values %{ $self->{all_controls} };
 
 440 SL::DBUpgrade2 - Parse database upgrade files stored in
 
 441 C<sql/Pg-upgrade2> and C<sql/Pg-upgrade2-auth> (and also in
 
 449   # Apply outstanding updates to the authentication database
 
 450   my $scripts = SL::DBUpgrade2->new(
 
 455   $scripts->apply_admin_dbupgrade_scripts(1);
 
 457   # Apply updates to a user database
 
 458   my $scripts = SL::DBUpgrade2->new(
 
 460     dbdriver => $::form->{dbdriver},
 
 463   User->dbupdate2($form, $scripts->parse_dbupdate_controls);
 
 467 Database upgrade files are used to upgrade the database structure and
 
 468 content of both the authentication database and the user
 
 469 databases. They're applied when a user logs in. As long as the
 
 470 authentication database is not up to date users cannot log in in
 
 471 general, and the admin has to log in first in order to get his
 
 474 Database scripts form a tree by specifying which upgrade file depends
 
 475 on which other upgrade file. This means that such files are always
 
 476 applied in a well-defined order.
 
 478 Each script is run in a separate transaction. If a script fails the
 
 479 current transaction is rolled back and the whole upgrade process is
 
 480 stopped. The user/admin is required to fix the issue manually.
 
 482 A list of applied upgrade scripts is maintained in a table called
 
 483 C<schema_info> for the user database and C<auth.schema_info>) for the
 
 484 authentication database. They contain the tags, the login name of the
 
 485 user having applied the script and the timestamp when the script was
 
 488 Database upgrade files come in two flavours: SQL files and Perl
 
 489 files. For both there are control fields that determine the order in
 
 490 which they're executed, what charset the scripts are written in
 
 491 etc. The control fields are tag/value pairs contained in comments.
 
 493 =head1 OLD UPGRADE FILES
 
 495 The files in C<sql/Pg-upgrade> are so old that I don't bother
 
 496 documenting them. They're handled by this class, too, but new files
 
 497 are only created as C<Pg-upgrade2> files.
 
 499 =head1 CONTROL FIELDS
 
 503 Control fields for Perl files:
 
 506   # @tag2: some more values
 
 511 Control fields for SQL files:
 
 514   -- @tag2: some more values
 
 517 =head2 TAGS AND THEIR MEANING
 
 519 The following tags are recognized:
 
 525 The name for this file. The C<tag> is also used for dependency
 
 526 resolution (see C<depends>).
 
 532 A description presented to the user when the update is applied.
 
 538 A space-separated list of tags of scripts this particular script
 
 539 depends on. All other upgrades listed in C<depends> will be applied
 
 540 before the current one is applied.
 
 545 The charset this file uses. Defaults to C<ISO-8859-15> if
 
 546 missing. Both terms are recognized.
 
 550 Ordering the scripts by their dependencies alone produces a lot of
 
 551 groups of scripts that could be applied at the same time (e.g. if both
 
 552 B and C depend only on A then B could be applied before C or the other
 
 553 way around). This field determines the order inside such a
 
 554 group. Scripts with lower priority fields are executed before scripts
 
 555 with higher priority fields.
 
 557 If two scripts have equal priorities then their tag name decides.
 
 559 The priority defaults to 1000.
 
 567 =item C<apply_admin_dbupgrade_scripts $called_from_admin>
 
 569 Applies all unapplied upgrade files to the authentication/admin
 
 570 database. The parameter C<$called_from_admin> should be truish if the
 
 571 function is called from the web interface and falsish if it's called
 
 572 from e.g. a command line script like C<scripts/dbupgrade2_tool.pl>.
 
 574 =item C<init %params>
 
 576 Initializes the object. Is called directly from L<new> and should not
 
 581 Creates a new object. Possible parameters are:
 
 587 Path to the upgrade files to parse. Required.
 
 591 C<SL::Form> object to use. Required.
 
 595 Name of the database driver. Currently only C<Pg> for PostgreSQL is
 
 600 Optional parameter defaulting to 0. If trueish then the scripts read
 
 601 are the ones applying to the authentication database.
 
 605 =item C<parse_dbupdate_controls>
 
 607 Parses all files located in C<path> (see L<new>), ananlyzes their
 
 608 control fields, builds the tree, and signals errors if control fields
 
 609 are missing/wrong (e.g. a tag name listed in C<depends> is not
 
 610 found). Sets C<$Self->{all_controls}> to the list of database
 
 613 =item C<process_file $dbh, $filename, $version_or_control, $db_charset>
 
 615 Applies a single database upgrade file. Calls L<process_perl_script>
 
 616 for Perl update files and C<process_query> for SQL update
 
 617 files. Requires an open database handle(C<$dbh>), the file name
 
 618 (C<$filename>), a hash structure of the file's control fields as
 
 619 produced by L<parse_dbupdate_controls> (C<$version_or_control>) and
 
 620 the database charset (for on-the-fly charset recoding of the script if
 
 621 required, C<$db_charset>).
 
 623 Returns the result of the actual function called.
 
 625 =item C<process_perl_script $dbh, $filename, $version_or_control, $db_charset>
 
 627 Applies a single Perl database upgrade file. Requires an open database
 
 628 handle(C<$dbh>), the file name (C<$filename>), a hash structure of the
 
 629 file's control fields as produced by L<parse_dbupdate_controls>
 
 630 (C<$version_or_control>) and the database charset (for on-the-fly
 
 631 charset recoding of the script if required, C<$db_charset>).
 
 633 Perl scripts are executed via L<eval>. If L<eval> returns falsish then
 
 634 an error is expected. There are two special return values: If the
 
 635 script returns C<1> then the update was successful. Return code C<2>
 
 636 means "needs more interaction from the user; remove users/nologin and
 
 637 end current upgrade process". All other return codes are fatal errors.
 
 639 Inside the Perl script several local variables exist that can be used:
 
 645 A locale object for translating messages
 
 649 The database handle (inside a transaction).
 
 653 The global C<SL::Form> object.
 
 657 A Perl script can actually implement queries that fail while
 
 658 continueing the process by handling the transaction itself, e.g. with
 
 659 the following function:
 
 662     my ($query, $may_fail) = @_;
 
 664     if (!$dbh->do($query)) {
 
 665       die($dbup_locale->text("Database update error:") . "<br>$msg<br>" . $DBI::errstr) unless $may_fail;
 
 671 =item C<process_query $dbh, $filename, $version_or_control, $db_charset>
 
 673 Applies a single SQL database upgrade file. Requires an open database
 
 674 handle(C<$dbh>), the file name (C<$filename>), a hash structure of the
 
 675 ofile's control fields as produced by L<parse_dbupdate_controls>
 
 676 (C<$version_or_control>) and the database charset (for on-the-fly
 
 677 charset recoding of the script if required, C<$db_charset>).
 
 679 =item C<sort_dbupdate_controls>
 
 681 Sorts the database upgrade scripts according to their C<tag> and
 
 682 C<priority> control fields. Returns a list of their hash
 
 683 representations that can be applied in order.
 
 685 =item C<unapplied_upgrade_scripts $dbh>
 
 687 Returns a list if upgrade scripts (their internal hash representation)
 
 688 that haven't been applied to a database yet. C<$dbh> is an open handle
 
 689 to the database that is checked.
 
 691 Requires that the scripts have been parsed.
 
 693 =item C<update2_available $dbh>
 
 695 Returns trueish if at least one upgrade script hasn't been applied to
 
 696 a database yet. C<$dbh> is an open handle to the database that is
 
 699 Requires that the scripts have been parsed.
 
 709 Moritz Bunkus E<lt>m.bunkus@linet-services.deE<gt>