Merge branch 'master' of git@lx-office.linet-services.de: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{schame}      ||= '';
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;