| 1 | package DBIx::Class::StateMigrations::Migration::Routine::SQL; | ||
| 2 | |||
| 3 | use strict; | ||
| 4 | use warnings; | ||
| 5 | |||
| 6 | # ABSTRACT: Raw SQL routine | ||
| 7 | |||
| 8 | |||
| 9 | use Moo; | ||
| 10 | extends 'DBIx::Class::StateMigrations::Migration::Routine'; | ||
| 11 | |||
| 12 | use Types::Standard qw(:all); | ||
| 13 | use Path::Class 'file'; | ||
| 14 | use SQL::SplitStatement; | ||
| 15 | use Try::Tiny; | ||
| 16 | |||
| 17 | has 'file_path', is => 'ro', isa => Maybe[Str], default => sub { undef }; | ||
| 18 | has 'raw_sql', is => 'ro', isa => Maybe[Str], default => sub { undef }; | ||
| 19 | |||
| 20 | sub BUILD { | ||
| 21 | my $self = shift; | ||
| 22 | die "Must supply 'file_path' or 'raw_sql'" unless ($self->file_path || $self->raw_sql); | ||
| 23 | die "Supply either 'file_path' or 'raw_sql' - not both" if ($self->file_path && $self->raw_sql); | ||
| 24 | } | ||
| 25 | |||
| 26 | sub _get_routine_coderef { | ||
| 27 | my $self = shift; | ||
| 28 | |||
| 29 | my $sql = $self->raw_sql; | ||
| 30 | |||
| 31 | if($self->file_path) { | ||
| 32 | my $File = file($self->file_path)->absolute; | ||
| 33 | -f $File or die "Supplied file '".$self->file_path."' not found"; | ||
| 34 | |||
| 35 | $sql = $File->slurp; | ||
| 36 | die "Supplied file '".$self->file_path."' is empty" unless ($sql); | ||
| 37 | } | ||
| 38 | |||
| 39 | my $err_pfx = $self->file_path ? $self->file_path . ': ' : 'routine (raw_sql): '; | ||
| 40 | $err_pfx = " $err_pfx"; | ||
| 41 | |||
| 42 | my @stmts = SQL::SplitStatement->new->split($sql); | ||
| 43 | |||
| 44 | scalar(@stmts) > 0 or die $err_pfx . "no sql statements to run"; | ||
| 45 | |||
| 46 | return sub { | ||
| 47 | my $db = shift; | ||
| 48 | |||
| 49 | for my $stmt (@stmts) { | ||
| 50 | try { | ||
| 51 | $db->storage->dbh->do($stmt) | ||
| 52 | } | ||
| 53 | catch { | ||
| 54 | my $err = shift; | ||
| 55 | die $err_pfx . "[Exception running statement '$stmt']: $err"; | ||
| 56 | } | ||
| 57 | } | ||
| 58 | } | ||
| 59 | } | ||
| 60 | |||
| 61 | |||
| 62 | |||
| 63 | 1; | ||
| 64 | |||
| 65 | __END__ |