Provide a command ‘hydra-init’ to initialise/upgrade the database
For schema upgrades, hydra-init executes the files src/sql/upgrade-<N>.sql, each of which upgrades the schema from version N-1 to N. The upgrades are wrapped in a transaction.
This commit is contained in:
58
src/script/hydra-init
Executable file
58
src/script/hydra-init
Executable file
@ -0,0 +1,58 @@
|
||||
#! /var/run/current-system/sw/bin/perl -w
|
||||
|
||||
use strict;
|
||||
use Hydra::Schema;
|
||||
use Hydra::Helper::Nix;
|
||||
use File::Slurp;
|
||||
use SQL::SplitStatement;
|
||||
use List::Util qw(max);
|
||||
|
||||
my $db = openHydraDB;
|
||||
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(
|
||||
$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");
|
||||
my @statements = $sql_splitter->split($schema);
|
||||
eval {
|
||||
$dbh->begin_work;
|
||||
$dbh->do($_) foreach @statements;
|
||||
$db->resultset('SchemaVersion')->create({version => $maxSchemaVersion});
|
||||
$dbh->commit;
|
||||
};
|
||||
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 {
|
||||
$dbh->begin_work;
|
||||
$dbh->do($_) foreach @statements;
|
||||
$db->resultset('SchemaVersion')->update({version => $m});
|
||||
$dbh->commit;
|
||||
};
|
||||
die "schema upgrade failed: $@\n" if $@;
|
||||
}
|
Reference in New Issue
Block a user