1 |
dpavlin |
935 |
package Frey::DBI::Sponge; |
2 |
|
|
use Moose; |
3 |
|
|
|
4 |
|
|
extends 'Frey'; |
5 |
|
|
|
6 |
dpavlin |
936 |
use lib 'lib'; |
7 |
|
|
use Frey::Types; |
8 |
dpavlin |
935 |
|
9 |
|
|
has sponge => ( |
10 |
|
|
is => 'rw', |
11 |
|
|
isa => 'Sponge', |
12 |
|
|
required => 1, |
13 |
dpavlin |
936 |
default => sub { {} }, |
14 |
dpavlin |
935 |
); |
15 |
|
|
|
16 |
|
|
has 'dsn' => ( |
17 |
|
|
is => 'ro', |
18 |
|
|
isa => 'dsn', |
19 |
|
|
default => 'dbi:Pg:dbname=frey', |
20 |
|
|
required => 1, |
21 |
|
|
); |
22 |
|
|
|
23 |
|
|
sub to_database_as_markup { |
24 |
|
|
my ($self) = @_; |
25 |
|
|
|
26 |
|
|
my $table = $self->sponge->{table} || die "no table in sponge ", $self->dump( $self->sponge ); |
27 |
|
|
|
28 |
|
|
warn "# dsn: ", $self->dsn; |
29 |
|
|
my $dbh = DBI->connect( $self->dsn, '', '', { RaiseError => 1 } ) || die $DBI::errstr; |
30 |
|
|
$dbh->do( qq{ set client_encoding='utf-8' } ); |
31 |
|
|
|
32 |
|
|
my @columns = @{ $self->sponge->{NAME} }; |
33 |
|
|
|
34 |
|
|
|
35 |
|
|
my $create_sql = qq{ |
36 |
|
|
create table $table ( |
37 |
|
|
} . join( ",\n", map { s/%//; "$_ text" } @columns ) . qq{ |
38 |
|
|
); |
39 |
|
|
}; |
40 |
|
|
eval { $dbh->do( $create_sql ); }; |
41 |
|
|
if ( $@ ) { |
42 |
|
|
die "$create_sql\n$@" if $@ !~ m{$table.*already exists}; |
43 |
|
|
warn "INFO: using existing table $table because of $@"; |
44 |
|
|
} else { |
45 |
|
|
warn "INFO: created $table using\n$create_sql"; |
46 |
|
|
} |
47 |
|
|
|
48 |
|
|
my $sth = $dbh->prepare( qq{ |
49 |
|
|
insert into $table values ( |
50 |
|
|
} . join( ",", map { '?' } @columns ) . qq{ |
51 |
|
|
); |
52 |
|
|
}); |
53 |
|
|
|
54 |
|
|
my $sponge_rows = $#{ $self->sponge->{rows} }; |
55 |
|
|
warn "# convert ", $sponge_rows + 1 ," rows from spunge into $table in ", $self->dsn; |
56 |
|
|
|
57 |
|
|
foreach my $row_nr ( 0 .. $sponge_rows ) { |
58 |
|
|
$sth->execute( @{ $self->sponge->{rows}->[$row_nr] } ); |
59 |
|
|
} |
60 |
|
|
|
61 |
|
|
$sponge_rows++; |
62 |
|
|
|
63 |
|
|
my $html = |
64 |
|
|
( $sponge_rows |
65 |
|
|
? qq|Inserted <b>$sponge_rows</b> rows| |
66 |
|
|
: qq|No rows inserted into $table| |
67 |
|
|
) |
68 |
|
|
. qq| to table <tt>$table</tt> at <tt>| . $self->dsn . qq|</tt>| |
69 |
|
|
; |
70 |
|
|
|
71 |
|
|
return $html; |
72 |
|
|
} |
73 |
|
|
|
74 |
|
|
1; |