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