epic-s6ts
[kivitendo-erp.git] / SL / DBUpgrade2.pm
index eba336f..0b14eca 100644 (file)
@@ -7,7 +7,7 @@ use List::MoreUtils qw(any);
 use SL::Common;
 use SL::DBUpgrade2::Base;
 use SL::DBUtils;
-use SL::Iconv;
+use SL::System::Process;
 
 use strict;
 
@@ -27,7 +27,7 @@ sub init {
 
   $params{path_suffix} ||= '';
   $params{schema}      ||= '';
-  $params{path}          = "sql/Pg-upgrade2" . $params{path_suffix};
+  $params{path}        ||= SL::System::Process->exe_dir . "/sql/Pg-upgrade2" . $params{path_suffix};
 
   map { $self->{$_} = $params{$_} } keys %params;
 
@@ -39,8 +39,6 @@ sub path {
 }
 
 sub parse_dbupdate_controls {
-  $::lxdebug->enter_sub();
-
   my ($self) = @_;
 
   my $form   = $self->{form};
@@ -52,14 +50,16 @@ sub parse_dbupdate_controls {
   my $path = $self->path;
 
   foreach my $file_name (<$path/*.sql>, <$path/*.pl>) {
-    next unless (open(IN, $file_name));
+    next unless (open(IN, "<:encoding(UTF-8)", $file_name));
 
     my $file = $file_name;
     $file =~ s|.*/||;
 
     my $control = {
-      "priority" => 1000,
-      "depends"  => [],
+      priority    => 1000,
+      depends     => [],
+      required_by => [],
+      locales     => [],
     };
 
     while (<IN>) {
@@ -72,8 +72,10 @@ sub parse_dbupdate_controls {
       my @fields = split(/\s*:\s*/, $_, 2);
       next unless (scalar(@fields) == 2);
 
-      if ($fields[0] eq "depends") {
-        push(@{$control->{"depends"}}, split(/\s+/, $fields[1]));
+      if ($fields[0] =~ m{^(?:depends|required_by)$}) {
+        push(@{$control->{$fields[0]}}, split(/\s+/, $fields[1]));
+      } elsif ($fields[0] eq "locales") {
+        push @{$control->{locales}}, $fields[1];
       } else {
         $control->{$fields[0]} = $fields[1];
       }
@@ -97,17 +99,31 @@ sub parse_dbupdate_controls {
       _control_error($form, $file_name, sprintf($locale->text("Missing 'description' field."))) ;
     }
 
+    delete @{$control}{qw(depth applied)};
+
+    my @unknown_keys = grep { !m{^ (?: depends | required_by | description | file | ignore | locales | may_fail | priority | superuser_privileges | tag ) $}x } keys %{ $control };
+    if (@unknown_keys) {
+      _control_error($form, $file_name, sprintf($locale->text("Unknown control fields: #1", join(' ', sort({ lc $a cmp lc $b } @unknown_keys)))));
+    }
+
     $control->{"priority"}  *= 1;
     $control->{"priority"} ||= 1000;
     $control->{"file"}       = $file;
 
-    delete @{$control}{qw(depth applied)};
-
     $all_controls{$control->{"tag"}} = $control;
 
     close(IN);
   }
 
+  foreach my $name (keys %all_controls) {
+    my $control = $all_controls{$name};
+
+    foreach my $dependency (@{ delete $control->{required_by} }) {
+      _control_error($form, $control->{"file"}, sprintf($locale->text("Unknown dependency '%s'."), $dependency)) if (!defined($all_controls{$dependency}));
+      push @{ $all_controls{$dependency}->{depends} }, $name;
+    }
+  }
+
   foreach my $control (values(%all_controls)) {
     foreach my $dependency (@{$control->{"depends"}}) {
       _control_error($form, $control->{"file"}, sprintf($locale->text("Unknown dependency '%s'."), $dependency)) if (!defined($all_controls{$dependency}));
@@ -122,8 +138,6 @@ sub parse_dbupdate_controls {
 
   $self->{all_controls} = \%all_controls;
 
-  $::lxdebug->leave_sub();
-
   return $self;
 }
 
@@ -133,7 +147,7 @@ sub process_query {
   my ($self, $dbh, $filename, $version_or_control) = @_;
 
   my $form  = $self->{form};
-  my $fh    = IO::File->new($filename, "r");
+  my $fh    = IO::File->new($filename, "<:encoding(UTF-8)");
   my $query = "";
   my $sth;
   my @quote_chars;
@@ -146,14 +160,9 @@ sub process_query {
   $dbh->begin_work();
 
   while (<$fh>) {
-    $_ = SL::Iconv::convert('UTF-8', 'UTF-8', $_);
-
     # Remove DOS and Unix style line endings.
     chomp;
 
-    # remove comments
-    s/--.*$//;
-
     for (my $i = 0; $i < length($_); $i++) {
       my $char = substr($_, $i, 1);
 
@@ -180,6 +189,11 @@ sub process_query {
              &&  $tag      =~ /^ (?= [A-Za-z_] [A-Za-z0-9_]* | ) $/x) {  # tag is identifier
           push @quote_chars, $char = '$' . $tag . '$';
           $i = $tag_end;
+        } elsif ($char eq "-") {
+          if ( substr($_, $i+1, 1) eq "-") {
+            # found a comment outside quote
+            last;
+          }
         } elsif ($char eq ";") {
 
           # Query is complete. Send it.
@@ -190,11 +204,13 @@ sub process_query {
             return $errstr // '<unknown database error>' if $self->{return_on_error};
             $sth->finish();
             $dbh->rollback();
-            $form->dberror("The database update/creation did not succeed. " .
-                           "The file ${filename} containing the following " .
-                           "query failed:<br>${query}<br>" .
-                           "The error message was: ${errstr}<br>" .
-                           "All changes in that file have been reverted.");
+            if (!ref $version_or_control || ref $version_or_control ne 'HASH' || !$version_or_control->{may_fail})  {
+              $form->dberror("The database update/creation did not succeed. " .
+                             "The file ${filename} containing the following " .
+                             "query failed:<br>${query}<br>" .
+                             "The error message was: ${errstr}<br>" .
+                             "All changes in that file have been reverted.")
+            }
           }
           $sth->finish();
 
@@ -238,7 +254,7 @@ sub process_perl_script {
 
   my ($self, $dbh, $filename, $version_or_control) = @_;
 
-  my %form_values = map { $_ => $::form->{$_} } qw(dbconnect dbdefault dbhost dbmbkiviunstable dbname dboptions dbpasswd dbport dbupdate dbuser login template_object version);
+  my %form_values = %$::form;
 
   $dbh->begin_work;
 
@@ -261,10 +277,10 @@ sub process_perl_script {
 
   if (!defined($result)) {
     print $::form->parse_html_template("dbupgrade/error", { file  => $filename, error => $error });
-    ::end_of_request();
+    $::dispatcher->end_request;
   } elsif (1 != $result) {
     SL::System::InstallationLock->unlock if 2 == $result;
-    ::end_of_request();
+    $::dispatcher->end_request;
   }
 
   if (ref($version_or_control) eq "HASH") {
@@ -290,30 +306,12 @@ sub process_perl_script {
 sub process_file {
   my ($self, $dbh, $filename, $version_or_control) = @_;
 
-  return $filename =~ m/sql$/ ? $self->process_query(      $dbh, $filename, $version_or_control)
-                              : $self->process_perl_script($dbh, $filename, $version_or_control);
-}
-
-sub update2_available {
-  $::lxdebug->enter_sub();
-
-  my ($self, $dbh) = @_;
-
-  map { $_->{applied} = 0; } values %{ $self->{all_controls} };
+  my $result = $filename =~ m/sql$/ ? $self->process_query(      $dbh, $filename, $version_or_control)
+                                    : $self->process_perl_script($dbh, $filename, $version_or_control);
 
-  my $sth = $dbh->prepare(qq|SELECT tag FROM | . $self->{schema} . qq|schema_info|);
-  if ($sth->execute) {
-    while (my ($tag) = $sth->fetchrow_array) {
-      $self->{all_controls}->{$tag}->{applied} = 1 if defined $self->{all_controls}->{$tag};
-    }
-  }
-  $sth->finish();
-
-  my $needs_update = any { !$_->{applied} } values %{ $self->{all_controls} };
-
-  $::lxdebug->leave_sub();
+  $::lxdebug->log_time("DB upgrade script '${filename}' finished");
 
-  return $needs_update;
+  return $result;
 }
 
 sub unapplied_upgrade_scripts {
@@ -344,8 +342,6 @@ sub apply_admin_dbupgrade_scripts {
 
   $self->{form}->{login} ||= 'admin';
 
-  map { $_->{description} = SL::Iconv::convert('UTF-8', 'UTF-8', $_->{description}) } values %{ $self->{all_controls} };
-
   if ($called_from_admin) {
     $self->{form}->{title} = $::locale->text('Dataset upgrade');
     $self->{form}->header;
@@ -353,6 +349,8 @@ sub apply_admin_dbupgrade_scripts {
 
   print $self->{form}->parse_html_template("dbupgrade/header", { dbname => $::auth->{DB_config}->{db} });
 
+  $::lxdebug->log_time("DB upgrades commencing");
+
   foreach my $control (@unapplied_scripts) {
     $::lxdebug->message(LXDebug->DEBUG2(), "Applying Update $control->{file}");
     print $self->{form}->parse_html_template("dbupgrade/upgrade_message2", $control);
@@ -360,6 +358,8 @@ sub apply_admin_dbupgrade_scripts {
     $self->process_file($dbh, "sql/Pg-upgrade2-auth/$control->{file}", $control);
   }
 
+  $::lxdebug->log_time("DB upgrades finished");
+
   print $self->{form}->parse_html_template("dbupgrade/footer", { is_admin => 1 }) if $called_from_admin;
 
   return 1;
@@ -394,13 +394,11 @@ sub _control_error {
 }
 
 sub _dbupdate2_calculate_depth {
-  $::lxdebug->enter_sub(2);
-
   my ($tree, $tag) = @_;
 
   my $node = $tree->{$tag};
 
-  return $::lxdebug->leave_sub(2) if (defined($node->{"depth"}));
+  return if (defined($node->{"depth"}));
 
   my $max_depth = 0;
 
@@ -411,8 +409,6 @@ sub _dbupdate2_calculate_depth {
   }
 
   $node->{"depth"} = $max_depth + 1;
-
-  $::lxdebug->leave_sub(2);
 }
 
 sub sort_dbupdate_controls {
@@ -629,7 +625,7 @@ The global C<SL::Form> object.
 =back
 
 A Perl script can actually implement queries that fail while
-continueing the process by handling the transaction itself, e.g. with
+continuing the process by handling the transaction itself, e.g. with
 the following function:
 
   sub do_query {
@@ -663,14 +659,6 @@ to the database that is checked.
 
 Requires that the scripts have been parsed.
 
-=item C<update2_available $dbh>
-
-Returns trueish if at least one upgrade script hasn't been applied to
-a database yet. C<$dbh> is an open handle to the database that is
-checked.
-
-Requires that the scripts have been parsed.
-
 =back
 
 =head1 BUGS