+sub apply_upgrade {
+ my $name = shift;
+
+ $form->error("Unknown dbupgrade tag '$name'") if (!$controls->{$name});
+
+ my (@order, %tags);
+
+ build_upgrade_order($name, \@order, \%tags);
+
+ my @upgradescripts = map { $controls->{$_}->{"applied"} = 0; $controls->{$_} } @order;
+
+ my $dbh = $form->dbconnect_noauto(\%myconfig);
+
+ $dbh->{PrintWarn} = 0;
+ $dbh->{PrintError} = 0;
+
+ $user->create_schema_info_table($form, $dbh);
+
+ my $query = qq|SELECT tag FROM schema_info|;
+ $sth = $dbh->prepare($query);
+ $sth->execute() || $form->dberror($query);
+ while (($tag) = $sth->fetchrow_array()) {
+ $controls->{$tag}->{"applied"} = 1 if defined $controls->{$tag};
+ }
+ $sth->finish();
+
+ my $all_applied = 1;
+ foreach (@upgradescripts) {
+ if (!$_->{"applied"}) {
+ $all_applied = 0;
+ last;
+ }
+ }
+
+ if ($all_applied) {
+ print "The upgrade has already been applied.\n";
+ exit 0;
+ }
+
+ foreach my $control (@upgradescripts) {
+ next if ($control->{"applied"});
+
+ $control->{"file"} =~ /\.(sql|pl)$/;
+ my $file_type = $1;
+
+ # apply upgrade
+ print "Applying upgrade $control->{file}\n";
+
+ if ($file_type eq "sql") {
+ $user->process_query($form, $dbh, "sql/$form->{dbdriver}-upgrade2/$control->{file}", $control);
+ } else {
+ $user->process_perl_script($form, $dbh, "sql/$form->{dbdriver}-upgrade2/$control->{file}", $control);
+ }
+ }
+
+ $dbh->disconnect();
+}
+
+sub build_upgrade_order {
+ my $name = shift;
+ my $order = shift;
+ my $tag = shift;
+
+ my $control = $controls->{$name};
+
+ foreach my $dependency (@{ $control->{"depends"} }) {
+ next if $tags->{$dependency};
+ $tags->{$dependency} = 1;
+ build_upgrade_order($dependency, $order, $tag);
+ }
+
+ push @{ $order }, $name;
+}
+