blib/lib/SQL/Translator/Producer/Dumper.pm

filter: Statementstmt 92.4% 49 / 53 Branchbran 50.0% 5 / 10 Conditioncond 43.4% 10 / 23 MC/DCmcdc 0.0% 0 / 13 Subroutinesub 100% 9 / 9 Podpod 0.0% 0 / 2 totaltotal 66.3% 73 / 110 CC 16 SCAR 29.2
CC
16
Cov
74%
produce
27.4
BEGIN
1.0
BEGIN
1.0
CRAP 18.6
« blib/lib/SQL/Translator/Parser/DBI.pm ↑ Summary blib/lib/SQL/Translator/Schema/Constraint.pm »
1 package SQL::Translator::Producer::Dumper;
2  
3 =head1 NAME
4  
5 SQL::Translator::Producer::Dumper - SQL Dumper producer for SQL::Translator
6  
7 =head1 SYNOPSIS
8  
9 use SQL::Translator::Producer::Dumper;
10  
11 Options:
12  
13 db_user Database username
14 db_password Database password
15 dsn DSN for DBI
16 mysql_loadfile Create MySQL's LOAD FILE syntax instead of INSERTs
17 skip=t1[,t2] Skip tables in comma-separated list
18 skiplike=regex Skip tables in comma-separated list
19  
20 =head1 DESCRIPTION
21  
22 This producer creates a Perl script that can connect to a database and
23 dump the data as INSERT statements (a la mysqldump) or as a file
24 suitable for MySQL's LOAD DATA command. If you enable "add-truncate"
25 or specify tables to "skip" (also using the "skiplike" regular
26 expression) then the generated dumper script will leave out those
27 tables. However, these will also be options in the generated dumper,
28 so you can wait to specify these options when you dump your database.
29 The database username, password, and DSN can be hardcoded into the
30 generated script, or part of the DSN can be intuited from the
31 "database" argument.
32  
33 =cut
34  
35 1 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
36 1 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
37 1 ▶use Config;
Subroutine BEGIN: called CC=1 SCAR=0.0
38 1 ▶use SQL::Translator;
Subroutine BEGIN: called CC=1 SCAR=0.0
39 1 ▶use File::Temp 'tempfile';
Subroutine BEGIN: called CC=1 SCAR=0.0
40 1 ▶use Template;
Subroutine BEGIN: called CC=1 SCAR=0.0
41  
42 1 ▶use Data::Dumper;
Subroutine BEGIN: called CC=1 SCAR=0.0
43  
44 1 our $VERSION = '1.66';
45  
46 1 ▶sub produce {
Subroutine produce: called CC=16 SCAR=33.1
Pod undocumented
47 1 my $t = shift;
48 1 my $args = $t->producer_args;
49 1 my $schema = $t->schema;
50 1 ▶ my $add_truncate = $args->{'add_truncate'} || 0;
Condition50%1/2
$args->{'add_truncate'} || 0
l!l
01
MC/DC0%0/1
$args->{'add_truncate'} || 0
$args->{'add_truncate'}
Truth table50%1/2
A
A= $args->{'add_truncate'}
Aresult
11
00
51 1 ▶ my $skip = $args->{'skip'} || '';
Condition50%1/2
$args->{'skip'} || ''
l!l
10
MC/DC0%0/1
$args->{'skip'} || ''
$args->{'skip'}
Truth table50%1/2
A
A= $args->{'skip'}
Aresult
11
00
52 1 ▶ my $skiplike = $args->{'skiplike'} || '';
Condition50%1/2
$args->{'skiplike'} || ''
l!l
01
MC/DC0%0/1
$args->{'skiplike'} || ''
$args->{'skiplike'}
Truth table50%1/2
A
A= $args->{'skiplike'}
Aresult
11
00
53 1 ▶ my $db_user = $args->{'db_user'} || 'db_user';
Condition50%1/2
$args->{'db_user'} || 'db_user'
l!l
10
MC/DC0%0/1
$args->{'db_user'} || 'db_user'
$args->{'db_user'}
Truth table50%1/2
A
A= $args->{'db_user'}
Aresult
11
00
54 1 ▶ my $db_pass = $args->{'db_password'} || 'db_pass';
Condition50%1/2
$args->{'db_password'} || 'db_pass'
l!l
10
MC/DC0%0/1
$args->{'db_password'} || 'db_pass'
$args->{'db_password'}
Truth table50%1/2
A
A= $args->{'db_password'}
Aresult
11
00
55 1 my $parser_name = $t->parser_type;
56 1 my %skip = map { $_, 1 } map { s/^\s+|\s+$//; $_ }
57 split(/,/, $skip);
58 1 my $sqlt_version = $t->version;
59  
60 1 ▶ if ($parser_name =~ /Parser::(\w+)$/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($parser_name =~ /Parser::(\w+)$/) 1 0 1
61 1 $parser_name = $1;
62 }
63  
64 1 my %type_to_dbd = (
65 MySQL => 'mysql',
66 Oracle => 'Oracle',
67 PostgreSQL => 'Pg',
68 SQLite => 'SQLite',
69 Sybase => 'Sybase',
70 );
71 1 ▶ my $dbd = $type_to_dbd{$parser_name} || 'DBD';
Condition50%1/2
$type_to_dbd{$parser_name} || 'DBD'
l!l
10
MC/DC0%0/1
$type_to_dbd{$parser_name} || 'DBD'
$type_to_dbd{$parser_name}
Truth table50%1/2
A
A= $type_to_dbd{$parser_name}
Aresult
11
00
72 1 ▶ my $dsn = $args->{'dsn'} || "dbi:$dbd:";
Condition50%1/2
$args->{'dsn'} || "dbi:${dbd}:"
l!l
10
MC/DC0%0/1
$args->{'dsn'} || "dbi:${dbd}:"
$args->{'dsn'}
Truth table50%1/2
A
A= $args->{'dsn'}
Aresult
11
00
73 1 ▶ if ($dbd eq 'Pg' && !$args->{'dsn'}) {
Branch: 3 branches
BranchTrueFalseTotal
if ($dbd eq 'Pg' and not $args->{'dsn'}) { } 0 1 1
elsif ($dbd eq 'Oracle' and not $args->{'dsn'}) { } 0 1 1
elsif ($dbd eq 'mysql' and not $args->{'dsn'}) { } 0 2 2
Condition33%1/3
$dbd eq "Pg" and not $args->{"dsn"}
!ll&&!rl&&r
100
MC/DC0%0/2
$dbd eq "Pg" and not $args->{"dsn"}
$dbd eq "Pg" not $args->{"dsn"}
Truth table33%1/3
A and not(B)
A= $dbd eq "Pg"B= not $args->{"dsn"}
ABresult
0X0
100
111
74 0 $dsn .= 'dbname=dbname;host=hostname';
75 ▶ } elsif ($dbd eq 'Oracle' && !$args->{'dsn'}) {
Condition33%1/3
$dbd eq "Oracle" and not $args->{"dsn"}
!ll&&!rl&&r
100
MC/DC0%0/2
$dbd eq "Oracle" and not $args->{"dsn"}
$dbd eq "Oracle" not $args->{"dsn"}
Truth table33%1/3
A and not(B)
A= $dbd eq "Oracle"B= not $args->{"dsn"}
ABresult
0X0
100
111
76 0 $db_user = "$db_user/$db_pass@(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)"
77 . "(HOST=hostname)(PORT=1521))(CONNECT_DATA=(SID=sid)))";
78 0 $db_pass = '';
79 ▶ } elsif ($dbd eq 'mysql' && !$args->{'dsn'}) {
Condition33%1/3
$dbd eq "mysql" and not $args->{"dsn"}
!ll&&!rl&&r
100
MC/DC0%0/2
$dbd eq "mysql" and not $args->{"dsn"}
$dbd eq "mysql" not $args->{"dsn"}
Truth table33%1/3
A and not(B)
A= $dbd eq "mysql"B= not $args->{"dsn"}
ABresult
0X0
100
111
80 0 $dsn .= 'dbname';
81 }
82  
83 1 my $template = Template->new;
84 1 my $template_text = template();
85 1 my $out;
86 $template->process(
87 \$template_text,
88 {
89 translator => $t,
90 schema => $schema,
91 db_user => $db_user,
92 db_pass => $db_pass,
93 dsn => $dsn,
94 1 ▶ perl => $Config{'startperl'},
Branch: 1 branch
BranchTrueFalseTotal
$template->process(\$template_text, {"translator", $t, "schema", $schema, "db_user", $db_user, "db_pass", $db_pass, "dsn", $dsn, "perl", $SQL::Translator::Producer::Dumper::Config{"startperl"}, "skip", \%skip, "skiplike", $skiplike}, \$out) or die $template->error 1 0 1
95 skip => \%skip,
96 skiplike => $skiplike,
97 },
98 \$out
99 ) or die $template->error;
100  
101 1 return $out;
102 }
103  
104 1 ▶sub template {
Subroutine template: called CC=1 SCAR=0.0
Pod undocumented
105 #
106 # Returns the template to be processed by Template Toolkit
107 #
108 1 return <<'EOF';
109 [% perl || '#!/usr/bin/perl' %]
110 [% USE date %]
111 #
112 # Generated by SQL::Translator [% translator.version %]
113 # [% date.format( date.now, "%Y-%m-%d" ) %]
114 # For more info, see http://sqlfairy.sourceforge.net/
115 #
116  
117 use strict;
118 use Cwd;
119 use DBI;
120 use Getopt::Long;
121 use File::Spec::Functions 'catfile';
122  
123 my ( $help, $add_truncate, $skip, $skiplike, $no_comments,
124 $takelike, $mysql_loadfile );
125 GetOptions(
126 'add-truncate' => \$add_truncate,
127 'h|help' => \$help,
128 'no-comments' => \$no_comments,
129 'mysql-loadfile' => \$mysql_loadfile,
130 'skip:s' => \$skip,
131 'skiplike:s' => \$skiplike,
132 'takelike:s' => \$takelike,
133 );
134  
135 if ( $help ) {
136 print <<"USAGE";
137 Usage:
138 $0 [options] > dump.sql
139  
140 Options:
141 -h|--help Show help and exit
142 --add-truncate Add "TRUNCATE TABLE" statements
143 --mysql-loadfile Create MySQL's LOAD FILE syntax, not INSERTs
144 --no-comments Suppress comments
145 --skip=t1[,t2] Comma-separated list of tables to skip
146 --skiplike=regex Regular expression of table names to skip
147 --takelike=regex Regular expression of table names to take
148  
149 USAGE
150 exit(0);
151 }
152  
153 $no_comments = 1 if $mysql_loadfile;
154  
155 [%-
156 SET table_defs = [];
157 SET max_field = 0;
158  
159 FOREACH table IN schema.get_tables;
160 SET table_name = table.name;
161 NEXT IF skip.$table_name;
162 NEXT IF skiplike AND table_name.match("(?:$skiplike)");
163  
164 SET field_names = [];
165 SET types = {};
166 FOR field IN table.get_fields;
167 field_name = field.name;
168 fname_len = field.name.length;
169 max_field = fname_len > max_field ? fname_len : max_field;
170 types.$field_name = field.data_type.match( '(char|str|long|text|enum|date)' )
171 ? 'string' : 'number';
172 field_names.push( field_name );
173 END;
174  
175 table_defs.push({
176 name => table_name,
177 types => types,
178 fields => field_names,
179 });
180 END
181 -%]
182  
183 my $db = DBI->connect(
184 '[% dsn %]',
185 '[% db_user %]',
186 '[% db_pass %]',
187 { RaiseError => 1 }
188 );
189 my %skip = map { $_, 1 } map { s/^\s+|\s+$//; $_ } split (/,/, $skip);
190 my @tables = (
191 [%- FOREACH t IN table_defs %]
192 {
193 table_name => '[% t.name %]',
194 fields => [ qw/ [% t.fields.join(' ') %] / ],
195 types => {
196 [%- FOREACH fname IN t.types.keys %]
197 '[% fname %]' => '[% t.types.$fname %]',
198 [%- END %]
199 },
200 },
201 [%- END %]
202 );
203  
204 for my $table ( @tables ) {
205 my $table_name = $table->{'table_name'};
206 next if $skip{ $table_name };
207 next if $skiplike && $table_name =~ qr/$skiplike/;
208 next if $takelike && $table_name !~ qr/$takelike/;
209  
210 my ( $out_fh, $outfile );
211 if ( $mysql_loadfile ) {
212 $outfile = catfile( cwd(), "$table_name.txt" );
213 open $out_fh, ">$outfile" or
214 die "Can't write LOAD FILE to '$table_name': $!\n";
215 }
216  
217 print "--\n-- Data for table '$table_name'\n--\n" unless $no_comments;
218  
219 if ( $add_truncate ) {
220 print "TRUNCATE TABLE $table_name;\n";
221 }
222  
223 my $sql =
224 'select ' . join(', ', @{ $table->{'fields'} } ) . " from $table_name"
225 ;
226 my $sth = $db->prepare( $sql );
227 $sth->execute;
228  
229 while ( my $rec = $sth->fetchrow_hashref ) {
230 my @vals;
231 for my $fld ( @{ $table->{'fields'} } ) {
232 my $val = $rec->{ $fld };
233 if ( defined $val ) {
234 if ( $table->{'types'}{ $fld } eq 'string' ) {
235 $val =~ s/'/\\'/g;
236 $val = qq['$val']
237 }
238 } else {
239 $val = $mysql_loadfile ? '\N' : 'NULL';
240 }
241 push @vals, $val;
242 }
243  
244 if ( $mysql_loadfile ) {
245 print $out_fh join("\t", @vals), "\n";
246 }
247 else {
248 print "INSERT INTO $table_name (".
249 join(', ', @{ $table->{'fields'} }) .
250 ') VALUES (', join(', ', @vals), ");\n";
251 }
252 }
253  
254 if ( $out_fh ) {
255 print "LOAD DATA INFILE '$outfile' INTO TABLE $table_name ",
256 "FIELDS OPTIONALLY ENCLOSED BY '\\'';\n";
257 close $out_fh or die "Can't close filehandle: $!\n";
258 }
259 else {
260 print "\n";
261 }
262 }
263 EOF
264 }
265  
266 1 1;
267  
268 # -------------------------------------------------------------------
269 # To create a little flower is the labour of ages.
270 # William Blake
271 # -------------------------------------------------------------------
272  
273 =pod
274  
275 =head1 AUTHOR
276  
277 Ken Youens-Clark E<lt>kclark@cpan.orgE<gt>.
278  
279 =cut
« blib/lib/SQL/Translator/Parser/DBI.pm ↑ Summary blib/lib/SQL/Translator/Schema/Constraint.pm »