1 package SL::DBUpgrade2;
4 use List::MoreUtils qw(any);
14 return bless({}, $package)->init(@_);
18 my ($self, %params) = @_;
21 $params{path_suffix} = "-auth";
22 $params{schema} = "auth.";
25 $params{path_suffix} ||= '';
26 $params{schame} ||= '';
28 map { $self->{$_} = $params{$_} } keys %params;
33 sub parse_dbupdate_controls {
34 $::lxdebug->enter_sub();
38 my $form = $self->{form};
39 my $locale = $::locale;
44 my $path = "sql/" . $self->{dbdriver} . "-upgrade2" . $self->{path_suffix};
46 foreach my $file_name (<$path/*.sql>, <$path/*.pl>) {
47 next unless (open(IN, $file_name));
49 my $file = $file_name;
59 next unless (/^(--|\#)\s*\@/);
64 my @fields = split(/\s*:\s*/, $_, 2);
65 next unless (scalar(@fields) == 2);
67 if ($fields[0] eq "depends") {
68 push(@{$control->{"depends"}}, split(/\s+/, $fields[1]));
70 $control->{$fields[0]} = $fields[1];
74 next if ($control->{ignore});
76 $control->{charset} ||= Common::DEFAULT_CHARSET;
78 if (!$control->{"tag"}) {
79 _control_error($form, $file_name, $locale->text("Missing 'tag' field.")) ;
82 if ($control->{"tag"} =~ /[^a-zA-Z0-9_\(\)\-]/) {
83 _control_error($form, $file_name, $locale->text("The 'tag' field must only consist of alphanumeric characters or the carachters - _ ( )"))
86 if (defined($all_controls{$control->{"tag"}})) {
87 _control_error($form, $file_name, sprintf($locale->text("More than one control file with the tag '%s' exist."), $control->{"tag"}))
90 if (!$control->{"description"}) {
91 _control_error($form, $file_name, sprintf($locale->text("Missing 'description' field."))) ;
94 $control->{"priority"} *= 1;
95 $control->{"priority"} ||= 1000;
96 $control->{"file"} = $file;
98 delete @{$control}{qw(depth applied)};
100 $all_controls{$control->{"tag"}} = $control;
105 foreach my $control (values(%all_controls)) {
106 foreach my $dependency (@{$control->{"depends"}}) {
107 _control_error($form, $control->{"file"}, sprintf($locale->text("Unknown dependency '%s'."), $dependency)) if (!defined($all_controls{$dependency}));
110 map({ $_->{"loop"} = 0; } values(%all_controls));
111 _check_for_loops($form, $control->{"file"}, \%all_controls, $control->{"tag"});
114 map({ _dbupdate2_calculate_depth(\%all_controls, $_->{"tag"}) }
115 values(%all_controls));
117 $self->{all_controls} = \%all_controls;
119 $::lxdebug->leave_sub();
125 $::lxdebug->enter_sub();
127 my ($self, $dbh, $filename, $version_or_control, $db_charset) = @_;
129 my $form = $self->{form};
130 my $fh = IO::File->new($filename, "r") or $form->error("$filename : $!\n");
135 my $file_charset = Common::DEFAULT_CHARSET;
138 next if !/^--\s*\@charset:\s*(.+)/;
142 $fh->seek(0, SEEK_SET);
144 $db_charset ||= Common::DEFAULT_CHARSET;
149 $_ = SL::Iconv::convert($file_charset, $db_charset, $_);
151 # Remove DOS and Unix style line endings.
157 for (my $i = 0; $i < length($_); $i++) {
158 my $char = substr($_, $i, 1);
160 # Are we inside a string?
162 if ($char eq $quote_chars[-1]) {
168 if (($char eq "'") || ($char eq "\"")) {
169 push(@quote_chars, $char);
171 } elsif ($char eq ";") {
173 # Query is complete. Send it.
175 $sth = $dbh->prepare($query);
176 if (!$sth->execute()) {
177 my $errstr = $dbh->errstr;
180 $form->dberror("The database update/creation did not succeed. " .
181 "The file ${filename} containing the following " .
182 "query failed:<br>${query}<br>" .
183 "The error message was: ${errstr}<br>" .
184 "All changes in that file have been reverted.");
196 # Insert a space at the end of each line so that queries split
197 # over multiple lines work properly.
199 $query .= @quote_chars ? "\n" : ' ';
203 if (ref($version_or_control) eq "HASH") {
204 $dbh->do("INSERT INTO " . $self->{schema} . "schema_info (tag, login) VALUES (" . $dbh->quote($version_or_control->{"tag"}) . ", " . $dbh->quote($form->{"login"}) . ")");
205 } elsif ($version_or_control) {
206 $dbh->do("UPDATE defaults SET version = " . $dbh->quote($version_or_control));
212 $::lxdebug->leave_sub();
215 # Process a Perl script which updates the database.
216 # If the script returns 1 then the update was successful.
217 # Return code "2" means "needs more interaction; remove
218 # users/nologin and end current request".
219 # All other return codes are fatal errors.
220 sub process_perl_script {
221 $::lxdebug->enter_sub();
223 my ($self, $dbh, $filename, $version_or_control, $db_charset) = @_;
225 my $form = $self->{form};
226 my $fh = IO::File->new($filename, "r") or $form->error("$filename : $!\n");
227 my $file_charset = Common::DEFAULT_CHARSET;
229 if (ref($version_or_control) eq "HASH") {
230 $file_charset = $version_or_control->{charset};
235 next if !/^--\s*\@charset:\s*(.+)/;
239 $fh->seek(0, SEEK_SET);
242 my $contents = join "", <$fh>;
245 $db_charset ||= Common::DEFAULT_CHARSET;
247 my $iconv = SL::Iconv::get_converter($file_charset, $db_charset);
251 # setup dbup_ export vars
252 my %dbup_myconfig = ();
253 map({ $dbup_myconfig{$_} = $form->{$_}; } qw(dbname dbuser dbpasswd dbhost dbport dbconnect));
255 my $dbup_locale = $::locale;
257 my $result = eval($contents);
264 if (!defined($result)) {
265 print $form->parse_html_template("dbupgrade/error",
266 { "file" => $filename,
269 } elsif (1 != $result) {
270 unlink("users/nologin") if (2 == $result);
274 if (ref($version_or_control) eq "HASH") {
275 $dbh->do("INSERT INTO " . $self->{schema} . "schema_info (tag, login) VALUES (" . $dbh->quote($version_or_control->{"tag"}) . ", " . $dbh->quote($form->{"login"}) . ")");
276 } elsif ($version_or_control) {
277 $dbh->do("UPDATE defaults SET version = " . $dbh->quote($version_or_control));
281 $::lxdebug->leave_sub();
285 my ($self, $dbh, $filename, $version_or_control, $db_charset) = @_;
287 if ($filename =~ m/sql$/) {
288 $self->process_query($dbh, $filename, $version_or_control, $db_charset);
290 $self->process_perl_script($dbh, $filename, $version_or_control, $db_charset);
294 sub update_available {
295 my ($self, $cur_version) = @_;
299 my $dbdriver = $self->{dbdriver};
300 opendir SQLDIR, "sql/${dbdriver}-upgrade" || error("", "sql/${dbdriver}-upgrade: $!");
301 my @upgradescripts = grep /${dbdriver}-upgrade-\Q$cur_version\E.*\.(sql|pl)$/, readdir SQLDIR;
304 return ($#upgradescripts > -1);
307 sub update2_available {
308 $::lxdebug->enter_sub();
310 my ($self, $dbh) = @_;
312 map { $_->{applied} = 0; } values %{ $self->{all_controls} };
314 my $sth = $dbh->prepare(qq|SELECT tag FROM | . $self->{schema} . qq|schema_info|);
316 while (my ($tag) = $sth->fetchrow_array) {
317 $self->{all_controls}->{$tag}->{applied} = 1 if defined $self->{all_controls}->{$tag};
322 my $needs_update = any { !$_->{applied} } values %{ $self->{all_controls} };
324 $::lxdebug->leave_sub();
326 return $needs_update;
329 sub unapplied_upgrade_scripts {
330 my ($self, $dbh) = @_;
332 my @all_scripts = map { $_->{applied} = 0; $_ } $self->sort_dbupdate_controls;
334 my $query = qq|SELECT tag FROM | . $self->{schema} . qq|schema_info|;
335 my $sth = $dbh->prepare($query);
336 $sth->execute || $self->{form}->dberror($query);
337 while (my ($tag) = $sth->fetchrow_array()) {
338 $self->{all_controls}->{$tag}->{applied} = 1 if defined $self->{all_controls}->{$tag};
342 return grep { !$_->{applied} } @all_scripts;
345 sub apply_admin_dbupgrade_scripts {
346 my ($self, $called_from_admin) = @_;
348 return 0 if !$self->{auth};
350 my $dbh = $::auth->dbconnect;
351 my @unapplied_scripts = $self->unapplied_upgrade_scripts($dbh);
353 return 0 if !@unapplied_scripts;
355 my $db_charset = $main::dbcharset || Common::DEFAULT_CHARSET;
356 $self->{form}->{login} ||= 'admin';
358 map { $_->{description} = SL::Iconv::convert($_->{charset}, $db_charset, $_->{description}) } values %{ $self->{all_controls} };
360 if ($called_from_admin) {
361 $self->{form}->{title} = $::locale->text('Dataset upgrade');
362 $self->{form}->header;
365 print $self->{form}->parse_html_template("dbupgrade/header", { dbname => $::auth->{DB_config}->{db} });
367 foreach my $control (@unapplied_scripts) {
368 $::lxdebug->message(LXDebug->DEBUG2(), "Applying Update $control->{file}");
369 print $self->{form}->parse_html_template("dbupgrade/upgrade_message2", $control);
371 $self->process_file($dbh, "sql/$self->{dbdriver}-upgrade2-auth/$control->{file}", $control, $db_charset);
374 print $self->{form}->parse_html_template("dbupgrade/footer", { is_admin => 1 }) if $called_from_admin;
379 sub _check_for_loops {
380 my ($form, $file_name, $controls, $tag, @path) = @_;
384 my $ctrl = $controls->{$tag};
386 if ($ctrl->{"loop"} == 1) {
388 _control_error($form, $file_name, $::locale->text("Dependency loop detected:") . " " . join(" -> ", @path))
390 } elsif ($ctrl->{"loop"} == 0) {
393 map({ _check_for_loops($form, $file_name, $controls, $_, @path); } @{ $ctrl->{"depends"} });
399 my ($form, $file_name, $message) = @_;
402 my $locale = $::locale;
404 $form->error(sprintf($locale->text("Error in database control file '%s': %s"), $file_name, $message));
407 sub _dbupdate2_calculate_depth {
408 $::lxdebug->enter_sub(2);
410 my ($tree, $tag) = @_;
412 my $node = $tree->{$tag};
414 return $::lxdebug->leave_sub(2) if (defined($node->{"depth"}));
418 foreach $tag (@{$node->{"depends"}}) {
419 _dbupdate2_calculate_depth($tree, $tag);
420 my $value = $tree->{$tag}->{"depth"};
421 $max_depth = $value if ($value > $max_depth);
424 $node->{"depth"} = $max_depth + 1;
426 $::lxdebug->leave_sub(2);
429 sub sort_dbupdate_controls {
432 $self->parse_dbupdate_controls unless $self->{all_controls};
434 return sort { ($a->{depth} <=> $b->{depth}) || ($a->{priority} <=> $b->{priority}) || ($a->{tag} cmp $b->{tag}) } values %{ $self->{all_controls} };