-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathreadToPsql.pl
executable file
·258 lines (213 loc) · 5.95 KB
/
readToPsql.pl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
#!/usr/bin/env perl
# Questions, comments -> [email protected]
use 5.10.1;
use strict;
use warnings;
use autodie;
use DBI;
use DBD::Pg qw/:pg_types/;
use Getopt::Long;
use Carp;
use Data::Dumper;
my $dbname;
my $port;
my $username;
my $password;
my $host;
my $tablename;
my $createstatement = 0;
my $nocreate = 0;
my $copystatement;
my $headerfile;
my $outfile;
GetOptions(
"db=s" => \$dbname,
"port=i" => \$port,
"username=s" => \$username,
"password=s" => \$password,
"host=s" => \$host,
"tablename=s" => \$tablename,
"createstatement" => \$createstatement,
"nocreate" => \$nocreate,
"copystatement=s" => \$copystatement, # expert option - provide own copy statement
"headerfile=s" => \$headerfile, # expert option - read header from different file
"outfile=s" => \$outfile
);
unless (defined($dbname)) {
say STDERR "Please specify db name with --db=[name]";
say STDERR "Options:";
say STDERR "--db=[database name] (mandantory)";
say STDERR "--host=[hostname]";
say STDERR "--port=[database port]";
say STDERR "--username=[username]";
say STDERR "--password=[password]";
say STDERR "--tablename=[table name]";
say STDERR "--createstatement (only shows create table statement)";
say STDERR "--nocreate (do not emit create table statement)";
say STDERR "--outfile=[filename] (dump to file instead of db, implies nocreate. Still needs db connection.)";
exit(-1);
}
my $outfh;
if ( defined($outfile) ) {
$nocreate = 1;
open($outfh, ">", $outfile);
}
my $connectString = "dbi:Pg:dbname=$dbname";
$connectString .= ";port=$port" if defined($port);
$connectString .= ";username=$username" if defined($username);
$connectString .= ";password=$password" if defined($password);
$connectString .= ";host=$host" if defined($host);
my $dbh = DBI->connect($connectString, "", "", {
RaiseError => 1,
# Autocommit => 1,
});
my %typemap = (
bool => "boolean",
int => "bigint",
count => "bigint",
counter => "bigint",
port => "integer",
subnet => "inet",
addr => "inet",
time => "double precision",
interval => "double precision",
double => "double precision",
enum => "text",
string => "text",
file => "text",
func => "text",
);
for my $file ( @ARGV ) {
say "Reading $file";
croak("File $file does not exist") unless ( -f $file );
next if ( -s $file == 0 );
# black magic from the internet... make all .gz and .bz2 arguments go through gzcat.
$file =~ s{
^ # make sure to get whole filename
(
[^'] + # at least one non-quote
\. # extension dot
(?: # now either suffix
gz
| Z
)
)
\z # through the end
}{zcat '$1' |}xs;
$file =~ s{
^ # make sure to get whole filename
(
[^'] + # at least one non-quote
\. # extension dot
(?: # now either suffix
bz2
)
)
\z # through the end
}{bzcat '$1' |}xs;
open(my $fh, $file);
my $headerfh;
if ( defined($headerfile) ) {
open($headerfh, "<", $headerfile);
}
$headerfh //= $fh;
# -------------------------------- Step 1 - parse header lines
my $fields_string;
my $types_string;
my $path;
# this only works if the last header line is #types...
while ( my $headerline = <$headerfh> ) {
chomp($headerline);
croak("Unexpected non-headerline: $headerline") unless ($headerline =~ m/^#/);
if ($headerline =~ s/^#path\s//) {
$path = $headerline;
next;
}
if ($headerline =~ s/^#fields\s//) {
$fields_string = $headerline;
next;
}
if ($headerline =~ s/^#types\s//) {
$types_string = $headerline;
last;
}
}
croak("No #types line") unless defined($types_string);
croak("No #fields line") unless defined($fields_string);
croak("No #path line") unless defined($path);
$path = $tablename if ( defined($tablename) );
my @fields = split(/\s/, $fields_string);
my @types = split(/\s/, $types_string);
my %f;
@f{@fields} = @types;
# -------------------------------- Step 2 - create table
my $create = "CREATE TABLE IF NOT EXISTS $path (\n";
$create .= "id SERIAL UNIQUE NOT NULL PRIMARY KEY";
for my $field ( @fields ) {
my $type = $f{$field};
$field =~ tr/./_/; # manipulation is SAVED TO ARRAY! which we want.
$field = 'from_addr' if $field eq 'from';
$field = 'to_addr' if $field eq 'to';
$create .= ",\n";
$create .= "$field ";
if ( $type =~ s#^(table|vector|set)\[(.*)\]#$2# ) {
carp("internal error") unless(defined($typemap{$type}));
$create .= $typemap{$type}."[]";
} else {
carp("internal error") unless(defined($typemap{$type}));
$create .= $typemap{$type};
}
}
$create .= "\n);";
if ( $createstatement ) {
say $create;
exit(0);
}
$dbh->do($create) unless ( $nocreate );
my $neednum = scalar @fields;
# -------------------------------- Step 2 - build copy statement
my $insert = "copy $path (".join(',', @fields).") FROM STDIN;";
$insert = $copystatement if ( defined($copystatement) );
$dbh->do($insert) unless(defined($outfile));
while ( my $line = <$fh> ) {
chomp($line);
next if ( $line =~ m/^#close\s.*/ );
next if ( $line =~ m/^#.*\s.*/ );
my @values = split('\t', $line);
if ( scalar @values != $neednum ) {
say "Column with wrong number of entries";
say $line;
last;
}
#say Dumper(\@values);
my $str;
my $pos=0;
my @out;
for my $val (@values) {
$val = $dbh->quote($val);
$val = substr($val, 1, -1);
if ( $val eq "-" ) {
push(@out, '\N');
} elsif ( $val eq "(empty)" ) {
push(@out, '{}');
} else {
if ( $types[$pos] =~ m#\[# ) {
$val =~ s/"/\\\\\"/g;
#die ($val) if $val =~ m#"#;
my @parts = split(',', $val);
my @parts2 = map { '"'.$_.'"' } @parts;
push(@out, '{'.join(',', @parts2).'}');
} else {
push(@out, $val);
}
}
$pos++;
}
#say Dumper(\@out);
$dbh->pg_putcopydata(join("\t", @out)."\n") unless(defined($outfile));
say $outfh join("\t", @out) if (defined($outfile));
}
close($fh);
close($outfh) if (defined($outfile));
$dbh->pg_putcopyend() unless(defined($outfile));
}