Funktion "process_query" von User.pm nach DBUpgrade2.pm verschoben
[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 sub _check_for_loops {
208   my ($form, $file_name, $controls, $tag, @path) = @_;
209
210   push(@path, $tag);
211
212   my $ctrl = $controls->{$tag};
213
214   if ($ctrl->{"loop"} == 1) {
215     # Not done yet.
216     _control_error($form, $file_name, $main::locale->text("Dependency loop detected:") . " " . join(" -> ", @path))
217
218   } elsif ($ctrl->{"loop"} == 0) {
219     # Not checked yet.
220     $ctrl->{"loop"} = 1;
221     map({ _check_for_loops($form, $file_name, $controls, $_, @path); } @{ $ctrl->{"depends"} });
222     $ctrl->{"loop"} = 2;
223   }
224 }
225
226 sub _control_error {
227   my ($form, $file_name, $message) = @_;
228
229   $form = $main::form;
230   my $locale = $main::locale;
231
232   $form->error(sprintf($locale->text("Error in database control file '%s': %s"), $file_name, $message));
233 }
234
235 sub _dbupdate2_calculate_depth {
236   $main::lxdebug->enter_sub(2);
237
238   my ($tree, $tag) = @_;
239
240   my $node = $tree->{$tag};
241
242   return $main::lxdebug->leave_sub(2) if (defined($node->{"depth"}));
243
244   my $max_depth = 0;
245
246   foreach $tag (@{$node->{"depends"}}) {
247     _dbupdate2_calculate_depth($tree, $tag);
248     my $value = $tree->{$tag}->{"depth"};
249     $max_depth = $value if ($value > $max_depth);
250   }
251
252   $node->{"depth"} = $max_depth + 1;
253
254   $main::lxdebug->leave_sub(2);
255 }
256
257 sub sort_dbupdate_controls {
258   my $self = shift;
259
260   return sort({   $a->{"depth"}    !=  $b->{"depth"}    ? $a->{"depth"}    <=> $b->{"depth"}
261                 : $a->{"priority"} !=  $b->{"priority"} ? $a->{"priority"} <=> $b->{"priority"}
262                 :                                         $a->{"tag"}      cmp $b->{"tag"}      } values(%{ $self->{all_controls} }));
263 }
264
265 1;