big kahuna
This commit is contained in:
72
lib/CW/Migration.pm
Normal file
72
lib/CW/Migration.pm
Normal file
@@ -0,0 +1,72 @@
|
||||
package CW::Migration;
|
||||
|
||||
use Moo;
|
||||
use feature qw(state say);
|
||||
use File::Find;
|
||||
|
||||
has dbh => (
|
||||
is => 'ro',
|
||||
required => 1
|
||||
);
|
||||
|
||||
sub migrate {
|
||||
my ($self) = @_;
|
||||
|
||||
return $self->_perform_migrations(pop)
|
||||
if !ref($self) && $self eq __PACKAGE__;
|
||||
|
||||
$self->dbh->do(<<'SQL');
|
||||
CREATE TABLE IF NOT EXISTS migrations (
|
||||
id VARCHAR(4),
|
||||
migration_sql TEXT NOT NULL,
|
||||
PRIMARY KEY (id)
|
||||
);
|
||||
SQL
|
||||
|
||||
my $id = $self->id;
|
||||
my $already_migrated = $self->already_migrated;
|
||||
|
||||
if ($already_migrated) {
|
||||
say "[Migration] $id already migrated";
|
||||
return;
|
||||
}
|
||||
|
||||
$self->dbh->do( $self->sql );
|
||||
$self->dbh->do( "INSERT INTO migrations (id, migration_sql) VALUES (?, ?)",
|
||||
undef, $id, $self->sql );
|
||||
say "[Migration] $id migrated successfully";
|
||||
}
|
||||
|
||||
sub already_migrated {
|
||||
my ($self) = @_;
|
||||
|
||||
my ($exists_check) =
|
||||
$self->dbh->selectrow_array(
|
||||
"SELECT 1 FROM migrations WHERE id = ? LIMIT 1",
|
||||
undef, $self->id );
|
||||
|
||||
return $exists_check;
|
||||
}
|
||||
|
||||
# static
|
||||
|
||||
sub _perform_migrations {
|
||||
my ( $class, $dbh ) = @_;
|
||||
|
||||
find(
|
||||
{
|
||||
wanted => sub {
|
||||
return unless /\.pm$/;
|
||||
my @parts = split( /\/+/, $File::Find::name );
|
||||
my $file = $parts[-1];
|
||||
my $class = "CW::Migration::" . ( $file =~ s/\.pm$//r );
|
||||
eval "use $class";
|
||||
my $migration = $class->new( dbh => $dbh );
|
||||
$migration->migrate;
|
||||
}
|
||||
},
|
||||
'lib/CW/Migration'
|
||||
);
|
||||
}
|
||||
|
||||
1;
|
||||
Reference in New Issue
Block a user