Merge branch 'master' of mjesec.ffzg.hr:/git/blackray-experiments
[blackray-experiments.git] / sql2blackray.pl
1 #!/usr/bin/perl
2
3 use warnings;
4 use strict;
5
6 use DBI;
7 use Data::Dump qw(dump);
8
9 our $dsn      = 'DBI:mysql:dbname=';
10 our $database = '';
11 our $user     = '';
12 our $passwd   = '';
13
14 require 'config.pl' if -e 'config.pl';
15
16 my $table = 'borrowers';
17 my $schema = $database;
18
19 my $dbh = DBI->connect($dsn . $database, $user,$passwd, { RaiseError => 1, AutoCommit => 0 }) || die $DBI::errstr;
20
21 open(my $load, '>', 'load.xml');
22
23 sub dump_table {
24         my $table = shift;
25         my @cols = @_;
26         @cols = ( '*' ) unless @cols;
27
28 my $sql = 'select ' . join(',', @cols) .  ' from ' . $table;
29 warn "# sql $sql\n";
30
31 my $sth = $dbh->prepare( $sql );
32 $sth->execute();
33
34 warn "got ", $sth->rows, " rows\n";
35
36 my @columns = @{ $sth->{NAME} };
37
38 warn "columns ", dump @columns;
39
40 print $load qq|<table-def name="$table" schema="$schema">\n|;
41 print $load qq| <column-def name="$_" type="string" tokenizing=" "
42                         searchable="yes" compress="no" wildcards="yes" />
43 | foreach @columns;
44 print $load qq|</table-def>\n|;
45
46 my $file = "$table.csv";
47
48 print $load qq|<load-data table="$table" schema="$schema" file="$file">\n|;
49 foreach my $i ( 0 .. $#columns ) {
50         print $load qq|
51         <column name="$columns[$i]" csv-column="$i">
52          <function type="trim" />
53     </column>
54         |;
55 }
56 print $load qq|</load-data>\n|;
57
58 open(my $fh, '>', $file) || die "$file: $!";
59
60 while (my $row = $sth->fetchrow_arrayref) {
61         print $fh join(',', map { ! defined $_ ? '' : m/^\d+$/ ? $_ : "\"$_\"" } @$row), "\n";
62 }
63
64 close($fh);
65
66 warn "$file ", -s $file, " bytes\n";
67
68 }
69
70 print $load qq|<load-script>\n|;
71 dump_table 'borrowers' => qw(
72         borrowernumber
73         cardnumber
74         surname
75         firstname
76         email
77 ); 
78 dump_table 'borrower_attributes' => qw(
79         borrowernumber
80         code
81         attribute
82 );
83
84 print $load qq|</load-script>\n|;
85
86 #$dbh->commit;