File: Dumper.pm

package info (click to toggle)
libsql-translator-perl 0.11011-1
  • links: PTS, VCS
  • area: main
  • in suites: wheezy
  • size: 15,380 kB
  • sloc: perl: 251,748; sql: 3,805; xml: 233; makefile: 7
file content (285 lines) | stat: -rw-r--r-- 7,990 bytes parent folder | download | duplicates (4)
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
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
package SQL::Translator::Producer::Dumper;

=head1 NAME

SQL::Translator::Producer::Dumper - SQL Dumper producer for SQL::Translator

=head1 SYNOPSIS

  use SQL::Translator::Producer::Dumper;

  Options:

    db_user         Database username
    db_password     Database password
    dsn             DSN for DBI
    mysql_loadfile  Create MySQL's LOAD FILE syntax instead of INSERTs
    skip=t1[,t2]    Skip tables in comma-separated list
    skiplike=regex  Skip tables in comma-separated list

=head1 DESCRIPTION

This producer creates a Perl script that can connect to a database and
dump the data as INSERT statements (a la mysqldump) or as a file
suitable for MySQL's LOAD DATA command.  If you enable "add-truncate"
or specify tables to "skip" (also using the "skiplike" regular
expression) then the generated dumper script will leave out those
tables.  However, these will also be options in the generated dumper,
so you can wait to specify these options when you dump your database.
The database username, password, and DSN can be hardcoded into the
generated script, or part of the DSN can be intuited from the
"database" argument.

=cut

use strict;
use warnings;
use Config;
use SQL::Translator;
use File::Temp 'tempfile';
use Template;

use Data::Dumper;

our $VERSION = '1.59';

sub produce {
    my $t              = shift;
    my $args           = $t->producer_args;
    my $schema         = $t->schema;
    my $add_truncate   = $args->{'add_truncate'}   || 0;
    my $skip           = $args->{'skip'}           || '';
    my $skiplike       = $args->{'skiplike'}       || '';
    my $db_user        = $args->{'db_user'}        || 'db_user';
    my $db_pass        = $args->{'db_password'}    || 'db_pass';
    my $parser_name    = $t->parser_type;
    my %skip           = map { $_, 1 } map { s/^\s+|\s+$//; $_ }
                         split (/,/, $skip);
    my $sqlt_version   = $t->version;

    if ( $parser_name  =~ /Parser::(\w+)$/ ) {
        $parser_name = $1
    }

    my %type_to_dbd    = (
        MySQL          => 'mysql',
        Oracle         => 'Oracle',
        PostgreSQL     => 'Pg',
        SQLite         => 'SQLite',
        Sybase         => 'Sybase',
    );
    my $dbd            = $type_to_dbd{ $parser_name } || 'DBD';
    my $dsn            = $args->{'dsn'} || "dbi:$dbd:";
    if ( $dbd eq 'Pg' && ! $args->{'dsn'} ) {
        $dsn .= 'dbname=dbname;host=hostname';
    }
    elsif ( $dbd eq 'Oracle' && ! $args->{'dsn'} ) {
        $db_user = "$db_user/$db_pass@(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)" .
            "(HOST=hostname)(PORT=1521))(CONNECT_DATA=(SID=sid)))";
        $db_pass = '';
    }
    elsif ( $dbd eq 'mysql' && ! $args->{'dsn'} ) {
        $dsn .= 'dbname';
    }

    my $template      = Template->new;
    my $template_text = template();
    my $out;
    $template->process(
        \$template_text,
        {
            translator     => $t,
            schema         => $schema,
            db_user        => $db_user,
            db_pass        => $db_pass,
            dsn            => $dsn,
            perl           => $Config{'startperl'},
            skip           => \%skip,
            skiplike       => $skiplike,
        },
        \$out
    ) or die $template->error;

    return $out;
}

sub template {
#
# Returns the template to be processed by Template Toolkit
#
    return <<'EOF';
[% perl || '#!/usr/bin/perl' %]
[% USE date %]
#
# Generated by SQL::Translator [% translator.version %]
# [% date.format( date.now, "%Y-%m-%d" ) %]
# For more info, see http://sqlfairy.sourceforge.net/
#

use strict;
use Cwd;
use DBI;
use Getopt::Long;
use File::Spec::Functions 'catfile';

my ( $help, $add_truncate, $skip, $skiplike, $no_comments,
    $takelike, $mysql_loadfile );
GetOptions(
    'add-truncate'   => \$add_truncate,
    'h|help'         => \$help,
    'no-comments'    => \$no_comments,
    'mysql-loadfile' => \$mysql_loadfile,
    'skip:s'         => \$skip,
    'skiplike:s'     => \$skiplike,
    'takelike:s'     => \$takelike,
);

if ( $help ) {
    print <<"USAGE";
Usage:
  $0 [options] > dump.sql

  Options:
    -h|--help          Show help and exit
    --add-truncate     Add "TRUNCATE TABLE" statements
    --mysql-loadfile   Create MySQL's LOAD FILE syntax, not INSERTs
    --no-comments      Suppress comments
    --skip=t1[,t2]     Comma-separated list of tables to skip
    --skiplike=regex   Regular expression of table names to skip
    --takelike=regex   Regular expression of table names to take

USAGE
    exit(0);
}

$no_comments = 1 if $mysql_loadfile;

[%-
SET table_defs = [];
SET max_field  = 0;

FOREACH table IN schema.get_tables;
    SET table_name = table.name;
    NEXT IF skip.$table_name;
    NEXT IF skiplike AND table_name.match("(?:$skiplike)");

    SET field_names = [];
    SET types       = {};
    FOR field IN table.get_fields;
        field_name = field.name;
        fname_len  = field.name.length;
        max_field  = fname_len > max_field ? fname_len : max_field;
        types.$field_name = field.data_type.match( '(char|str|long|text|enum|date)' )
            ? 'string' : 'number';
        field_names.push( field_name );
    END;

    table_defs.push({
        name   => table_name,
        types  => types,
        fields => field_names,
    });
END
-%]

my $db     = DBI->connect(
    '[% dsn %]',
    '[% db_user %]',
    '[% db_pass %]',
    { RaiseError => 1 }
);
my %skip   = map { $_, 1 } map { s/^\s+|\s+$//; $_ } split (/,/, $skip);
my @tables = (
[%- FOREACH t IN table_defs %]
    {
        table_name  => '[% t.name %]',
        fields      => [ qw/ [% t.fields.join(' ') %] / ],
        types       => {
            [%- FOREACH fname IN t.types.keys %]
            '[% fname %]' => '[% t.types.$fname %]',
            [%- END %]
        },
    },
[%- END %]
);

for my $table ( @tables ) {
    my $table_name = $table->{'table_name'};
    next if $skip{ $table_name };
    next if $skiplike && $table_name =~ qr/$skiplike/;
    next if $takelike && $table_name !~ qr/$takelike/;

    my ( $out_fh, $outfile );
    if ( $mysql_loadfile ) {
        $outfile = catfile( cwd(), "$table_name.txt" );
        open $out_fh, ">$outfile" or
            die "Can't write LOAD FILE to '$table_name': $!\n";
    }

    print "--\n-- Data for table '$table_name'\n--\n" unless $no_comments;

    if ( $add_truncate ) {
        print "TRUNCATE TABLE $table_name;\n";
    }

    my $sql =
        'select ' . join(', ', @{ $table->{'fields'} } ) . " from $table_name"
    ;
    my $sth = $db->prepare( $sql );
    $sth->execute;

    while ( my $rec = $sth->fetchrow_hashref ) {
        my @vals;
        for my $fld ( @{ $table->{'fields'} } ) {
            my $val = $rec->{ $fld };
            if ( $table->{'types'}{ $fld } eq 'string' ) {
                if ( defined $val ) {
                    $val =~ s/'/\\'/g;
                    $val = qq['$val']
                }
                else {
                    $val = qq[''];
                }
            }
            else {
                $val = defined $val ? $val : $mysql_loadfile ? '\N' : 'NULL';
            }
            push @vals, $val;
        }

        if ( $mysql_loadfile ) {
            print $out_fh join("\t", @vals), "\n";
        }
        else {
            print "INSERT INTO $table_name (".
                join(', ', @{ $table->{'fields'} }) .
                ') VALUES (', join(', ', @vals), ");\n";
        }
    }

    if ( $out_fh ) {
        print "LOAD DATA INFILE '$outfile' INTO TABLE $table_name ",
            "FIELDS OPTIONALLY ENCLOSED BY '\\'';\n";
        close $out_fh or die "Can't close filehandle: $!\n";
    }
    else {
        print "\n";
    }
}
EOF
}

1;

# -------------------------------------------------------------------
# To create a little flower is the labour of ages.
# William Blake
# -------------------------------------------------------------------

=pod

=head1 AUTHOR

Ken Youens-Clark E<lt>kclark@cpan.orgE<gt>.

=cut