Commit nach DB-Upgrade auch, wenn AutoCommit aus ist
[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::Iconv;
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}          = "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   $::lxdebug->enter_sub();
43
44   my ($self) = @_;
45
46   my $form   = $self->{form};
47   my $locale = $::locale;
48
49   local *IN;
50   my %all_controls;
51
52   my $path = $self->path;
53
54   foreach my $file_name (<$path/*.sql>, <$path/*.pl>) {
55     next unless (open(IN, $file_name));
56
57     my $file = $file_name;
58     $file =~ s|.*/||;
59
60     my $control = {
61       "priority" => 1000,
62       "depends"  => [],
63     };
64
65     while (<IN>) {
66       chomp();
67       next unless (/^(--|\#)\s*\@/);
68       s/^(--|\#)\s*\@//;
69       s/\s*$//;
70       next if ($_ eq "");
71
72       my @fields = split(/\s*:\s*/, $_, 2);
73       next unless (scalar(@fields) == 2);
74
75       if ($fields[0] eq "depends") {
76         push(@{$control->{"depends"}}, split(/\s+/, $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   $::lxdebug->leave_sub();
126
127   return $self;
128 }
129
130 sub process_query {
131   $::lxdebug->enter_sub();
132
133   my ($self, $dbh, $filename, $version_or_control) = @_;
134
135   my $form  = $self->{form};
136   my $fh    = IO::File->new($filename, "r");
137   my $query = "";
138   my $sth;
139   my @quote_chars;
140
141   if (!$fh) {
142     return "No such file: $filename" if $self->{return_on_error};
143     $form->error("$filename : $!\n");
144   }
145
146   $dbh->begin_work();
147
148   while (<$fh>) {
149     $_ = SL::Iconv::convert('UTF-8', 'UTF-8', $_);
150
151     # Remove DOS and Unix style line endings.
152     chomp;
153
154     # remove comments
155     s/--.*$//;
156
157     for (my $i = 0; $i < length($_); $i++) {
158       my $char = substr($_, $i, 1);
159
160       # Are we inside a string?
161       if (@quote_chars) {
162         if ($char eq $quote_chars[-1]) {
163           pop(@quote_chars);
164         } elsif (length $quote_chars[-1] > 1
165              &&  substr($_, $i, length $quote_chars[-1]) eq $quote_chars[-1]) {
166           $i   += length($quote_chars[-1]) - 1;
167           $char = $quote_chars[-1];
168           pop(@quote_chars);
169         }
170         $query .= $char;
171
172       } else {
173         my ($tag, $tag_end);
174         if (($char eq "'") || ($char eq "\"")) {
175           push(@quote_chars, $char);
176
177         } elsif ($char eq '$'                                            # start of dollar quoting
178              && ($tag_end  = index($_, '$', $i + 1)) > -1                # ends on same line
179              && (do { $tag = substr($_, $i + 1, $tag_end - $i - 1); 1 }) # extract tag
180              &&  $tag      =~ /^ (?= [A-Za-z_] [A-Za-z0-9_]* | ) $/x) {  # tag is identifier
181           push @quote_chars, $char = '$' . $tag . '$';
182           $i = $tag_end;
183         } elsif ($char eq ";") {
184
185           # Query is complete. Send it.
186
187           $sth = $dbh->prepare($query);
188           if (!$sth->execute()) {
189             my $errstr = $dbh->errstr;
190             return $errstr // '<unknown database error>' if $self->{return_on_error};
191             $sth->finish();
192             $dbh->rollback();
193             $form->dberror("The database update/creation did not succeed. " .
194                            "The file ${filename} containing the following " .
195                            "query failed:<br>${query}<br>" .
196                            "The error message was: ${errstr}<br>" .
197                            "All changes in that file have been reverted.");
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 = map { $_ => $::form->{$_} } qw(dbconnect dbdefault dbhost dbmbkiviunstable dbname dboptions dbpasswd dbport dbupdate dbuser login template_object version);
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     ::end_of_request();
265   } elsif (1 != $result) {
266     SL::System::InstallationLock->unlock if 2 == $result;
267     ::end_of_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 update2_available {
298   $::lxdebug->enter_sub();
299
300   my ($self, $dbh) = @_;
301
302   map { $_->{applied} = 0; } values %{ $self->{all_controls} };
303
304   my $sth = $dbh->prepare(qq|SELECT tag FROM | . $self->{schema} . qq|schema_info|);
305   if ($sth->execute) {
306     while (my ($tag) = $sth->fetchrow_array) {
307       $self->{all_controls}->{$tag}->{applied} = 1 if defined $self->{all_controls}->{$tag};
308     }
309   }
310   $sth->finish();
311
312   my $needs_update = any { !$_->{applied} } values %{ $self->{all_controls} };
313
314   $::lxdebug->leave_sub();
315
316   return $needs_update;
317 }
318
319 sub unapplied_upgrade_scripts {
320   my ($self, $dbh) = @_;
321
322   my @all_scripts = map { $_->{applied} = 0; $_ } $self->sort_dbupdate_controls;
323
324   my $query = qq|SELECT tag FROM | . $self->{schema} . qq|schema_info|;
325   my $sth   = $dbh->prepare($query);
326   $sth->execute || $self->{form}->dberror($query);
327   while (my ($tag) = $sth->fetchrow_array()) {
328     $self->{all_controls}->{$tag}->{applied} = 1 if defined $self->{all_controls}->{$tag};
329   }
330   $sth->finish;
331
332   return grep { !$_->{applied} } @all_scripts;
333 }
334
335 sub apply_admin_dbupgrade_scripts {
336   my ($self, $called_from_admin) = @_;
337
338   return 0 if !$self->{auth};
339
340   my $dbh               = $::auth->dbconnect;
341   my @unapplied_scripts = $self->unapplied_upgrade_scripts($dbh);
342
343   return 0 if !@unapplied_scripts;
344
345   $self->{form}->{login} ||= 'admin';
346
347   map { $_->{description} = SL::Iconv::convert('UTF-8', 'UTF-8', $_->{description}) } values %{ $self->{all_controls} };
348
349   if ($called_from_admin) {
350     $self->{form}->{title} = $::locale->text('Dataset upgrade');
351     $self->{form}->header;
352   }
353
354   print $self->{form}->parse_html_template("dbupgrade/header", { dbname => $::auth->{DB_config}->{db} });
355
356   foreach my $control (@unapplied_scripts) {
357     $::lxdebug->message(LXDebug->DEBUG2(), "Applying Update $control->{file}");
358     print $self->{form}->parse_html_template("dbupgrade/upgrade_message2", $control);
359
360     $self->process_file($dbh, "sql/Pg-upgrade2-auth/$control->{file}", $control);
361   }
362
363   print $self->{form}->parse_html_template("dbupgrade/footer", { is_admin => 1 }) if $called_from_admin;
364
365   return 1;
366 }
367
368 sub _check_for_loops {
369   my ($form, $file_name, $controls, $tag, @path) = @_;
370
371   push(@path, $tag);
372
373   my $ctrl = $controls->{$tag};
374
375   if ($ctrl->{"loop"} == 1) {
376     # Not done yet.
377     _control_error($form, $file_name, $::locale->text("Dependency loop detected:") . " " . join(" -> ", @path))
378
379   } elsif ($ctrl->{"loop"} == 0) {
380     # Not checked yet.
381     $ctrl->{"loop"} = 1;
382     map({ _check_for_loops($form, $file_name, $controls, $_, @path); } @{ $ctrl->{"depends"} });
383     $ctrl->{"loop"} = 2;
384   }
385 }
386
387 sub _control_error {
388   my ($form, $file_name, $message) = @_;
389
390   $form = $::form;
391   my $locale = $::locale;
392
393   $form->error(sprintf($locale->text("Error in database control file '%s': %s"), $file_name, $message));
394 }
395
396 sub _dbupdate2_calculate_depth {
397   $::lxdebug->enter_sub(2);
398
399   my ($tree, $tag) = @_;
400
401   my $node = $tree->{$tag};
402
403   return $::lxdebug->leave_sub(2) if (defined($node->{"depth"}));
404
405   my $max_depth = 0;
406
407   foreach $tag (@{$node->{"depends"}}) {
408     _dbupdate2_calculate_depth($tree, $tag);
409     my $value = $tree->{$tag}->{"depth"};
410     $max_depth = $value if ($value > $max_depth);
411   }
412
413   $node->{"depth"} = $max_depth + 1;
414
415   $::lxdebug->leave_sub(2);
416 }
417
418 sub sort_dbupdate_controls {
419   my $self = shift;
420
421   $self->parse_dbupdate_controls unless $self->{all_controls};
422
423   return sort { ($a->{depth} <=> $b->{depth}) || ($a->{priority} <=> $b->{priority}) || ($a->{tag} cmp $b->{tag}) } values %{ $self->{all_controls} };
424 }
425
426 1;
427 __END__
428
429 =pod
430
431 =encoding utf8
432
433 =head1 NAME
434
435 SL::DBUpgrade2 - Parse database upgrade files stored in
436 C<sql/Pg-upgrade2> and C<sql/Pg-upgrade2-auth>
437
438 =head1 SYNOPSIS
439
440   use SL::User;
441   use SL::DBUpgrade2;
442
443   # Apply outstanding updates to the authentication database
444   my $scripts = SL::DBUpgrade2->new(
445     form     => $::form,
446     auth     => 1
447   );
448   $scripts->apply_admin_dbupgrade_scripts(1);
449
450   # Apply updates to a user database
451   my $scripts = SL::DBUpgrade2->new(
452     form     => $::form,
453     auth     => 1
454   );
455   User->dbupdate2(form     => $form,
456                   updater  => $scripts->parse_dbupdate_controls,
457                   database => $dbname);
458
459 =head1 OVERVIEW
460
461 Database upgrade files are used to upgrade the database structure and
462 content of both the authentication database and the user
463 databases. They're applied when a user logs in. As long as the
464 authentication database is not up to date users cannot log in in
465 general, and the admin has to log in first in order to get his
466 database updated.
467
468 Database scripts form a tree by specifying which upgrade file depends
469 on which other upgrade file. This means that such files are always
470 applied in a well-defined order.
471
472 Each script is run in a separate transaction. If a script fails the
473 current transaction is rolled back and the whole upgrade process is
474 stopped. The user/admin is required to fix the issue manually.
475
476 A list of applied upgrade scripts is maintained in a table called
477 C<schema_info> for the user database and C<auth.schema_info>) for the
478 authentication database. They contain the tags, the login name of the
479 user having applied the script and the timestamp when the script was
480 applied.
481
482 Database upgrade files come in two flavours: SQL files and Perl
483 files. For both there are control fields that determine the order in
484 which they're executed etc. The control fields are tag/value pairs
485 contained in comments.
486
487 =head1 CONTROL FIELDS
488
489 =head2 SYNTAX
490
491 Control fields for Perl files:
492
493   # @tag1: value1
494   # @tag2: some more values
495   sub do_stuff {
496   }
497   1;
498
499 Control fields for SQL files:
500
501   -- @tag1: value1
502   -- @tag2: some more values
503   ALTER TABLE ...;
504
505 =head2 TAGS AND THEIR MEANING
506
507 The following tags are recognized:
508
509 =over 4
510
511 =item tag
512
513 The name for this file. The C<tag> is also used for dependency
514 resolution (see C<depends>).
515
516 This is mandatory.
517
518 =item description
519
520 A description presented to the user when the update is applied.
521
522 This is mandatory.
523
524 =item depends
525
526 A space-separated list of tags of scripts this particular script
527 depends on. All other upgrades listed in C<depends> will be applied
528 before the current one is applied.
529
530 =item priority
531
532 Ordering the scripts by their dependencies alone produces a lot of
533 groups of scripts that could be applied at the same time (e.g. if both
534 B and C depend only on A then B could be applied before C or the other
535 way around). This field determines the order inside such a
536 group. Scripts with lower priority fields are executed before scripts
537 with higher priority fields.
538
539 If two scripts have equal priorities then their tag name decides.
540
541 The priority defaults to 1000.
542
543 =back
544
545 =head1 FUNCTIONS
546
547 =over 4
548
549 =item C<apply_admin_dbupgrade_scripts $called_from_admin>
550
551 Applies all unapplied upgrade files to the authentication/admin
552 database. The parameter C<$called_from_admin> should be truish if the
553 function is called from the web interface and falsish if it's called
554 from e.g. a command line script like C<scripts/dbupgrade2_tool.pl>.
555
556 =item C<init %params>
557
558 Initializes the object. Is called directly from L<new> and should not
559 be called again.
560
561 =item C<new %params>
562
563 Creates a new object. Possible parameters are:
564
565 =over 4
566
567 =item path
568
569 Path to the upgrade files to parse. Required.
570
571 =item form
572
573 C<SL::Form> object to use. Required.
574
575 =item auth
576
577 Optional parameter defaulting to 0. If trueish then the scripts read
578 are the ones applying to the authentication database.
579
580 =back
581
582 =item C<parse_dbupdate_controls>
583
584 Parses all files located in C<path> (see L<new>), ananlyzes their
585 control fields, builds the tree, and signals errors if control fields
586 are missing/wrong (e.g. a tag name listed in C<depends> is not
587 found). Sets C<$Self-&gt;{all_controls}> to the list of database
588 scripts.
589
590 =item C<process_file $dbh, $filename, $version_or_control>
591
592 Applies a single database upgrade file. Calls L<process_perl_script>
593 for Perl update files and C<process_query> for SQL update
594 files. Requires an open database handle(C<$dbh>), the file name
595 (C<$filename>) and a hash structure of the file's control fields as
596 produced by L<parse_dbupdate_controls> (C<$version_or_control>).
597
598 Returns the result of the actual function called.
599
600 =item C<process_perl_script $dbh, $filename, $version_or_control>
601
602 Applies a single Perl database upgrade file. Requires an open database
603 handle(C<$dbh>), the file name (C<$filename>) and a hash structure of
604 the file's control fields as produced by L<parse_dbupdate_controls>
605 (C<$version_or_control>).
606
607 Perl scripts are executed via L<eval>. If L<eval> returns falsish then
608 an error is expected. There are two special return values: If the
609 script returns C<1> then the update was successful. Return code C<2>
610 means "needs more interaction from the user; unlock the system and
611 end current upgrade process". All other return codes are fatal errors.
612
613 Inside the Perl script several local variables exist that can be used:
614
615 =over 4
616
617 =item $dbup_locale
618
619 A locale object for translating messages
620
621 =item $dbh
622
623 The database handle (inside a transaction).
624
625 =item $::form
626
627 The global C<SL::Form> object.
628
629 =back
630
631 A Perl script can actually implement queries that fail while
632 continueing the process by handling the transaction itself, e.g. with
633 the following function:
634
635   sub do_query {
636     my ($query, $may_fail) = @_;
637
638     if (!$dbh->do($query)) {
639       die($dbup_locale->text("Database update error:") . "<br>$msg<br>" . $DBI::errstr) unless $may_fail;
640       $dbh->rollback();
641       $dbh->begin_work();
642     }
643   }
644
645 =item C<process_query $dbh, $filename, $version_or_control>
646
647 Applies a single SQL database upgrade file. Requires an open database
648 handle(C<$dbh>), the file name (C<$filename>), and a hash structure of
649 the file's control fields as produced by L<parse_dbupdate_controls>
650 (C<$version_or_control>).
651
652 =item C<sort_dbupdate_controls>
653
654 Sorts the database upgrade scripts according to their C<tag> and
655 C<priority> control fields. Returns a list of their hash
656 representations that can be applied in order.
657
658 =item C<unapplied_upgrade_scripts $dbh>
659
660 Returns a list if upgrade scripts (their internal hash representation)
661 that haven't been applied to a database yet. C<$dbh> is an open handle
662 to the database that is checked.
663
664 Requires that the scripts have been parsed.
665
666 =item C<update2_available $dbh>
667
668 Returns trueish if at least one upgrade script hasn't been applied to
669 a database yet. C<$dbh> is an open handle to the database that is
670 checked.
671
672 Requires that the scripts have been parsed.
673
674 =back
675
676 =head1 BUGS
677
678 Nothing here yet.
679
680 =head1 AUTHOR
681
682 Moritz Bunkus E<lt>m.bunkus@linet-services.deE<gt>
683
684 =cut