| 1 | package DBIx::SimpleMigration::Client::Pg; | ||
| 2 | use parent qw(DBIx::SimpleMigration::Client); | ||
| 3 | |||
| 4 | use Carp; | ||
| 5 | |||
| 6 | our $VERSION = '1.0.2'; | ||
| 7 | |||
| 8 | sub new { | ||
| 9 | my $class = shift; | ||
| 10 | my $self = $class->SUPER::new(@_); | ||
| 11 | |||
| 12 | $self->{options}->{migrations_schema} = 'public' unless $self->{options}->{migrations_schema}; | ||
| 13 | $self->{options}->{migrations_table} = $self->{options}->{migrations_schema} . '.' . $self->{options}->{migrations_table}; | ||
| 14 | |||
| 15 | return $self; | ||
| 16 | } | ||
| 17 | |||
| 18 | sub _create_migrations_schema { | ||
| 19 | my ($self) = @_; | ||
| 20 | return unless $self->{options}->{migrations_schema}; | ||
| 21 | |||
| 22 | my $query = ' | ||
| 23 | SET client_min_messages = error; | ||
| 24 | CREATE SCHEMA IF NOT EXISTS ' . $self->{options}->{migrations_schema}; | ||
| 25 | |||
| 26 | eval { $self->{dbh}->do($query) }; | ||
| 27 | if ($@) { | ||
| 28 | croak __PACKAGE__ . ': Error creating schema: ' . $self->{dbh}->errstr; | ||
| 29 | } | ||
| 30 | } | ||
| 31 | |||
| 32 | sub _create_migrations_table { | ||
| 33 | my ($self) = @_; | ||
| 34 | |||
| 35 | if ($self->{options}->{migrations_schema} ne 'public') { | ||
| 36 | $self->_create_migrations_schema; | ||
| 37 | } | ||
| 38 | |||
| 39 | my $query = ' | ||
| 40 | SET client_min_messages = error; | ||
| 41 | CREATE TABLE IF NOT EXISTS ' . $self->{options}->{migrations_table} . ' ( | ||
| 42 | name text primary key not null, | ||
| 43 | applied timestamp not null | ||
| 44 | ) | ||
| 45 | '; | ||
| 46 | |||
| 47 | eval { $self->{dbh}->do($query) }; | ||
| 48 | if ($@) { | ||
| 49 | croak __PACKAGE__ . ': Error creating table: ' . $self->{dbh}->errstr; | ||
| 50 | } | ||
| 51 | } | ||
| 52 | |||
| 53 | sub _migrations_table_exists { | ||
| 54 | my ($self) = @_; | ||
| 55 | |||
| 56 | my $schema_where; | ||
| 57 | if ($self->{options}->{migrations_schema}) { | ||
| 58 | $schema_where = "AND table_schema = '$self->{options}->{migrations_schema}'"; | ||
| 59 | } | ||
| 60 | |||
| 61 | my $query = " | ||
| 62 | WITH tables AS ( | ||
| 63 | SELECT table_schema::text || '.' || table_name::text as theTable | ||
| 64 | FROM information_schema.tables | ||
| 65 | ) | ||
| 66 | SELECT EXISTS ( | ||
| 67 | SELECT NULL | ||
| 68 | FROM tables | ||
| 69 | WHERE theTable = ? | ||
| 70 | ) | ||
| 71 | "; | ||
| 72 | |||
| 73 | my $row = $self->{dbh}->selectrow_hashref($query, {}, $self->{options}->{migrations_table}) or croak __PACKAGE__ . ': Database error: ' . $self->{dbh}->errstr; | ||
| 74 | |||
| 75 | return $row->{exists}; | ||
| 76 | } | ||
| 77 | |||
| 78 | sub _lock_migrations_table { | ||
| 79 | my ($self) = @_; | ||
| 80 | |||
| 81 | my $query = 'LOCK TABLE ' . $self->{options}->{migrations_table} . ' IN EXCLUSIVE MODE'; | ||
| 82 | return $self->{dbh}->do($query); | ||
| 83 | } | ||
| 84 | |||
| 85 | 1; |