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