adding load report file for resource mate
[migration-tools.git] / text / csv2sql
1 #!/usr/bin/perl -w
2 use Getopt::Long;
3 use Text::CSV::Auto;
4 use Data::Dumper;
5 use DBI;
6 use File::Basename;
7 use Env qw(
8     HOME PGHOST PGPORT PGUSER PGDATABASE MIGSCHEMA
9     MIGBASEWORKDIR MIGBASEGITDIR MIGGITDIR MIGWORKDIR
10 );
11
12 my $dbh;
13 my $cfg;
14 my $csv_config;
15
16 sub init {
17     if ($PGHOST and $PGPORT and $PGUSER and $PGDATABASE) 
18     {
19         $dbh = connect_db($PGDATABASE,$PGUSER,undef,$PGHOST) or die $DBI::errstr;
20     } else {
21         our %config;
22         do '/openils/conf/offline-config.pl';
23         $dbh = DBI->connect( $config{dsn}, $config{usr}, $config{pw} ) or die $DBI::errstr;
24     }
25
26         $cfg = {
27                 schema => 'm_foo',
28                 auto_options => {
29                 }
30         };
31         our %CSV_options = (
32             binary => 1,
33             auto_diag => 1,
34             diag_verbose => 1,
35         );
36         $cfg->{auto_options}->{csv_options} = \%CSV_options;
37
38         GetOptions(
39                 'config=s' => \$csv_config,
40                 'no-legacy-prefix' => \($cfg->{no_legacy_prefix}),
41                 'use-no-headers-file' => \($cfg->{use_no_headers_file}),
42                 'add-x-migrate' => \($cfg->{add_x_migrate}),
43         'outfile=s' => \($cfg->{outfile}),
44                 'schema=s' => \($cfg->{schema}),
45                 'parent=s' => \($cfg->{parent}),
46                 'help|?' => \$help
47         );
48         if ($help || ((@ARGV == 0) && (-t STDIN))) {
49                 die qq^\n\t$0 [--config <CONFIG>] [--add-x-migrate] [--no-legacy-prefix] [--schema <schema>] [--parent <base table>] [--outfile <file to create>] <"clean" file from clean_csv script>\n\n^;
50         }
51         if ($csv_config && ! -e $csv_config) {
52                 die "$csv_config does not exist\n";
53         }
54         if ($csv_config && -e $csv_config) {
55                 do $csv_config;
56         }
57         if (! -e $ARGV[0]) {
58                 die "$ARGV[0] does not exist\n";
59         }
60 }
61
62 sub connect_db {
63     my ($db, $dbuser, $dbpw, $dbhost) = @_;
64
65     my $dsn = "dbi:Pg:host=$dbhost;dbname=$db;port=5432";
66
67     my $attrs = {
68         ShowErrorStatement => 1,
69         RaiseError => 1,
70         PrintError => 1,
71         pg_enable_utf8 => 1,
72     };
73     my $dbh = DBI->connect($dsn, $dbuser, $dbpw, $attrs);
74
75     return $dbh;
76 }
77
78
79 sub write_sql_sample {
80         my $cfg = shift;
81         my $info = shift;
82         my $fn = $cfg->{outfile} || $cfg->{auto_options}->{file} . '.sql';
83
84         print "\twriting $fn\n";
85         local *SQL;
86         open SQL, ">$fn";
87         print SQL "-- $cfg->{auto_options}->{file}\n/*\n";
88         open IN, $cfg->{auto_options}->{file};
89         foreach (1..5) {
90                 my $line = <IN>;
91                 print SQL $line;
92         }
93         close IN;
94         print SQL "*/\n";
95         return *SQL;
96 }
97
98 sub write_sql_table {
99         my $sql = shift;
100         my $cfg = shift;
101         my $info = shift;
102         my $fn = $cfg->{auto_options}->{file};
103         my @indices = ();
104
105         print "\twriting table definition\n";
106     if ($cfg->{parent}) {
107         $cfg->{table_name} = $cfg->{parent} . '_legacy';
108     } else {
109             $cfg->{table_name} = lc(basename($fn)); $cfg->{table_name} =~ s/[\-\. ]/_/g;
110     }
111         print $sql "DROP TABLE IF EXISTS $cfg->{schema}.$cfg->{table_name};\n";
112         print $sql "CREATE UNLOGGED TABLE $cfg->{schema}.$cfg->{table_name} (\n";
113         my $idx = 0;
114         if ($cfg->{add_x_migrate}) {
115                 print $sql "    x_migrate BOOLEAN\n";
116                 $idx++;
117                 push @indices, 'x_migrate';
118         }
119         foreach my $column (@{ $info }) {
120                 my $cn = $column->{'header'};
121                 if ($cn =~ /^x_/) {
122                         push @indices, $cn;
123                 }
124                 my $col_info = Dumper($column);
125                 $col_info =~ s/^\$VAR1 = //;
126                 print $sql "   " . ($idx++ ? ',' : ' ');
127                 print $sql "l_" unless $cfg->{no_legacy_prefix} or $column->{'header'} =~ /^x_/ or $column->{'header'} =~ /^l_/;
128         print $sql "$cn " . ($cn eq 'x_eg_bib_id' ? 'BIGINT' : 'TEXT');
129         print $sql " /*\n         $col_info   */\n";
130         }
131     if ($cfg->{parent}) {
132             print $sql ') INHERITS (' . $cfg->{schema} . '.' . $cfg->{parent} . ");\n";
133     } else {
134             print $sql ");\n";
135     }
136         foreach my $cn (@indices) {
137                 print $sql "CREATE INDEX ON $cfg->{schema}.$cfg->{table_name} ($cn);\n";
138         }
139 }
140
141 sub write_sql_loader {
142         my $sql = shift;
143         my $cfg = shift;
144         my $auto = shift;
145         my $info = shift;
146         my $fn = $cfg->{auto_options}->{file} . ($cfg->{use_no_headers_file} ? '.no_headers' : '');
147
148         print "\twriting copy statement\n";
149         print $sql "\n\\COPY $cfg->{schema}.$cfg->{table_name} (";
150     my $idx = 0;
151     foreach my $column (@{ $info }) {
152         print $sql ($idx++ ? ',' : '');
153         print $sql "l_" unless $cfg->{no_legacy_prefix} or $column->{'header'} =~ /^x_/ or $column->{'header'} =~ /^l_/;
154         print $sql $column->{'header'};
155     }
156     print $sql ") FROM '$fn'";
157     if ($auto->csv->sep_char eq chr(9) && ! defined $auto->csv->quote_char && ! defined $auto->csv->escape_char) {
158         # true .tsv, don't treat as csv
159     } elsif ($auto->csv->sep_char eq chr(9)) {
160         # probably good enough .tsv, don't treat as csv
161     } else {
162         print $sql " WITH csv " . ($cfg->{use_no_headers_file} ? "" : "header");
163         print $sql " delimiter " . $dbh->quote( $auto->csv->sep_char ) unless $dbh->quote( $auto->csv->sep_char ) eq 'NULL';
164         print $sql " quote " . $dbh->quote( $auto->csv->quote_char ) unless $dbh->quote( $auto->csv->quote_char ) eq 'NULL';
165         print $sql " escape " . $dbh->quote( $auto->csv->escape_char ) unless $dbh->quote( $auto->csv->escape_char ) eq 'NULL';
166     }
167         print $sql "\n";
168 }
169
170 sub main {
171         init();
172         foreach my $fn (@ARGV) {
173                 print "processing $fn\n";
174                 $cfg->{auto_options}->{file} = $fn;
175                 my $auto = Text::CSV::Auto->new($cfg->{auto_options});
176
177                 my $info = $auto->analyze();
178                 my $sql = write_sql_sample($cfg,$info);
179                 write_sql_table($sql,$cfg,$info);
180                 write_sql_loader($sql,$cfg,$auto,$info);
181                 close $sql;
182
183                 print "\tdone.\n";
184         }
185 }
186
187 main();
188