2012-02-28 19:16:16 +00:00
|
|
|
#! /var/run/current-system/sw/bin/perl -w
|
|
|
|
|
|
|
|
use strict;
|
|
|
|
use Hydra::Schema;
|
|
|
|
use Hydra::Helper::Nix;
|
2012-03-13 11:10:19 +00:00
|
|
|
use Hydra::Model::DB;
|
2012-02-28 19:16:16 +00:00
|
|
|
use File::Slurp;
|
|
|
|
use SQL::SplitStatement;
|
|
|
|
use List::Util qw(max);
|
|
|
|
|
2012-03-13 11:10:19 +00:00
|
|
|
my $db = Hydra::Model::DB->new();
|
2012-02-28 19:16:16 +00:00
|
|
|
my $dbh = $db->storage->dbh;
|
|
|
|
$dbh->{RaiseError} = 1;
|
|
|
|
|
|
|
|
my $home = getHydraHome;
|
|
|
|
|
|
|
|
my $sql_splitter = SQL::SplitStatement->new;
|
|
|
|
|
|
|
|
# Figure out the target schema version.
|
|
|
|
my $maxSchemaVersion = max (map { /.*\/upgrade-(\d.*)\.sql/; $1 } (glob "$home/sql/upgrade-[0-9]*.sql")) || 1;
|
|
|
|
|
|
|
|
# Check whether the database has been initialised. If not, load the
|
|
|
|
# schema.
|
|
|
|
my @tables = $dbh->tables;
|
|
|
|
if (! grep { /SchemaVersion/i } @tables) {
|
|
|
|
print STDERR "initialising the Hydra database schema...\n";
|
|
|
|
my $schema = read_file(
|
2012-04-15 16:34:32 +00:00
|
|
|
$dbh->{Driver}->{Name} eq 'SQLite' ? "$home/sql/hydra-sqlite.sql" :
|
|
|
|
$dbh->{Driver}->{Name} eq 'Pg' ? "$home/sql/hydra-postgresql.sql" :
|
|
|
|
die "unsupported database type\n");
|
2012-02-28 19:16:16 +00:00
|
|
|
my @statements = $sql_splitter->split($schema);
|
|
|
|
eval {
|
2012-04-15 16:34:32 +00:00
|
|
|
$dbh->begin_work;
|
|
|
|
$dbh->do($_) foreach @statements;
|
|
|
|
$db->resultset('SchemaVersion')->create({version => $maxSchemaVersion});
|
|
|
|
$dbh->commit;
|
2012-02-28 19:16:16 +00:00
|
|
|
};
|
|
|
|
die "schema initialisation failed: $@\n" if $@;
|
|
|
|
exit 0;
|
|
|
|
}
|
|
|
|
|
|
|
|
# Get the current schema version.
|
|
|
|
my @versions = $db->resultset('SchemaVersion')->all;
|
|
|
|
die "couldn't get Hydra schema version!" if scalar @versions != 1;
|
|
|
|
my $schemaVersion = $versions[0]->version;
|
|
|
|
|
|
|
|
for (my $n = $schemaVersion; $n < $maxSchemaVersion; $n++) {
|
|
|
|
my $m = $n + 1;
|
|
|
|
print STDERR "upgrading Hydra schema from version $n to $m\n";
|
|
|
|
my $schema = read_file("$home/sql/upgrade-$m.sql");
|
|
|
|
my @statements = $sql_splitter->split($schema);
|
|
|
|
eval {
|
2012-04-15 16:34:32 +00:00
|
|
|
$dbh->begin_work;
|
2013-08-12 18:11:34 +00:00
|
|
|
sub run_ {
|
2012-04-15 16:34:32 +00:00
|
|
|
my ($stm) = @_;
|
|
|
|
print STDERR "executing SQL statement: $stm\n";
|
|
|
|
$dbh->do($_);
|
|
|
|
}
|
2013-08-12 18:11:34 +00:00
|
|
|
run_($_) foreach @statements;
|
2012-04-15 16:34:32 +00:00
|
|
|
$db->resultset('SchemaVersion')->update({version => $m});
|
|
|
|
$dbh->commit;
|
2012-02-28 19:16:16 +00:00
|
|
|
};
|
|
|
|
die "schema upgrade failed: $@\n" if $@;
|
|
|
|
}
|