Datenbankupgrades: unbekannte Control-Felder als Fehler werten
[kivitendo-erp.git] / SL / DBUpgrade2.pm
1 package SL::DBUpgrade2;
2
3 use English qw(-no_match_vars);
4 use IO::File;
5 use List::MoreUtils qw(any);
6
7 use SL::Common;
8 use SL::DBUpgrade2::Base;
9 use SL::DBUtils;
10 use SL::System::Process;
11
12 use strict;
13
14 sub new {
15   my $package = shift;
16
17   return bless({}, $package)->init(@_);
18 }
19
20 sub init {
21   my ($self, %params) = @_;
22
23   if ($params{auth}) {
24     $params{path_suffix} = "-auth";
25     $params{schema}      = "auth.";
26   }
27
28   $params{path_suffix} ||= '';
29   $params{schema}      ||= '';
30   $params{path}        ||= SL::System::Process->exe_dir . "/sql/Pg-upgrade2" . $params{path_suffix};
31
32   map { $self->{$_} = $params{$_} } keys %params;
33
34   return $self;
35 }
36
37 sub path {
38   $_[0]{path};
39 }
40
41 sub parse_dbupdate_controls {
42   my ($self) = @_;
43
44   my $form   = $self->{form};
45   my $locale = $::locale;
46
47   local *IN;
48   my %all_controls;
49
50   my $path = $self->path;
51
52   foreach my $file_name (<$path/*.sql>, <$path/*.pl>) {
53     next unless (open(IN, "<:encoding(UTF-8)", $file_name));
54
55     my $file = $file_name;
56     $file =~ s|.*/||;
57
58     my $control = {
59       "priority" => 1000,
60       "depends"  => [],
61       "locales"  => [],
62     };
63
64     while (<IN>) {
65       chomp();
66       next unless (/^(--|\#)\s*\@/);
67       s/^(--|\#)\s*\@//;
68       s/\s*$//;
69       next if ($_ eq "");
70
71       my @fields = split(/\s*:\s*/, $_, 2);
72       next unless (scalar(@fields) == 2);
73
74       if ($fields[0] eq "depends") {
75         push(@{$control->{"depends"}}, split(/\s+/, $fields[1]));
76       } elsif ($fields[0] eq "locales") {
77         push @{$control->{locales}}, $fields[1];
78       } else {
79         $control->{$fields[0]} = $fields[1];
80       }
81     }
82
83     next if ($control->{ignore});
84
85     if (!$control->{"tag"}) {
86       _control_error($form, $file_name, $locale->text("Missing 'tag' field.")) ;
87     }
88
89     if ($control->{"tag"} =~ /[^a-zA-Z0-9_\(\)\-]/) {
90       _control_error($form, $file_name, $locale->text("The 'tag' field must only consist of alphanumeric characters or the carachters - _ ( )"))
91     }
92
93     if (defined($all_controls{$control->{"tag"}})) {
94       _control_error($form, $file_name, sprintf($locale->text("More than one control file with the tag '%s' exist."), $control->{"tag"}))
95     }
96
97     if (!$control->{"description"}) {
98       _control_error($form, $file_name, sprintf($locale->text("Missing 'description' field."))) ;
99     }
100
101     delete @{$control}{qw(depth applied)};
102
103     my @unknown_keys = grep { !m{^ (?: depends | description | file | ignore | locales | may_fail | priority | tag ) $}x } keys %{ $control };
104     if (@unknown_keys) {
105       _control_error($form, $file_name, sprintf($locale->text("Unknown control fields: #1", join(' ', sort({ lc $a cmp lc $b } @unknown_keys)))));
106     }
107
108     $control->{"priority"}  *= 1;
109     $control->{"priority"} ||= 1000;
110     $control->{"file"}       = $file;
111
112     $all_controls{$control->{"tag"}} = $control;
113
114     close(IN);
115   }
116
117   foreach my $control (values(%all_controls)) {
118     foreach my $dependency (@{$control->{"depends"}}) {
119       _control_error($form, $control->{"file"}, sprintf($locale->text("Unknown dependency '%s'."), $dependency)) if (!defined($all_controls{$dependency}));
120     }
121
122     map({ $_->{"loop"} = 0; } values(%all_controls));
123     _check_for_loops($form, $control->{"file"}, \%all_controls, $control->{"tag"});
124   }
125
126   map({ _dbupdate2_calculate_depth(\%all_controls, $_->{"tag"}) }
127       values(%all_controls));
128
129   $self->{all_controls} = \%all_controls;
130
131   return $self;
132 }
133
134 sub process_query {
135   $::lxdebug->enter_sub();
136
137   my ($self, $dbh, $filename, $version_or_control) = @_;
138
139   my $form  = $self->{form};
140   my $fh    = IO::File->new($filename, "<:encoding(UTF-8)");
141   my $query = "";
142   my $sth;
143   my @quote_chars;
144
145   if (!$fh) {
146     return "No such file: $filename" if $self->{return_on_error};
147     $form->error("$filename : $!\n");
148   }
149
150   $dbh->begin_work();
151
152   while (<$fh>) {
153     # Remove DOS and Unix style line endings.
154     chomp;
155
156     for (my $i = 0; $i < length($_); $i++) {
157       my $char = substr($_, $i, 1);
158
159       # Are we inside a string?
160       if (@quote_chars) {
161         if ($char eq $quote_chars[-1]) {
162           pop(@quote_chars);
163         } elsif (length $quote_chars[-1] > 1
164              &&  substr($_, $i, length $quote_chars[-1]) eq $quote_chars[-1]) {
165           $i   += length($quote_chars[-1]) - 1;
166           $char = $quote_chars[-1];
167           pop(@quote_chars);
168         }
169         $query .= $char;
170
171       } else {
172         my ($tag, $tag_end);
173         if (($char eq "'") || ($char eq "\"")) {
174           push(@quote_chars, $char);
175
176         } elsif ($char eq '$'                                            # start of dollar quoting
177              && ($tag_end  = index($_, '$', $i + 1)) > -1                # ends on same line
178              && (do { $tag = substr($_, $i + 1, $tag_end - $i - 1); 1 }) # extract tag
179              &&  $tag      =~ /^ (?= [A-Za-z_] [A-Za-z0-9_]* | ) $/x) {  # tag is identifier
180           push @quote_chars, $char = '$' . $tag . '$';
181           $i = $tag_end;
182         } elsif ($char eq "-") {
183           if ( substr($_, $i+1, 1) eq "-") {
184             # found a comment outside quote
185             last;
186           }
187         } elsif ($char eq ";") {
188
189           # Query is complete. Send it.
190
191           $sth = $dbh->prepare($query);
192           if (!$sth->execute()) {
193             my $errstr = $dbh->errstr;
194             return $errstr // '<unknown database error>' if $self->{return_on_error};
195             $sth->finish();
196             $dbh->rollback();
197             if (!ref $version_or_control || ref $version_or_control ne 'HASH' || !$version_or_control->{may_fail})  {
198               $form->dberror("The database update/creation did not succeed. " .
199                              "The file ${filename} containing the following " .
200                              "query failed:<br>${query}<br>" .
201                              "The error message was: ${errstr}<br>" .
202                              "All changes in that file have been reverted.")
203             }
204           }
205           $sth->finish();
206
207           $char  = "";
208           $query = "";
209         }
210
211         $query .= $char;
212       }
213     }
214
215     # Insert a space at the end of each line so that queries split
216     # over multiple lines work properly.
217     if ($query ne '') {
218       $query .= @quote_chars ? "\n" : ' ';
219     }
220   }
221
222   if (ref($version_or_control) eq "HASH") {
223     $dbh->do("INSERT INTO " . $self->{schema} . "schema_info (tag, login) VALUES (" . $dbh->quote($version_or_control->{"tag"}) . ", " . $dbh->quote($form->{"login"}) . ")");
224   } elsif ($version_or_control) {
225     $dbh->do("UPDATE defaults SET version = " . $dbh->quote($version_or_control));
226   }
227   $dbh->commit();
228
229   $fh->close();
230
231   $::lxdebug->leave_sub();
232
233   # Signal "no error"
234   return undef;
235 }
236
237 # Process a Perl script which updates the database.
238 # If the script returns 1 then the update was successful.
239 # Return code "2" means "needs more interaction; unlock
240 # the system and end current request".
241 # All other return codes are fatal errors.
242 sub process_perl_script {
243   $::lxdebug->enter_sub();
244
245   my ($self, $dbh, $filename, $version_or_control) = @_;
246
247   my %form_values = %$::form;
248
249   $dbh->begin_work;
250
251   # setup dbup_ export vars & run script
252   my %dbup_myconfig = map { ($_ => $::form->{$_}) } qw(dbname dbuser dbpasswd dbhost dbport dbconnect);
253   my $result        = eval {
254     SL::DBUpgrade2::Base::execute_script(
255       file_name => $filename,
256       tag       => $version_or_control->{tag},
257       dbh       => $dbh,
258       myconfig  => \%dbup_myconfig,
259     );
260   };
261
262   my $error = $EVAL_ERROR;
263
264   $dbh->rollback if 1 != ($result // -1);
265
266   return $error if $self->{return_on_error} && (1 != ($result // -1));
267
268   if (!defined($result)) {
269     print $::form->parse_html_template("dbupgrade/error", { file  => $filename, error => $error });
270     $::dispatcher->end_request;
271   } elsif (1 != $result) {
272     SL::System::InstallationLock->unlock if 2 == $result;
273     $::dispatcher->end_request;
274   }
275
276   if (ref($version_or_control) eq "HASH") {
277     $dbh->do("INSERT INTO " . $self->{schema} . "schema_info (tag, login) VALUES (" . $dbh->quote($version_or_control->{tag}) . ", " . $dbh->quote($::form->{login}) . ")");
278   } elsif ($version_or_control) {
279     $dbh->do("UPDATE defaults SET version = " . $dbh->quote($version_or_control));
280   }
281
282   $dbh->commit if !$dbh->{AutoCommit} || $dbh->{BegunWork};
283
284   # Clear $::form of values that may have been set so that following
285   # Perl upgrade scripts won't have to work with old data (think of
286   # the usual 'continued' mechanism that's used for determining
287   # whether or not the upgrade form must be displayed).
288   delete @{ $::form }{ keys %{ $::form } };
289   $::form->{$_} = $form_values{$_} for keys %form_values;
290
291   $::lxdebug->leave_sub();
292
293   return undef;
294 }
295
296 sub process_file {
297   my ($self, $dbh, $filename, $version_or_control) = @_;
298
299   my $result = $filename =~ m/sql$/ ? $self->process_query(      $dbh, $filename, $version_or_control)
300                                     : $self->process_perl_script($dbh, $filename, $version_or_control);
301
302   $::lxdebug->log_time("DB upgrade script '${filename}' finished");
303
304   return $result;
305 }
306
307 sub unapplied_upgrade_scripts {
308   my ($self, $dbh) = @_;
309
310   my @all_scripts = map { $_->{applied} = 0; $_ } $self->sort_dbupdate_controls;
311
312   my $query = qq|SELECT tag FROM | . $self->{schema} . qq|schema_info|;
313   my $sth   = $dbh->prepare($query);
314   $sth->execute || $self->{form}->dberror($query);
315   while (my ($tag) = $sth->fetchrow_array()) {
316     $self->{all_controls}->{$tag}->{applied} = 1 if defined $self->{all_controls}->{$tag};
317   }
318   $sth->finish;
319
320   return grep { !$_->{applied} } @all_scripts;
321 }
322
323 sub update2_available {
324   my ($self, $dbh) = @_;
325
326   my @unapplied_scripts = $self->unapplied_upgrade_scripts($dbh);
327
328   return !!@unapplied_scripts;
329 }
330
331 sub apply_admin_dbupgrade_scripts {
332   my ($self, $called_from_admin) = @_;
333
334   return 0 if !$self->{auth};
335
336   my $dbh               = $::auth->dbconnect;
337   my @unapplied_scripts = $self->unapplied_upgrade_scripts($dbh);
338
339   return 0 if !@unapplied_scripts;
340
341   $self->{form}->{login} ||= 'admin';
342
343   if ($called_from_admin) {
344     $self->{form}->{title} = $::locale->text('Dataset upgrade');
345     $self->{form}->header;
346   }
347
348   print $self->{form}->parse_html_template("dbupgrade/header", { dbname => $::auth->{DB_config}->{db} });
349
350   $::lxdebug->log_time("DB upgrades commencing");
351
352   foreach my $control (@unapplied_scripts) {
353     $::lxdebug->message(LXDebug->DEBUG2(), "Applying Update $control->{file}");
354     print $self->{form}->parse_html_template("dbupgrade/upgrade_message2", $control);
355
356     $self->process_file($dbh, "sql/Pg-upgrade2-auth/$control->{file}", $control);
357   }
358
359   $::lxdebug->log_time("DB upgrades finished");
360
361   print $self->{form}->parse_html_template("dbupgrade/footer", { is_admin => 1 }) if $called_from_admin;
362
363   return 1;
364 }
365
366 sub _check_for_loops {
367   my ($form, $file_name, $controls, $tag, @path) = @_;
368
369   push(@path, $tag);
370
371   my $ctrl = $controls->{$tag};
372
373   if ($ctrl->{"loop"} == 1) {
374     # Not done yet.
375     _control_error($form, $file_name, $::locale->text("Dependency loop detected:") . " " . join(" -> ", @path))
376
377   } elsif ($ctrl->{"loop"} == 0) {
378     # Not checked yet.
379     $ctrl->{"loop"} = 1;
380     map({ _check_for_loops($form, $file_name, $controls, $_, @path); } @{ $ctrl->{"depends"} });
381     $ctrl->{"loop"} = 2;
382   }
383 }
384
385 sub _control_error {
386   my ($form, $file_name, $message) = @_;
387
388   $form = $::form;
389   my $locale = $::locale;
390
391   $form->error(sprintf($locale->text("Error in database control file '%s': %s"), $file_name, $message));
392 }
393
394 sub _dbupdate2_calculate_depth {
395   my ($tree, $tag) = @_;
396
397   my $node = $tree->{$tag};
398
399   return if (defined($node->{"depth"}));
400
401   my $max_depth = 0;
402
403   foreach $tag (@{$node->{"depends"}}) {
404     _dbupdate2_calculate_depth($tree, $tag);
405     my $value = $tree->{$tag}->{"depth"};
406     $max_depth = $value if ($value > $max_depth);
407   }
408
409   $node->{"depth"} = $max_depth + 1;
410 }
411
412 sub sort_dbupdate_controls {
413   my $self = shift;
414
415   $self->parse_dbupdate_controls unless $self->{all_controls};
416
417   return sort { ($a->{depth} <=> $b->{depth}) || ($a->{priority} <=> $b->{priority}) || ($a->{tag} cmp $b->{tag}) } values %{ $self->{all_controls} };
418 }
419
420 1;
421 __END__
422
423 =pod
424
425 =encoding utf8
426
427 =head1 NAME
428
429 SL::DBUpgrade2 - Parse database upgrade files stored in
430 C<sql/Pg-upgrade2> and C<sql/Pg-upgrade2-auth>
431
432 =head1 SYNOPSIS
433
434   use SL::User;
435   use SL::DBUpgrade2;
436
437   # Apply outstanding updates to the authentication database
438   my $scripts = SL::DBUpgrade2->new(
439     form     => $::form,
440     auth     => 1
441   );
442   $scripts->apply_admin_dbupgrade_scripts(1);
443
444   # Apply updates to a user database
445   my $scripts = SL::DBUpgrade2->new(
446     form     => $::form,
447     auth     => 1
448   );
449   User->dbupdate2(form     => $form,
450                   updater  => $scripts->parse_dbupdate_controls,
451                   database => $dbname);
452
453 =head1 OVERVIEW
454
455 Database upgrade files are used to upgrade the database structure and
456 content of both the authentication database and the user
457 databases. They're applied when a user logs in. As long as the
458 authentication database is not up to date users cannot log in in
459 general, and the admin has to log in first in order to get his
460 database updated.
461
462 Database scripts form a tree by specifying which upgrade file depends
463 on which other upgrade file. This means that such files are always
464 applied in a well-defined order.
465
466 Each script is run in a separate transaction. If a script fails the
467 current transaction is rolled back and the whole upgrade process is
468 stopped. The user/admin is required to fix the issue manually.
469
470 A list of applied upgrade scripts is maintained in a table called
471 C<schema_info> for the user database and C<auth.schema_info>) for the
472 authentication database. They contain the tags, the login name of the
473 user having applied the script and the timestamp when the script was
474 applied.
475
476 Database upgrade files come in two flavours: SQL files and Perl
477 files. For both there are control fields that determine the order in
478 which they're executed etc. The control fields are tag/value pairs
479 contained in comments.
480
481 =head1 CONTROL FIELDS
482
483 =head2 SYNTAX
484
485 Control fields for Perl files:
486
487   # @tag1: value1
488   # @tag2: some more values
489   sub do_stuff {
490   }
491   1;
492
493 Control fields for SQL files:
494
495   -- @tag1: value1
496   -- @tag2: some more values
497   ALTER TABLE ...;
498
499 =head2 TAGS AND THEIR MEANING
500
501 The following tags are recognized:
502
503 =over 4
504
505 =item tag
506
507 The name for this file. The C<tag> is also used for dependency
508 resolution (see C<depends>).
509
510 This is mandatory.
511
512 =item description
513
514 A description presented to the user when the update is applied.
515
516 This is mandatory.
517
518 =item depends
519
520 A space-separated list of tags of scripts this particular script
521 depends on. All other upgrades listed in C<depends> will be applied
522 before the current one is applied.
523
524 =item priority
525
526 Ordering the scripts by their dependencies alone produces a lot of
527 groups of scripts that could be applied at the same time (e.g. if both
528 B and C depend only on A then B could be applied before C or the other
529 way around). This field determines the order inside such a
530 group. Scripts with lower priority fields are executed before scripts
531 with higher priority fields.
532
533 If two scripts have equal priorities then their tag name decides.
534
535 The priority defaults to 1000.
536
537 =back
538
539 =head1 FUNCTIONS
540
541 =over 4
542
543 =item C<apply_admin_dbupgrade_scripts $called_from_admin>
544
545 Applies all unapplied upgrade files to the authentication/admin
546 database. The parameter C<$called_from_admin> should be truish if the
547 function is called from the web interface and falsish if it's called
548 from e.g. a command line script like C<scripts/dbupgrade2_tool.pl>.
549
550 =item C<init %params>
551
552 Initializes the object. Is called directly from L<new> and should not
553 be called again.
554
555 =item C<new %params>
556
557 Creates a new object. Possible parameters are:
558
559 =over 4
560
561 =item path
562
563 Path to the upgrade files to parse. Required.
564
565 =item form
566
567 C<SL::Form> object to use. Required.
568
569 =item auth
570
571 Optional parameter defaulting to 0. If trueish then the scripts read
572 are the ones applying to the authentication database.
573
574 =back
575
576 =item C<parse_dbupdate_controls>
577
578 Parses all files located in C<path> (see L<new>), ananlyzes their
579 control fields, builds the tree, and signals errors if control fields
580 are missing/wrong (e.g. a tag name listed in C<depends> is not
581 found). Sets C<$Self-&gt;{all_controls}> to the list of database
582 scripts.
583
584 =item C<process_file $dbh, $filename, $version_or_control>
585
586 Applies a single database upgrade file. Calls L<process_perl_script>
587 for Perl update files and C<process_query> for SQL update
588 files. Requires an open database handle(C<$dbh>), the file name
589 (C<$filename>) and a hash structure of the file's control fields as
590 produced by L<parse_dbupdate_controls> (C<$version_or_control>).
591
592 Returns the result of the actual function called.
593
594 =item C<process_perl_script $dbh, $filename, $version_or_control>
595
596 Applies a single Perl database upgrade file. Requires an open database
597 handle(C<$dbh>), the file name (C<$filename>) and a hash structure of
598 the file's control fields as produced by L<parse_dbupdate_controls>
599 (C<$version_or_control>).
600
601 Perl scripts are executed via L<eval>. If L<eval> returns falsish then
602 an error is expected. There are two special return values: If the
603 script returns C<1> then the update was successful. Return code C<2>
604 means "needs more interaction from the user; unlock the system and
605 end current upgrade process". All other return codes are fatal errors.
606
607 Inside the Perl script several local variables exist that can be used:
608
609 =over 4
610
611 =item $dbup_locale
612
613 A locale object for translating messages
614
615 =item $dbh
616
617 The database handle (inside a transaction).
618
619 =item $::form
620
621 The global C<SL::Form> object.
622
623 =back
624
625 A Perl script can actually implement queries that fail while
626 continuing the process by handling the transaction itself, e.g. with
627 the following function:
628
629   sub do_query {
630     my ($query, $may_fail) = @_;
631
632     if (!$dbh->do($query)) {
633       die($dbup_locale->text("Database update error:") . "<br>$msg<br>" . $DBI::errstr) unless $may_fail;
634       $dbh->rollback();
635       $dbh->begin_work();
636     }
637   }
638
639 =item C<process_query $dbh, $filename, $version_or_control>
640
641 Applies a single SQL database upgrade file. Requires an open database
642 handle(C<$dbh>), the file name (C<$filename>), and a hash structure of
643 the file's control fields as produced by L<parse_dbupdate_controls>
644 (C<$version_or_control>).
645
646 =item C<sort_dbupdate_controls>
647
648 Sorts the database upgrade scripts according to their C<tag> and
649 C<priority> control fields. Returns a list of their hash
650 representations that can be applied in order.
651
652 =item C<unapplied_upgrade_scripts $dbh>
653
654 Returns a list if upgrade scripts (their internal hash representation)
655 that haven't been applied to a database yet. C<$dbh> is an open handle
656 to the database that is checked.
657
658 Requires that the scripts have been parsed.
659
660 =item C<update2_available $dbh>
661
662 Returns trueish if at least one upgrade script hasn't been applied to
663 a database yet. C<$dbh> is an open handle to the database that is
664 checked.
665
666 Requires that the scripts have been parsed.
667
668 =back
669
670 =head1 BUGS
671
672 Nothing here yet.
673
674 =head1 AUTHOR
675
676 Moritz Bunkus E<lt>m.bunkus@linet-services.deE<gt>
677
678 =cut