1 package SL::DBUpgrade2;
3 use English qw(-no_match_vars);
5 use List::MoreUtils qw(any);
8 use SL::DBUpgrade2::Base;
17 return bless({}, $package)->init(@_);
21 my ($self, %params) = @_;
24 $params{path_suffix} = "-auth";
25 $params{schema} = "auth.";
28 $params{path_suffix} ||= '';
29 $params{schema} ||= '';
30 $params{path} = "sql/Pg-upgrade2" . $params{path_suffix};
32 map { $self->{$_} = $params{$_} } keys %params;
41 sub parse_dbupdate_controls {
42 $::lxdebug->enter_sub();
46 my $form = $self->{form};
47 my $locale = $::locale;
52 my $path = $self->path;
54 foreach my $file_name (<$path/*.sql>, <$path/*.pl>) {
55 next unless (open(IN, $file_name));
57 my $file = $file_name;
67 next unless (/^(--|\#)\s*\@/);
72 my @fields = split(/\s*:\s*/, $_, 2);
73 next unless (scalar(@fields) == 2);
75 if ($fields[0] eq "depends") {
76 push(@{$control->{"depends"}}, split(/\s+/, $fields[1]));
78 $control->{$fields[0]} = $fields[1];
82 next if ($control->{ignore});
84 $control->{charset} = 'UTF-8' if $file =~ m/\.pl$/;
85 $control->{charset} = $control->{charset} || $control->{encoding} || Common::DEFAULT_CHARSET;
87 if (!$control->{"tag"}) {
88 _control_error($form, $file_name, $locale->text("Missing 'tag' field.")) ;
91 if ($control->{"tag"} =~ /[^a-zA-Z0-9_\(\)\-]/) {
92 _control_error($form, $file_name, $locale->text("The 'tag' field must only consist of alphanumeric characters or the carachters - _ ( )"))
95 if (defined($all_controls{$control->{"tag"}})) {
96 _control_error($form, $file_name, sprintf($locale->text("More than one control file with the tag '%s' exist."), $control->{"tag"}))
99 if (!$control->{"description"}) {
100 _control_error($form, $file_name, sprintf($locale->text("Missing 'description' field."))) ;
103 $control->{"priority"} *= 1;
104 $control->{"priority"} ||= 1000;
105 $control->{"file"} = $file;
107 delete @{$control}{qw(depth applied)};
109 $all_controls{$control->{"tag"}} = $control;
114 foreach my $control (values(%all_controls)) {
115 foreach my $dependency (@{$control->{"depends"}}) {
116 _control_error($form, $control->{"file"}, sprintf($locale->text("Unknown dependency '%s'."), $dependency)) if (!defined($all_controls{$dependency}));
119 map({ $_->{"loop"} = 0; } values(%all_controls));
120 _check_for_loops($form, $control->{"file"}, \%all_controls, $control->{"tag"});
123 map({ _dbupdate2_calculate_depth(\%all_controls, $_->{"tag"}) }
124 values(%all_controls));
126 $self->{all_controls} = \%all_controls;
128 $::lxdebug->leave_sub();
134 $::lxdebug->enter_sub();
136 my ($self, $dbh, $filename, $version_or_control, $db_charset) = @_;
138 my $form = $self->{form};
139 my $fh = IO::File->new($filename, "r") or $form->error("$filename : $!\n");
144 my $file_charset = Common::DEFAULT_CHARSET;
147 next if !/^--\s*\@(?:charset|encoding):\s*(.+)/;
151 $fh->seek(0, SEEK_SET);
153 $db_charset ||= Common::DEFAULT_CHARSET;
158 $_ = SL::Iconv::convert($file_charset, $db_charset, $_);
160 # Remove DOS and Unix style line endings.
166 for (my $i = 0; $i < length($_); $i++) {
167 my $char = substr($_, $i, 1);
169 # Are we inside a string?
171 if ($char eq $quote_chars[-1]) {
173 } elsif (length $quote_chars[-1] > 1
174 && substr($_, $i, length $quote_chars[-1]) eq $quote_chars[-1]) {
175 $i += length($quote_chars[-1]) - 1;
176 $char = $quote_chars[-1];
183 if (($char eq "'") || ($char eq "\"")) {
184 push(@quote_chars, $char);
186 } elsif ($char eq '$' # start of dollar quoting
187 && ($tag_end = index($_, '$', $i + 1)) > -1 # ends on same line
188 && (do { $tag = substr($_, $i + 1, $tag_end - $i - 1); 1 }) # extract tag
189 && $tag =~ /^ (?= [A-Za-z_] [A-Za-z0-9_]* | ) $/x) { # tag is identifier
190 push @quote_chars, $char = '$' . $tag . '$';
192 } elsif ($char eq ";") {
194 # Query is complete. Send it.
196 $sth = $dbh->prepare($query);
197 if (!$sth->execute()) {
198 my $errstr = $dbh->errstr;
201 $form->dberror("The database update/creation did not succeed. " .
202 "The file ${filename} containing the following " .
203 "query failed:<br>${query}<br>" .
204 "The error message was: ${errstr}<br>" .
205 "All changes in that file have been reverted.");
217 # Insert a space at the end of each line so that queries split
218 # over multiple lines work properly.
220 $query .= @quote_chars ? "\n" : ' ';
224 if (ref($version_or_control) eq "HASH") {
225 $dbh->do("INSERT INTO " . $self->{schema} . "schema_info (tag, login) VALUES (" . $dbh->quote($version_or_control->{"tag"}) . ", " . $dbh->quote($form->{"login"}) . ")");
226 } elsif ($version_or_control) {
227 $dbh->do("UPDATE defaults SET version = " . $dbh->quote($version_or_control));
233 $::lxdebug->leave_sub();
236 # Process a Perl script which updates the database.
237 # If the script returns 1 then the update was successful.
238 # Return code "2" means "needs more interaction; unlock
239 # the system and end current request".
240 # All other return codes are fatal errors.
241 sub process_perl_script {
242 $::lxdebug->enter_sub();
244 my ($self, $dbh, $filename, $version_or_control, $db_charset) = @_;
246 my %form_values = map { $_ => $::form->{$_} } qw(dbconnect dbdefault dbhost dbmbkiviunstable dbname dboptions dbpasswd dbport dbupdate dbuser login template_object version);
250 # setup dbup_ export vars & run script
251 my %dbup_myconfig = map { ($_ => $::form->{$_}) } qw(dbname dbuser dbpasswd dbhost dbport dbconnect);
253 SL::DBUpgrade2::Base::execute_script(
254 file_name => $filename,
255 tag => $version_or_control->{tag},
257 myconfig => \%dbup_myconfig,
261 my $error = $EVAL_ERROR;
263 $dbh->rollback if 1 != ($result // -1);
265 if (!defined($result)) {
266 print $::form->parse_html_template("dbupgrade/error", { file => $filename, error => $error });
268 } elsif (1 != $result) {
269 SL::System::InstallationLock->unlock if 2 == $result;
273 if (ref($version_or_control) eq "HASH") {
274 $dbh->do("INSERT INTO " . $self->{schema} . "schema_info (tag, login) VALUES (" . $dbh->quote($version_or_control->{tag}) . ", " . $dbh->quote($::form->{login}) . ")");
275 } elsif ($version_or_control) {
276 $dbh->do("UPDATE defaults SET version = " . $dbh->quote($version_or_control));
280 # Clear $::form of values that may have been set so that following
281 # Perl upgrade scripts won't have to work with old data (think of
282 # the usual 'continued' mechanism that's used for determining
283 # whether or not the upgrade form must be displayed).
284 delete @{ $::form }{ keys %{ $::form } };
285 $::form->{$_} = $form_values{$_} for keys %form_values;
287 $::lxdebug->leave_sub();
291 my ($self, $dbh, $filename, $version_or_control, $db_charset) = @_;
293 if ($filename =~ m/sql$/) {
294 $self->process_query($dbh, $filename, $version_or_control, $db_charset);
296 $self->process_perl_script($dbh, $filename, $version_or_control, $db_charset);
300 sub update_available {
301 my ($self, $cur_version) = @_;
305 opendir SQLDIR, "sql/Pg-upgrade" || error("", "sql/Pg-upgrade: $!");
306 my @upgradescripts = grep /Pg-upgrade-\Q$cur_version\E.*\.(sql|pl)$/, readdir SQLDIR;
309 return ($#upgradescripts > -1);
312 sub update2_available {
313 $::lxdebug->enter_sub();
315 my ($self, $dbh) = @_;
317 map { $_->{applied} = 0; } values %{ $self->{all_controls} };
319 my $sth = $dbh->prepare(qq|SELECT tag FROM | . $self->{schema} . qq|schema_info|);
321 while (my ($tag) = $sth->fetchrow_array) {
322 $self->{all_controls}->{$tag}->{applied} = 1 if defined $self->{all_controls}->{$tag};
327 my $needs_update = any { !$_->{applied} } values %{ $self->{all_controls} };
329 $::lxdebug->leave_sub();
331 return $needs_update;
334 sub unapplied_upgrade_scripts {
335 my ($self, $dbh) = @_;
337 my @all_scripts = map { $_->{applied} = 0; $_ } $self->sort_dbupdate_controls;
339 my $query = qq|SELECT tag FROM | . $self->{schema} . qq|schema_info|;
340 my $sth = $dbh->prepare($query);
341 $sth->execute || $self->{form}->dberror($query);
342 while (my ($tag) = $sth->fetchrow_array()) {
343 $self->{all_controls}->{$tag}->{applied} = 1 if defined $self->{all_controls}->{$tag};
347 return grep { !$_->{applied} } @all_scripts;
350 sub apply_admin_dbupgrade_scripts {
351 my ($self, $called_from_admin) = @_;
353 return 0 if !$self->{auth};
355 my $dbh = $::auth->dbconnect;
356 my @unapplied_scripts = $self->unapplied_upgrade_scripts($dbh);
358 return 0 if !@unapplied_scripts;
360 my $db_charset = $::lx_office_conf{system}->{dbcharset} || Common::DEFAULT_CHARSET;
361 $self->{form}->{login} ||= 'admin';
363 map { $_->{description} = SL::Iconv::convert($_->{charset}, $db_charset, $_->{description}) } values %{ $self->{all_controls} };
365 if ($called_from_admin) {
366 $self->{form}->{title} = $::locale->text('Dataset upgrade');
367 $self->{form}->header;
370 print $self->{form}->parse_html_template("dbupgrade/header", { dbname => $::auth->{DB_config}->{db} });
372 foreach my $control (@unapplied_scripts) {
373 $::lxdebug->message(LXDebug->DEBUG2(), "Applying Update $control->{file}");
374 print $self->{form}->parse_html_template("dbupgrade/upgrade_message2", $control);
376 $self->process_file($dbh, "sql/Pg-upgrade2-auth/$control->{file}", $control, $db_charset);
379 print $self->{form}->parse_html_template("dbupgrade/footer", { is_admin => 1 }) if $called_from_admin;
384 sub _check_for_loops {
385 my ($form, $file_name, $controls, $tag, @path) = @_;
389 my $ctrl = $controls->{$tag};
391 if ($ctrl->{"loop"} == 1) {
393 _control_error($form, $file_name, $::locale->text("Dependency loop detected:") . " " . join(" -> ", @path))
395 } elsif ($ctrl->{"loop"} == 0) {
398 map({ _check_for_loops($form, $file_name, $controls, $_, @path); } @{ $ctrl->{"depends"} });
404 my ($form, $file_name, $message) = @_;
407 my $locale = $::locale;
409 $form->error(sprintf($locale->text("Error in database control file '%s': %s"), $file_name, $message));
412 sub _dbupdate2_calculate_depth {
413 $::lxdebug->enter_sub(2);
415 my ($tree, $tag) = @_;
417 my $node = $tree->{$tag};
419 return $::lxdebug->leave_sub(2) if (defined($node->{"depth"}));
423 foreach $tag (@{$node->{"depends"}}) {
424 _dbupdate2_calculate_depth($tree, $tag);
425 my $value = $tree->{$tag}->{"depth"};
426 $max_depth = $value if ($value > $max_depth);
429 $node->{"depth"} = $max_depth + 1;
431 $::lxdebug->leave_sub(2);
434 sub sort_dbupdate_controls {
437 $self->parse_dbupdate_controls unless $self->{all_controls};
439 return sort { ($a->{depth} <=> $b->{depth}) || ($a->{priority} <=> $b->{priority}) || ($a->{tag} cmp $b->{tag}) } values %{ $self->{all_controls} };
451 SL::DBUpgrade2 - Parse database upgrade files stored in
452 C<sql/Pg-upgrade2> and C<sql/Pg-upgrade2-auth> (and also in
460 # Apply outstanding updates to the authentication database
461 my $scripts = SL::DBUpgrade2->new(
465 $scripts->apply_admin_dbupgrade_scripts(1);
467 # Apply updates to a user database
468 my $scripts = SL::DBUpgrade2->new(
472 User->dbupdate2(form => $form,
473 updater => $scripts->parse_dbupdate_controls,
474 database => $dbname);
478 Database upgrade files are used to upgrade the database structure and
479 content of both the authentication database and the user
480 databases. They're applied when a user logs in. As long as the
481 authentication database is not up to date users cannot log in in
482 general, and the admin has to log in first in order to get his
485 Database scripts form a tree by specifying which upgrade file depends
486 on which other upgrade file. This means that such files are always
487 applied in a well-defined order.
489 Each script is run in a separate transaction. If a script fails the
490 current transaction is rolled back and the whole upgrade process is
491 stopped. The user/admin is required to fix the issue manually.
493 A list of applied upgrade scripts is maintained in a table called
494 C<schema_info> for the user database and C<auth.schema_info>) for the
495 authentication database. They contain the tags, the login name of the
496 user having applied the script and the timestamp when the script was
499 Database upgrade files come in two flavours: SQL files and Perl
500 files. For both there are control fields that determine the order in
501 which they're executed, what charset the scripts are written in
502 etc. The control fields are tag/value pairs contained in comments.
504 =head1 OLD UPGRADE FILES
506 The files in C<sql/Pg-upgrade> are so old that I don't bother
507 documenting them. They're handled by this class, too, but new files
508 are only created as C<Pg-upgrade2> files.
510 =head1 CONTROL FIELDS
514 Control fields for Perl files:
517 # @tag2: some more values
522 Control fields for SQL files:
525 -- @tag2: some more values
528 =head2 TAGS AND THEIR MEANING
530 The following tags are recognized:
536 The name for this file. The C<tag> is also used for dependency
537 resolution (see C<depends>).
543 A description presented to the user when the update is applied.
549 A space-separated list of tags of scripts this particular script
550 depends on. All other upgrades listed in C<depends> will be applied
551 before the current one is applied.
557 The charset this file uses. Defaults to C<ISO-8859-15> if
558 missing. Both terms are recognized.
562 Ordering the scripts by their dependencies alone produces a lot of
563 groups of scripts that could be applied at the same time (e.g. if both
564 B and C depend only on A then B could be applied before C or the other
565 way around). This field determines the order inside such a
566 group. Scripts with lower priority fields are executed before scripts
567 with higher priority fields.
569 If two scripts have equal priorities then their tag name decides.
571 The priority defaults to 1000.
579 =item C<apply_admin_dbupgrade_scripts $called_from_admin>
581 Applies all unapplied upgrade files to the authentication/admin
582 database. The parameter C<$called_from_admin> should be truish if the
583 function is called from the web interface and falsish if it's called
584 from e.g. a command line script like C<scripts/dbupgrade2_tool.pl>.
586 =item C<init %params>
588 Initializes the object. Is called directly from L<new> and should not
593 Creates a new object. Possible parameters are:
599 Path to the upgrade files to parse. Required.
603 C<SL::Form> object to use. Required.
607 Optional parameter defaulting to 0. If trueish then the scripts read
608 are the ones applying to the authentication database.
612 =item C<parse_dbupdate_controls>
614 Parses all files located in C<path> (see L<new>), ananlyzes their
615 control fields, builds the tree, and signals errors if control fields
616 are missing/wrong (e.g. a tag name listed in C<depends> is not
617 found). Sets C<$Self->{all_controls}> to the list of database
620 =item C<process_file $dbh, $filename, $version_or_control, $db_charset>
622 Applies a single database upgrade file. Calls L<process_perl_script>
623 for Perl update files and C<process_query> for SQL update
624 files. Requires an open database handle(C<$dbh>), the file name
625 (C<$filename>), a hash structure of the file's control fields as
626 produced by L<parse_dbupdate_controls> (C<$version_or_control>) and
627 the database charset (for on-the-fly charset recoding of the script if
628 required, C<$db_charset>).
630 Returns the result of the actual function called.
632 =item C<process_perl_script $dbh, $filename, $version_or_control, $db_charset>
634 Applies a single Perl database upgrade file. Requires an open database
635 handle(C<$dbh>), the file name (C<$filename>), a hash structure of the
636 file's control fields as produced by L<parse_dbupdate_controls>
637 (C<$version_or_control>) and the database charset (for on-the-fly
638 charset recoding of the script if required, C<$db_charset>).
640 Perl scripts are executed via L<eval>. If L<eval> returns falsish then
641 an error is expected. There are two special return values: If the
642 script returns C<1> then the update was successful. Return code C<2>
643 means "needs more interaction from the user; unlock the system and
644 end current upgrade process". All other return codes are fatal errors.
646 Inside the Perl script several local variables exist that can be used:
652 A locale object for translating messages
656 The database handle (inside a transaction).
660 The global C<SL::Form> object.
664 A Perl script can actually implement queries that fail while
665 continueing the process by handling the transaction itself, e.g. with
666 the following function:
669 my ($query, $may_fail) = @_;
671 if (!$dbh->do($query)) {
672 die($dbup_locale->text("Database update error:") . "<br>$msg<br>" . $DBI::errstr) unless $may_fail;
678 =item C<process_query $dbh, $filename, $version_or_control, $db_charset>
680 Applies a single SQL database upgrade file. Requires an open database
681 handle(C<$dbh>), the file name (C<$filename>), a hash structure of the
682 ofile's control fields as produced by L<parse_dbupdate_controls>
683 (C<$version_or_control>) and the database charset (for on-the-fly
684 charset recoding of the script if required, C<$db_charset>).
686 =item C<sort_dbupdate_controls>
688 Sorts the database upgrade scripts according to their C<tag> and
689 C<priority> control fields. Returns a list of their hash
690 representations that can be applied in order.
692 =item C<unapplied_upgrade_scripts $dbh>
694 Returns a list if upgrade scripts (their internal hash representation)
695 that haven't been applied to a database yet. C<$dbh> is an open handle
696 to the database that is checked.
698 Requires that the scripts have been parsed.
700 =item C<update2_available $dbh>
702 Returns trueish if at least one upgrade script hasn't been applied to
703 a database yet. C<$dbh> is an open handle to the database that is
706 Requires that the scripts have been parsed.
716 Moritz Bunkus E<lt>m.bunkus@linet-services.deE<gt>