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 if (!$control->{"tag"}) {
85 _control_error($form, $file_name, $locale->text("Missing 'tag' field.")) ;
88 if ($control->{"tag"} =~ /[^a-zA-Z0-9_\(\)\-]/) {
89 _control_error($form, $file_name, $locale->text("The 'tag' field must only consist of alphanumeric characters or the carachters - _ ( )"))
92 if (defined($all_controls{$control->{"tag"}})) {
93 _control_error($form, $file_name, sprintf($locale->text("More than one control file with the tag '%s' exist."), $control->{"tag"}))
96 if (!$control->{"description"}) {
97 _control_error($form, $file_name, sprintf($locale->text("Missing 'description' field."))) ;
100 $control->{"priority"} *= 1;
101 $control->{"priority"} ||= 1000;
102 $control->{"file"} = $file;
104 delete @{$control}{qw(depth applied)};
106 $all_controls{$control->{"tag"}} = $control;
111 foreach my $control (values(%all_controls)) {
112 foreach my $dependency (@{$control->{"depends"}}) {
113 _control_error($form, $control->{"file"}, sprintf($locale->text("Unknown dependency '%s'."), $dependency)) if (!defined($all_controls{$dependency}));
116 map({ $_->{"loop"} = 0; } values(%all_controls));
117 _check_for_loops($form, $control->{"file"}, \%all_controls, $control->{"tag"});
120 map({ _dbupdate2_calculate_depth(\%all_controls, $_->{"tag"}) }
121 values(%all_controls));
123 $self->{all_controls} = \%all_controls;
125 $::lxdebug->leave_sub();
131 $::lxdebug->enter_sub();
133 my ($self, $dbh, $filename, $version_or_control) = @_;
135 my $form = $self->{form};
136 my $fh = IO::File->new($filename, "r") or $form->error("$filename : $!\n");
144 $_ = SL::Iconv::convert('UTF-8', 'UTF-8', $_);
146 # Remove DOS and Unix style line endings.
152 for (my $i = 0; $i < length($_); $i++) {
153 my $char = substr($_, $i, 1);
155 # Are we inside a string?
157 if ($char eq $quote_chars[-1]) {
159 } elsif (length $quote_chars[-1] > 1
160 && substr($_, $i, length $quote_chars[-1]) eq $quote_chars[-1]) {
161 $i += length($quote_chars[-1]) - 1;
162 $char = $quote_chars[-1];
169 if (($char eq "'") || ($char eq "\"")) {
170 push(@quote_chars, $char);
172 } elsif ($char eq '$' # start of dollar quoting
173 && ($tag_end = index($_, '$', $i + 1)) > -1 # ends on same line
174 && (do { $tag = substr($_, $i + 1, $tag_end - $i - 1); 1 }) # extract tag
175 && $tag =~ /^ (?= [A-Za-z_] [A-Za-z0-9_]* | ) $/x) { # tag is identifier
176 push @quote_chars, $char = '$' . $tag . '$';
178 } elsif ($char eq ";") {
180 # Query is complete. Send it.
182 $sth = $dbh->prepare($query);
183 if (!$sth->execute()) {
184 my $errstr = $dbh->errstr;
187 $form->dberror("The database update/creation did not succeed. " .
188 "The file ${filename} containing the following " .
189 "query failed:<br>${query}<br>" .
190 "The error message was: ${errstr}<br>" .
191 "All changes in that file have been reverted.");
203 # Insert a space at the end of each line so that queries split
204 # over multiple lines work properly.
206 $query .= @quote_chars ? "\n" : ' ';
210 if (ref($version_or_control) eq "HASH") {
211 $dbh->do("INSERT INTO " . $self->{schema} . "schema_info (tag, login) VALUES (" . $dbh->quote($version_or_control->{"tag"}) . ", " . $dbh->quote($form->{"login"}) . ")");
212 } elsif ($version_or_control) {
213 $dbh->do("UPDATE defaults SET version = " . $dbh->quote($version_or_control));
219 $::lxdebug->leave_sub();
222 # Process a Perl script which updates the database.
223 # If the script returns 1 then the update was successful.
224 # Return code "2" means "needs more interaction; unlock
225 # the system and end current request".
226 # All other return codes are fatal errors.
227 sub process_perl_script {
228 $::lxdebug->enter_sub();
230 my ($self, $dbh, $filename, $version_or_control) = @_;
232 my %form_values = map { $_ => $::form->{$_} } qw(dbconnect dbdefault dbhost dbmbkiviunstable dbname dboptions dbpasswd dbport dbupdate dbuser login template_object version);
236 # setup dbup_ export vars & run script
237 my %dbup_myconfig = map { ($_ => $::form->{$_}) } qw(dbname dbuser dbpasswd dbhost dbport dbconnect);
239 SL::DBUpgrade2::Base::execute_script(
240 file_name => $filename,
241 tag => $version_or_control->{tag},
243 myconfig => \%dbup_myconfig,
247 my $error = $EVAL_ERROR;
249 $dbh->rollback if 1 != ($result // -1);
251 if (!defined($result)) {
252 print $::form->parse_html_template("dbupgrade/error", { file => $filename, error => $error });
254 } elsif (1 != $result) {
255 SL::System::InstallationLock->unlock if 2 == $result;
259 if (ref($version_or_control) eq "HASH") {
260 $dbh->do("INSERT INTO " . $self->{schema} . "schema_info (tag, login) VALUES (" . $dbh->quote($version_or_control->{tag}) . ", " . $dbh->quote($::form->{login}) . ")");
261 } elsif ($version_or_control) {
262 $dbh->do("UPDATE defaults SET version = " . $dbh->quote($version_or_control));
266 # Clear $::form of values that may have been set so that following
267 # Perl upgrade scripts won't have to work with old data (think of
268 # the usual 'continued' mechanism that's used for determining
269 # whether or not the upgrade form must be displayed).
270 delete @{ $::form }{ keys %{ $::form } };
271 $::form->{$_} = $form_values{$_} for keys %form_values;
273 $::lxdebug->leave_sub();
277 my ($self, $dbh, $filename, $version_or_control) = @_;
279 if ($filename =~ m/sql$/) {
280 $self->process_query($dbh, $filename, $version_or_control);
282 $self->process_perl_script($dbh, $filename, $version_or_control);
286 sub update2_available {
287 $::lxdebug->enter_sub();
289 my ($self, $dbh) = @_;
291 map { $_->{applied} = 0; } values %{ $self->{all_controls} };
293 my $sth = $dbh->prepare(qq|SELECT tag FROM | . $self->{schema} . qq|schema_info|);
295 while (my ($tag) = $sth->fetchrow_array) {
296 $self->{all_controls}->{$tag}->{applied} = 1 if defined $self->{all_controls}->{$tag};
301 my $needs_update = any { !$_->{applied} } values %{ $self->{all_controls} };
303 $::lxdebug->leave_sub();
305 return $needs_update;
308 sub unapplied_upgrade_scripts {
309 my ($self, $dbh) = @_;
311 my @all_scripts = map { $_->{applied} = 0; $_ } $self->sort_dbupdate_controls;
313 my $query = qq|SELECT tag FROM | . $self->{schema} . qq|schema_info|;
314 my $sth = $dbh->prepare($query);
315 $sth->execute || $self->{form}->dberror($query);
316 while (my ($tag) = $sth->fetchrow_array()) {
317 $self->{all_controls}->{$tag}->{applied} = 1 if defined $self->{all_controls}->{$tag};
321 return grep { !$_->{applied} } @all_scripts;
324 sub apply_admin_dbupgrade_scripts {
325 my ($self, $called_from_admin) = @_;
327 return 0 if !$self->{auth};
329 my $dbh = $::auth->dbconnect;
330 my @unapplied_scripts = $self->unapplied_upgrade_scripts($dbh);
332 return 0 if !@unapplied_scripts;
334 $self->{form}->{login} ||= 'admin';
336 map { $_->{description} = SL::Iconv::convert('UTF-8', 'UTF-8', $_->{description}) } values %{ $self->{all_controls} };
338 if ($called_from_admin) {
339 $self->{form}->{title} = $::locale->text('Dataset upgrade');
340 $self->{form}->header;
343 print $self->{form}->parse_html_template("dbupgrade/header", { dbname => $::auth->{DB_config}->{db} });
345 foreach my $control (@unapplied_scripts) {
346 $::lxdebug->message(LXDebug->DEBUG2(), "Applying Update $control->{file}");
347 print $self->{form}->parse_html_template("dbupgrade/upgrade_message2", $control);
349 $self->process_file($dbh, "sql/Pg-upgrade2-auth/$control->{file}", $control);
352 print $self->{form}->parse_html_template("dbupgrade/footer", { is_admin => 1 }) if $called_from_admin;
357 sub _check_for_loops {
358 my ($form, $file_name, $controls, $tag, @path) = @_;
362 my $ctrl = $controls->{$tag};
364 if ($ctrl->{"loop"} == 1) {
366 _control_error($form, $file_name, $::locale->text("Dependency loop detected:") . " " . join(" -> ", @path))
368 } elsif ($ctrl->{"loop"} == 0) {
371 map({ _check_for_loops($form, $file_name, $controls, $_, @path); } @{ $ctrl->{"depends"} });
377 my ($form, $file_name, $message) = @_;
380 my $locale = $::locale;
382 $form->error(sprintf($locale->text("Error in database control file '%s': %s"), $file_name, $message));
385 sub _dbupdate2_calculate_depth {
386 $::lxdebug->enter_sub(2);
388 my ($tree, $tag) = @_;
390 my $node = $tree->{$tag};
392 return $::lxdebug->leave_sub(2) if (defined($node->{"depth"}));
396 foreach $tag (@{$node->{"depends"}}) {
397 _dbupdate2_calculate_depth($tree, $tag);
398 my $value = $tree->{$tag}->{"depth"};
399 $max_depth = $value if ($value > $max_depth);
402 $node->{"depth"} = $max_depth + 1;
404 $::lxdebug->leave_sub(2);
407 sub sort_dbupdate_controls {
410 $self->parse_dbupdate_controls unless $self->{all_controls};
412 return sort { ($a->{depth} <=> $b->{depth}) || ($a->{priority} <=> $b->{priority}) || ($a->{tag} cmp $b->{tag}) } values %{ $self->{all_controls} };
424 SL::DBUpgrade2 - Parse database upgrade files stored in
425 C<sql/Pg-upgrade2> and C<sql/Pg-upgrade2-auth>
432 # Apply outstanding updates to the authentication database
433 my $scripts = SL::DBUpgrade2->new(
437 $scripts->apply_admin_dbupgrade_scripts(1);
439 # Apply updates to a user database
440 my $scripts = SL::DBUpgrade2->new(
444 User->dbupdate2(form => $form,
445 updater => $scripts->parse_dbupdate_controls,
446 database => $dbname);
450 Database upgrade files are used to upgrade the database structure and
451 content of both the authentication database and the user
452 databases. They're applied when a user logs in. As long as the
453 authentication database is not up to date users cannot log in in
454 general, and the admin has to log in first in order to get his
457 Database scripts form a tree by specifying which upgrade file depends
458 on which other upgrade file. This means that such files are always
459 applied in a well-defined order.
461 Each script is run in a separate transaction. If a script fails the
462 current transaction is rolled back and the whole upgrade process is
463 stopped. The user/admin is required to fix the issue manually.
465 A list of applied upgrade scripts is maintained in a table called
466 C<schema_info> for the user database and C<auth.schema_info>) for the
467 authentication database. They contain the tags, the login name of the
468 user having applied the script and the timestamp when the script was
471 Database upgrade files come in two flavours: SQL files and Perl
472 files. For both there are control fields that determine the order in
473 which they're executed etc. The control fields are tag/value pairs
474 contained in comments.
476 =head1 CONTROL FIELDS
480 Control fields for Perl files:
483 # @tag2: some more values
488 Control fields for SQL files:
491 -- @tag2: some more values
494 =head2 TAGS AND THEIR MEANING
496 The following tags are recognized:
502 The name for this file. The C<tag> is also used for dependency
503 resolution (see C<depends>).
509 A description presented to the user when the update is applied.
515 A space-separated list of tags of scripts this particular script
516 depends on. All other upgrades listed in C<depends> will be applied
517 before the current one is applied.
521 Ordering the scripts by their dependencies alone produces a lot of
522 groups of scripts that could be applied at the same time (e.g. if both
523 B and C depend only on A then B could be applied before C or the other
524 way around). This field determines the order inside such a
525 group. Scripts with lower priority fields are executed before scripts
526 with higher priority fields.
528 If two scripts have equal priorities then their tag name decides.
530 The priority defaults to 1000.
538 =item C<apply_admin_dbupgrade_scripts $called_from_admin>
540 Applies all unapplied upgrade files to the authentication/admin
541 database. The parameter C<$called_from_admin> should be truish if the
542 function is called from the web interface and falsish if it's called
543 from e.g. a command line script like C<scripts/dbupgrade2_tool.pl>.
545 =item C<init %params>
547 Initializes the object. Is called directly from L<new> and should not
552 Creates a new object. Possible parameters are:
558 Path to the upgrade files to parse. Required.
562 C<SL::Form> object to use. Required.
566 Optional parameter defaulting to 0. If trueish then the scripts read
567 are the ones applying to the authentication database.
571 =item C<parse_dbupdate_controls>
573 Parses all files located in C<path> (see L<new>), ananlyzes their
574 control fields, builds the tree, and signals errors if control fields
575 are missing/wrong (e.g. a tag name listed in C<depends> is not
576 found). Sets C<$Self->{all_controls}> to the list of database
579 =item C<process_file $dbh, $filename, $version_or_control>
581 Applies a single database upgrade file. Calls L<process_perl_script>
582 for Perl update files and C<process_query> for SQL update
583 files. Requires an open database handle(C<$dbh>), the file name
584 (C<$filename>) and a hash structure of the file's control fields as
585 produced by L<parse_dbupdate_controls> (C<$version_or_control>).
587 Returns the result of the actual function called.
589 =item C<process_perl_script $dbh, $filename, $version_or_control>
591 Applies a single Perl database upgrade file. Requires an open database
592 handle(C<$dbh>), the file name (C<$filename>) and a hash structure of
593 the file's control fields as produced by L<parse_dbupdate_controls>
594 (C<$version_or_control>).
596 Perl scripts are executed via L<eval>. If L<eval> returns falsish then
597 an error is expected. There are two special return values: If the
598 script returns C<1> then the update was successful. Return code C<2>
599 means "needs more interaction from the user; unlock the system and
600 end current upgrade process". All other return codes are fatal errors.
602 Inside the Perl script several local variables exist that can be used:
608 A locale object for translating messages
612 The database handle (inside a transaction).
616 The global C<SL::Form> object.
620 A Perl script can actually implement queries that fail while
621 continueing the process by handling the transaction itself, e.g. with
622 the following function:
625 my ($query, $may_fail) = @_;
627 if (!$dbh->do($query)) {
628 die($dbup_locale->text("Database update error:") . "<br>$msg<br>" . $DBI::errstr) unless $may_fail;
634 =item C<process_query $dbh, $filename, $version_or_control>
636 Applies a single SQL database upgrade file. Requires an open database
637 handle(C<$dbh>), the file name (C<$filename>), and a hash structure of
638 the file's control fields as produced by L<parse_dbupdate_controls>
639 (C<$version_or_control>).
641 =item C<sort_dbupdate_controls>
643 Sorts the database upgrade scripts according to their C<tag> and
644 C<priority> control fields. Returns a list of their hash
645 representations that can be applied in order.
647 =item C<unapplied_upgrade_scripts $dbh>
649 Returns a list if upgrade scripts (their internal hash representation)
650 that haven't been applied to a database yet. C<$dbh> is an open handle
651 to the database that is checked.
653 Requires that the scripts have been parsed.
655 =item C<update2_available $dbh>
657 Returns trueish if at least one upgrade script hasn't been applied to
658 a database yet. C<$dbh> is an open handle to the database that is
661 Requires that the scripts have been parsed.
671 Moritz Bunkus E<lt>m.bunkus@linet-services.deE<gt>