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