1 package SL::DBUpgrade2;
4 use List::MoreUtils qw(any);
15 return bless({}, $package)->init(@_);
19 my ($self, %params) = @_;
22 $params{path_suffix} = "-auth";
23 $params{schema} = "auth.";
26 $params{path_suffix} ||= '';
27 $params{schame} ||= '';
29 map { $self->{$_} = $params{$_} } keys %params;
34 sub parse_dbupdate_controls {
35 $::lxdebug->enter_sub();
39 my $form = $self->{form};
40 my $locale = $::locale;
45 my $path = "sql/" . $self->{dbdriver} . "-upgrade2" . $self->{path_suffix};
47 foreach my $file_name (<$path/*.sql>, <$path/*.pl>) {
48 next unless (open(IN, $file_name));
50 my $file = $file_name;
60 next unless (/^(--|\#)\s*\@/);
65 my @fields = split(/\s*:\s*/, $_, 2);
66 next unless (scalar(@fields) == 2);
68 if ($fields[0] eq "depends") {
69 push(@{$control->{"depends"}}, split(/\s+/, $fields[1]));
71 $control->{$fields[0]} = $fields[1];
75 next if ($control->{ignore});
77 $control->{charset} ||= Common::DEFAULT_CHARSET;
79 if (!$control->{"tag"}) {
80 _control_error($form, $file_name, $locale->text("Missing 'tag' field.")) ;
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 - _ ( )"))
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"}))
91 if (!$control->{"description"}) {
92 _control_error($form, $file_name, sprintf($locale->text("Missing 'description' field."))) ;
95 $control->{"priority"} *= 1;
96 $control->{"priority"} ||= 1000;
97 $control->{"file"} = $file;
99 delete @{$control}{qw(depth applied)};
101 $all_controls{$control->{"tag"}} = $control;
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}));
111 map({ $_->{"loop"} = 0; } values(%all_controls));
112 _check_for_loops($form, $control->{"file"}, \%all_controls, $control->{"tag"});
115 map({ _dbupdate2_calculate_depth(\%all_controls, $_->{"tag"}) }
116 values(%all_controls));
118 $self->{all_controls} = \%all_controls;
120 $::lxdebug->leave_sub();
126 $::lxdebug->enter_sub();
128 my ($self, $dbh, $filename, $version_or_control, $db_charset) = @_;
130 my $form = $self->{form};
131 my $fh = IO::File->new($filename, "r") or $form->error("$filename : $!\n");
136 my $file_charset = Common::DEFAULT_CHARSET;
139 next if !/^--\s*\@charset:\s*(.+)/;
143 $fh->seek(0, SEEK_SET);
145 $db_charset ||= Common::DEFAULT_CHARSET;
150 $_ = SL::Iconv::convert($file_charset, $db_charset, $_);
152 # Remove DOS and Unix style line endings.
158 for (my $i = 0; $i < length($_); $i++) {
159 my $char = substr($_, $i, 1);
161 # Are we inside a string?
163 if ($char eq $quote_chars[-1]) {
169 if (($char eq "'") || ($char eq "\"")) {
170 push(@quote_chars, $char);
172 } elsif ($char eq ";") {
174 # Query is complete. Send it.
176 $sth = $dbh->prepare($query);
177 if (!$sth->execute()) {
178 my $errstr = $dbh->errstr;
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.");
197 # Insert a space at the end of each line so that queries split
198 # over multiple lines work properly.
200 $query .= @quote_chars ? "\n" : ' ';
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));
213 $::lxdebug->leave_sub();
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();
224 my ($self, $dbh, $filename, $version_or_control, $db_charset) = @_;
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;
230 if (ref($version_or_control) eq "HASH") {
231 $file_charset = $version_or_control->{charset};
236 next if !/^--\s*\@charset:\s*(.+)/;
240 $fh->seek(0, SEEK_SET);
243 my $contents = join "", <$fh>;
246 $db_charset ||= Common::DEFAULT_CHARSET;
248 my $iconv = SL::Iconv->new($file_charset, $db_charset);
252 # setup dbup_ export vars
253 my %dbup_myconfig = ();
254 map({ $dbup_myconfig{$_} = $form->{$_}; } qw(dbname dbuser dbpasswd dbhost dbport dbconnect));
256 my $dbup_locale = $::locale;
258 my $result = eval($contents);
265 if (!defined($result)) {
266 print $form->parse_html_template("dbupgrade/error",
267 { "file" => $filename,
270 } elsif (1 != $result) {
271 unlink("users/nologin") if (2 == $result);
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));
282 $::lxdebug->leave_sub();
286 my ($self, $dbh, $filename, $version_or_control, $db_charset) = @_;
288 if ($filename =~ m/sql$/) {
289 $self->process_query($dbh, $filename, $version_or_control, $db_charset);
291 $self->process_perl_script($dbh, $filename, $version_or_control, $db_charset);
295 sub update_available {
296 my ($self, $cur_version) = @_;
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;
305 return ($#upgradescripts > -1);
308 sub update2_available {
309 $::lxdebug->enter_sub();
311 my ($self, $dbh) = @_;
313 map { $_->{applied} = 0; } values %{ $self->{all_controls} };
315 my $sth = $dbh->prepare(qq|SELECT tag FROM | . $self->{schema} . qq|schema_info|);
317 while (my ($tag) = $sth->fetchrow_array) {
318 $self->{all_controls}->{$tag}->{applied} = 1 if defined $self->{all_controls}->{$tag};
323 my $needs_update = any { !$_->{applied} } values %{ $self->{all_controls} };
325 $::lxdebug->leave_sub();
327 return $needs_update;
330 sub unapplied_upgrade_scripts {
331 my ($self, $dbh) = @_;
333 my @all_scripts = map { $_->{applied} = 0; $_ } $self->sort_dbupdate_controls;
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};
343 return grep { !$_->{applied} } @all_scripts;
346 sub apply_admin_dbupgrade_scripts {
347 my ($self, $called_from_admin) = @_;
349 return 0 if !$self->{auth};
351 my $dbh = $::auth->dbconnect;
352 my @unapplied_scripts = $self->unapplied_upgrade_scripts($dbh);
354 return 0 if !@unapplied_scripts;
356 my $db_charset = $::lx_office_conf{system}->{dbcharset} || Common::DEFAULT_CHARSET;
357 $self->{form}->{login} ||= 'admin';
359 map { $_->{description} = SL::Iconv::convert($_->{charset}, $db_charset, $_->{description}) } values %{ $self->{all_controls} };
361 if ($called_from_admin) {
362 $self->{form}->{title} = $::locale->text('Dataset upgrade');
363 $self->{form}->header;
366 print $self->{form}->parse_html_template("dbupgrade/header", { dbname => $::auth->{DB_config}->{db} });
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);
372 $self->process_file($dbh, "sql/$self->{dbdriver}-upgrade2-auth/$control->{file}", $control, $db_charset);
375 print $self->{form}->parse_html_template("dbupgrade/footer", { is_admin => 1 }) if $called_from_admin;
380 sub _check_for_loops {
381 my ($form, $file_name, $controls, $tag, @path) = @_;
385 my $ctrl = $controls->{$tag};
387 if ($ctrl->{"loop"} == 1) {
389 _control_error($form, $file_name, $::locale->text("Dependency loop detected:") . " " . join(" -> ", @path))
391 } elsif ($ctrl->{"loop"} == 0) {
394 map({ _check_for_loops($form, $file_name, $controls, $_, @path); } @{ $ctrl->{"depends"} });
400 my ($form, $file_name, $message) = @_;
403 my $locale = $::locale;
405 $form->error(sprintf($locale->text("Error in database control file '%s': %s"), $file_name, $message));
408 sub _dbupdate2_calculate_depth {
409 $::lxdebug->enter_sub(2);
411 my ($tree, $tag) = @_;
413 my $node = $tree->{$tag};
415 return $::lxdebug->leave_sub(2) if (defined($node->{"depth"}));
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);
425 $node->{"depth"} = $max_depth + 1;
427 $::lxdebug->leave_sub(2);
430 sub sort_dbupdate_controls {
433 $self->parse_dbupdate_controls unless $self->{all_controls};
435 return sort { ($a->{depth} <=> $b->{depth}) || ($a->{priority} <=> $b->{priority}) || ($a->{tag} cmp $b->{tag}) } values %{ $self->{all_controls} };