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