86e8b7b4ca059482db76652d3be1cd07ae892ba2
[MojoFacets.git] / lib / MojoFacets / Import / SQL.pm
1 package MojoFacets::Import::SQL;
2
3 use warnings;
4 use strict;
5
6 use base 'Mojo::Base';
7
8 use DBI;
9 use File::Slurp;
10 use Data::Dump qw(dump);
11 use Encode;
12
13 __PACKAGE__->attr('path');
14
15 sub data {
16         my $self = shift;
17
18         my $path = $self->path;
19
20         my $sql = read_file $path, { binmode => ':raw' }; # FIXME configurable!
21
22         my $dsn    = $1 if $sql =~ s/--\s*(dbi:\S+)//;
23         my $user   = $1 if $sql =~ s/--\s*user:\s*(\S+)//;
24         my $passwd = $1 if $sql =~ s/--\s*passwd:\s*(\S+)//;
25
26         warn "# $dsn $user/", '*' x length($passwd);
27
28         my $opts = { RaiseError => 1, AutoCommit => 0 };
29         delete $opts->{AutoCommit} if $dsn =~ m/Gofer/; # not supported with Gofer
30
31         if ( $dsn =~ m{Pg} ) {
32                 $opts->{pg_enable_utf8} = 1;
33         } elsif ( $dsn =~ m{mysql} ) {
34                 $opts->{mysql_enable_utf8} = 1;
35         } else {
36                 warn "utf-8 encoding can't be set for this dsn!";
37         }
38
39         my $dbh = DBI->connect($dsn, $user, $passwd, $opts) || die $DBI::errstr;
40
41         warn "# SQL: $sql";
42         my $sth = $dbh->prepare($sql);
43         $sth->execute();
44
45         warn "# got ", $sth->rows, " rows\n";
46
47         my $data = { items => [] };
48         $data->{header} = [ $sth->{NAME} ];
49
50         while( my $row = $sth->fetchrow_hashref ) {
51                 push @{ $data->{items} }, $row;
52         }
53
54         return $data;
55
56 }
57
58 1