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