7725bd6bc36e8074a98bf206b979b1f929af2749
[kivitendo-erp.git] / SL / DBUpgrade2.pm
1 package SL::DBUpgrade2;
2
3 use IO::File;
4
5 use SL::Common;
6 use SL::Iconv;
7
8 use strict;
9
10 sub new {
11   my ($package, $form, $dbdriver) = @_;
12   my $self                        = { form => $form, dbdriver => $dbdriver };
13   return bless($self, $package);
14 }
15
16 sub set_dbcharset {
17   my $self           = shift;
18   $self->{dbcharset} = shift;
19   return $self;
20 }
21
22 sub parse_dbupdate_controls {
23   $main::lxdebug->enter_sub();
24
25   my ($self) = @_;
26
27   my $form   = $self->{form};
28   my $locale = $main::locale;
29
30   local *IN;
31   my %all_controls;
32
33   my $path = "sql/" . $self->{dbdriver} . "-upgrade2";
34
35   foreach my $file_name (<$path/*.sql>, <$path/*.pl>) {
36     next unless (open(IN, $file_name));
37
38     my $file = $file_name;
39     $file =~ s|.*/||;
40
41     my $control = {
42       "priority" => 1000,
43       "depends"  => [],
44     };
45
46     while (<IN>) {
47       chomp();
48       next unless (/^(--|\#)\s*\@/);
49       s/^(--|\#)\s*\@//;
50       s/\s*$//;
51       next if ($_ eq "");
52
53       my @fields = split(/\s*:\s*/, $_, 2);
54       next unless (scalar(@fields) == 2);
55
56       if ($fields[0] eq "depends") {
57         push(@{$control->{"depends"}}, split(/\s+/, $fields[1]));
58       } else {
59         $control->{$fields[0]} = $fields[1];
60       }
61     }
62
63     next if ($control->{ignore});
64
65     $control->{charset} ||= Common::DEFAULT_CHARSET;
66
67     if (!$control->{"tag"}) {
68       _control_error($form, $file_name, $locale->text("Missing 'tag' field.")) ;
69     }
70
71     if ($control->{"tag"} =~ /[^a-zA-Z0-9_\(\)\-]/) {
72       _control_error($form, $file_name, $locale->text("The 'tag' field must only consist of alphanumeric characters or the carachters - _ ( )"))
73     }
74
75     if (defined($all_controls{$control->{"tag"}})) {
76       _control_error($form, $file_name, sprintf($locale->text("More than one control file with the tag '%s' exist."), $control->{"tag"}))
77     }
78
79     if (!$control->{"description"}) {
80       _control_error($form, $file_name, sprintf($locale->text("Missing 'description' field."))) ;
81     }
82
83     $control->{"priority"}  *= 1;
84     $control->{"priority"} ||= 1000;
85     $control->{"file"}       = $file;
86
87     delete @{$control}{qw(depth applied)};
88
89     $all_controls{$control->{"tag"}} = $control;
90
91     close(IN);
92   }
93
94   foreach my $control (values(%all_controls)) {
95     foreach my $dependency (@{$control->{"depends"}}) {
96       _control_error($form, $control->{"file"}, sprintf($locale->text("Unknown dependency '%s'."), $dependency)) if (!defined($all_controls{$dependency}));
97     }
98
99     map({ $_->{"loop"} = 0; } values(%all_controls));
100     _check_for_loops($form, $control->{"file"}, \%all_controls, $control->{"tag"});
101   }
102
103   map({ _dbupdate2_calculate_depth(\%all_controls, $_->{"tag"}) }
104       values(%all_controls));
105
106   $self->{all_controls} = \%all_controls;
107
108   $main::lxdebug->leave_sub();
109
110   return \%all_controls;
111 }
112
113 sub process_query {
114   $main::lxdebug->enter_sub();
115
116   my ($self, $dbh, $filename, $version_or_control, $db_charset) = @_;
117
118   my $form  = $self->{form};
119   my $fh    = IO::File->new($filename, "r") or $form->error("$filename : $!\n");
120   my $query = "";
121   my $sth;
122   my @quote_chars;
123
124   my $file_charset = Common::DEFAULT_CHARSET;
125   while (<$fh>) {
126     last if !/^--/;
127     next if !/^--\s*\@charset:\s*(.+)/;
128     $file_charset = $1;
129     last;
130   }
131   $fh->seek(0, SEEK_SET);
132
133   $db_charset ||= Common::DEFAULT_CHARSET;
134
135   $dbh->begin_work();
136
137   while (<$fh>) {
138     $_ = SL::Iconv::convert($file_charset, $db_charset, $_);
139
140     # Remove DOS and Unix style line endings.
141     chomp;
142
143     # remove comments
144     s/--.*$//;
145
146     for (my $i = 0; $i < length($_); $i++) {
147       my $char = substr($_, $i, 1);
148
149       # Are we inside a string?
150       if (@quote_chars) {
151         if ($char eq $quote_chars[-1]) {
152           pop(@quote_chars);
153         }
154         $query .= $char;
155
156       } else {
157         if (($char eq "'") || ($char eq "\"")) {
158           push(@quote_chars, $char);
159
160         } elsif ($char eq ";") {
161
162           # Query is complete. Send it.
163
164           $sth = $dbh->prepare($query);
165           if (!$sth->execute()) {
166             my $errstr = $dbh->errstr;
167             $sth->finish();
168             $dbh->rollback();
169             $form->dberror("The database update/creation did not succeed. " .
170                            "The file ${filename} containing the following " .
171                            "query failed:<br>${query}<br>" .
172                            "The error message was: ${errstr}<br>" .
173                            "All changes in that file have been reverted.");
174           }
175           $sth->finish();
176
177           $char  = "";
178           $query = "";
179         }
180
181         $query .= $char;
182       }
183     }
184
185     # Insert a space at the end of each line so that queries split
186     # over multiple lines work properly.
187     if ($query ne '') {
188       $query .= @quote_chars ? "\n" : ' ';
189     }
190   }
191
192   if (ref($version_or_control) eq "HASH") {
193     $dbh->do("INSERT INTO schema_info (tag, login) VALUES (" .
194              $dbh->quote($version_or_control->{"tag"}) . ", " .
195              $dbh->quote($form->{"login"}) . ")");
196   } elsif ($version_or_control) {
197     $dbh->do("UPDATE defaults SET version = " .
198              $dbh->quote($version_or_control));
199   }
200   $dbh->commit();
201
202   $fh->close();
203
204   $main::lxdebug->leave_sub();
205 }
206
207 # Process a Perl script which updates the database.
208 # If the script returns 1 then the update was successful.
209 # Return code "2" means "needs more interaction; remove
210 # users/nologin and end current request".
211 # All other return codes are fatal errors.
212 sub process_perl_script {
213   $main::lxdebug->enter_sub();
214
215   my ($self, $dbh, $filename, $version_or_control, $db_charset) = @_;
216
217   my $form         = $self->{form};
218   my $fh           = IO::File->new($filename, "r") or $form->error("$filename : $!\n");
219   my $file_charset = Common::DEFAULT_CHARSET;
220
221   if (ref($version_or_control) eq "HASH") {
222     $file_charset = $version_or_control->{charset};
223
224   } else {
225     while (<$fh>) {
226       last if !/^--/;
227       next if !/^--\s*\@charset:\s*(.+)/;
228       $file_charset = $1;
229       last;
230     }
231     $fh->seek(0, SEEK_SET);
232   }
233
234   my $contents = join "", <$fh>;
235   $fh->close();
236
237   $db_charset ||= Common::DEFAULT_CHARSET;
238
239   my $iconv = SL::Iconv::get_converter($file_charset, $db_charset);
240
241   $dbh->begin_work();
242
243   # setup dbup_ export vars
244   my %dbup_myconfig = ();
245   map({ $dbup_myconfig{$_} = $form->{$_}; } qw(dbname dbuser dbpasswd dbhost dbport dbconnect));
246
247   my $dbup_locale = $::locale;
248
249   my $result = eval($contents);
250
251   if (1 != $result) {
252     $dbh->rollback();
253     $dbh->disconnect();
254   }
255
256   if (!defined($result)) {
257     print $form->parse_html_template("dbupgrade/error",
258                                      { "file"  => $filename,
259                                        "error" => $@ });
260     ::end_of_request();
261   } elsif (1 != $result) {
262     unlink("users/nologin") if (2 == $result);
263     ::end_of_request();
264   }
265
266   if (ref($version_or_control) eq "HASH") {
267     $dbh->do("INSERT INTO schema_info (tag, login) VALUES (" .
268              $dbh->quote($version_or_control->{"tag"}) . ", " .
269              $dbh->quote($form->{"login"}) . ")");
270   } elsif ($version_or_control) {
271     $dbh->do("UPDATE defaults SET version = " .
272              $dbh->quote($version_or_control));
273   }
274   $dbh->commit();
275
276   $main::lxdebug->leave_sub();
277 }
278
279 sub _check_for_loops {
280   my ($form, $file_name, $controls, $tag, @path) = @_;
281
282   push(@path, $tag);
283
284   my $ctrl = $controls->{$tag};
285
286   if ($ctrl->{"loop"} == 1) {
287     # Not done yet.
288     _control_error($form, $file_name, $main::locale->text("Dependency loop detected:") . " " . join(" -> ", @path))
289
290   } elsif ($ctrl->{"loop"} == 0) {
291     # Not checked yet.
292     $ctrl->{"loop"} = 1;
293     map({ _check_for_loops($form, $file_name, $controls, $_, @path); } @{ $ctrl->{"depends"} });
294     $ctrl->{"loop"} = 2;
295   }
296 }
297
298 sub _control_error {
299   my ($form, $file_name, $message) = @_;
300
301   $form = $main::form;
302   my $locale = $main::locale;
303
304   $form->error(sprintf($locale->text("Error in database control file '%s': %s"), $file_name, $message));
305 }
306
307 sub _dbupdate2_calculate_depth {
308   $main::lxdebug->enter_sub(2);
309
310   my ($tree, $tag) = @_;
311
312   my $node = $tree->{$tag};
313
314   return $main::lxdebug->leave_sub(2) if (defined($node->{"depth"}));
315
316   my $max_depth = 0;
317
318   foreach $tag (@{$node->{"depends"}}) {
319     _dbupdate2_calculate_depth($tree, $tag);
320     my $value = $tree->{$tag}->{"depth"};
321     $max_depth = $value if ($value > $max_depth);
322   }
323
324   $node->{"depth"} = $max_depth + 1;
325
326   $main::lxdebug->leave_sub(2);
327 }
328
329 sub sort_dbupdate_controls {
330   my $self = shift;
331
332   return sort({   $a->{"depth"}    !=  $b->{"depth"}    ? $a->{"depth"}    <=> $b->{"depth"}
333                 : $a->{"priority"} !=  $b->{"priority"} ? $a->{"priority"} <=> $b->{"priority"}
334                 :                                         $a->{"tag"}      cmp $b->{"tag"}      } values(%{ $self->{all_controls} }));
335 }
336
337 1;