File Coverage

blib/lib/SQL/Translator.pm
Criterion Covered Total %
statement 201 216 93.0
branch 87 114 76.3
condition 23 45 51.1
subroutine 32 33 96.9
pod 4 13 30.7
total 347 421 82.4


line stmt bran cond sub pod time code
1             package SQL::Translator;
2              
3 71     71   2890225 use Moo;
  71         657822  
  71         505  
4             our ($DEFAULT_SUB, $DEBUG, $ERROR);
5              
6             our $VERSION = '1.66';
7             $VERSION =~ tr/_//d;
8             $DEBUG = 0 unless defined $DEBUG;
9             $ERROR = "";
10              
11 71     71   135572 use Carp qw(carp croak);
  71         183  
  71         4913  
12              
13 71     71   19513 use Data::Dumper;
  71         300322  
  71         5200  
14 71     71   560 use File::Find;
  71         195  
  71         7668  
15 71     71   37701 use File::Spec::Functions qw(catfile);
  71         69178  
  71         6696  
16 71     71   600 use File::Basename qw(dirname);
  71         133  
  71         5725  
17 71     71   52387 use IO::Dir;
  71         1701297  
  71         5164  
18 71     71   41899 use Sub::Quote qw(quote_sub);
  71         575151  
  71         6196  
19 71     71   36132 use SQL::Translator::Producer;
  71         233  
  71         3097  
20 71     71   41813 use SQL::Translator::Schema;
  71         386  
  71         3933  
21 71     71   654 use SQL::Translator::Utils qw(throw ex2err carp_ro normalize_quote_options);
  71         151  
  71         375771  
22              
23             $DEFAULT_SUB = sub { $_[0]->schema }
24             unless defined $DEFAULT_SUB;
25              
26             with qw(
27             SQL::Translator::Role::Debug
28             SQL::Translator::Role::Error
29             SQL::Translator::Role::BuildArgs
30             );
31              
32             around BUILDARGS => sub {
33             my $orig = shift;
34             my $self = shift;
35             my $config = $self->$orig(@_);
36              
37             # If a 'parser' or 'from' parameter is passed in, use that as the
38             # parser; if a 'producer' or 'to' parameter is passed in, use that
39             # as the producer; both default to $DEFAULT_SUB.
40             $config->{parser} ||= $config->{from} if defined $config->{from};
41             $config->{producer} ||= $config->{to} if defined $config->{to};
42              
43             $config->{filename} ||= $config->{file} if defined $config->{file};
44              
45             my $quote = normalize_quote_options($config);
46             $config->{quote_identifiers} = $quote if defined $quote;
47              
48             return $config;
49             };
50              
51             sub BUILD {
52 142     142 0 16188 my ($self) = @_;
53              
54             # Make sure all the tool-related stuff is set up
55 142         448 foreach my $tool (qw(producer parser)) {
56 284         8526 $self->$tool($self->$tool);
57             }
58             }
59              
60             has $_ => (
61             is => 'rw',
62             default => quote_sub(q{ 0 }),
63             coerce => quote_sub(q{ $_[0] ? 1 : 0 }),
64             ) foreach qw(add_drop_table no_comments show_warnings trace validate);
65              
66             # quote_identifiers is on by default, use a 0-but-true as indicator
67             # so we can allow individual producers to change the default
68             has quote_identifiers => (
69             is => 'rw',
70             default => quote_sub(q{ '0E0' }),
71             coerce => quote_sub(q{ $_[0] || 0 }),
72             );
73              
74             sub quote_table_names {
75 11 50 33 11 1 441 (@_ > 1 and ($_[1] xor $_[0]->quote_identifiers))
76             ? croak 'Using quote_table_names as a setter is no longer supported'
77             : $_[0]->quote_identifiers;
78             }
79              
80             sub quote_field_names {
81 11 50 33 11 1 347 (@_ > 1 and ($_[1] xor $_[0]->quote_identifiers))
82             ? croak 'Using quote_field_names as a setter is no longer supported'
83             : $_[0]->quote_identifiers;
84             }
85              
86             after quote_identifiers => sub {
87             if (@_ > 1) {
88              
89             # synchronize for old code reaching directly into guts
90             $_[0]->{quote_table_names} = $_[0]->{quote_field_names} = $_[1] ? 1 : 0;
91             }
92             };
93              
94             has producer => (is => 'rw', default => sub {$DEFAULT_SUB});
95              
96             around producer => sub {
97             my $orig = shift;
98             shift->_tool(
99             {
100             orig => $orig,
101             name => 'producer',
102             path => "SQL::Translator::Producer",
103             default_sub => "produce",
104             },
105             @_
106             );
107             };
108              
109             has producer_type => (is => 'rwp', init_arg => undef);
110              
111             around producer_type => carp_ro('producer_type');
112              
113             has producer_args => (is => 'rw', default => quote_sub(q{ +{} }));
114              
115             around producer_args => sub {
116             my $orig = shift;
117             shift->_args($orig, @_);
118             };
119              
120             has parser => (is => 'rw', default => sub {$DEFAULT_SUB});
121              
122             around parser => sub {
123             my $orig = shift;
124             shift->_tool(
125             {
126             orig => $orig,
127             name => 'parser',
128             path => "SQL::Translator::Parser",
129             default_sub => "parse",
130             },
131             @_
132             );
133             };
134              
135             has parser_type => (is => 'rwp', init_arg => undef);
136              
137             around parser_type => carp_ro('parser_type');
138              
139             has parser_args => (is => 'rw', default => quote_sub(q{ +{} }));
140              
141             around parser_args => sub {
142             my $orig = shift;
143             shift->_args($orig, @_);
144             };
145              
146             has filters => (
147             is => 'rw',
148             default => quote_sub(q{ [] }),
149             coerce => sub {
150             my @filters;
151              
152             # Set. Convert args to list of [\&code,@args]
153             foreach (@{ $_[0] || [] }) {
154             my ($filt, @args) = ref($_) eq "ARRAY" ? @$_ : $_;
155             if (isa($filt, "CODE")) {
156             push @filters, [ $filt, @args ];
157             next;
158             } else {
159             __PACKAGE__->debug("Adding $filt filter. Args:" . Dumper(\@args) . "\n")
160             if __PACKAGE__->debugging;
161             $filt = _load_sub("$filt\::filter", "SQL::Translator::Filter")
162             || throw(__PACKAGE__->error);
163             push @filters, [ $filt, @args ];
164             }
165             }
166             return \@filters;
167             },
168             );
169              
170             around filters => sub {
171             my $orig = shift;
172             my $self = shift;
173             return @{ $self->$orig([ @{ $self->$orig }, @_ ]) } if @_;
174             return @{ $self->$orig };
175             };
176              
177             has filename => (
178             is => 'rw',
179             isa => sub {
180             foreach my $filename (ref($_[0]) eq 'ARRAY' ? @{ $_[0] } : $_[0]) {
181             if (-d $filename) {
182             throw("Cannot use directory '$filename' as input source");
183             } elsif (not -f _ && -r _ ) {
184             throw("Cannot use '$filename' as input source: " . "file does not exist or is not readable.");
185             }
186             }
187             },
188             );
189              
190             around filename => \&ex2err;
191              
192             has data => (
193             is => 'rw',
194             builder => 1,
195             lazy => 1,
196             coerce => sub {
197              
198             # Set $self->data based on what was passed in. We will
199             # accept a number of things; do our best to get it right.
200             my $data = shift;
201             if (isa($data, 'ARRAY')) {
202             $data = join '', @$data;
203             } elsif (isa($data, 'GLOB')) {
204             seek($data, 0, 0) if eof($data);
205             local $/;
206             $data = <$data>;
207             }
208             return isa($data, 'SCALAR') ? $data : \$data;
209             },
210             );
211              
212             around data => sub {
213             my $orig = shift;
214             my $self = shift;
215              
216             if (@_ > 1 && !ref $_[0]) {
217             return $self->$orig(\join('', @_));
218             } elsif (@_) {
219             return $self->$orig(@_);
220             }
221             return ex2err($orig, $self);
222             };
223              
224             sub _build_data {
225 54     54   6210 my $self = shift;
226              
227             # If we have a filename but no data yet, populate.
228 54 100       1508 if (my $filename = $self->filename) {
229 50         1746 $self->debug("Opening '$filename' to get contents.\n");
230 50         639 local $/;
231 50         117 my $data;
232              
233 50 50       295 my @files = ref($filename) eq 'ARRAY' ? @$filename : ($filename);
234              
235 50         177 foreach my $file (@files) {
236 50 50       4774 open my $fh, '<', $file
237             or throw("Can't read file '$file': $!");
238              
239 50         34861 $data .= <$fh>;
240              
241 50 50       1223 close $fh or throw("Can't close file '$file': $!");
242             }
243              
244 50         570 return \$data;
245             }
246             }
247              
248             has schema => (
249             is => 'lazy',
250             init_arg => undef,
251             clearer => 'reset',
252             predicate => '_has_schema',
253             );
254              
255             around schema => carp_ro('schema');
256              
257             around reset => sub {
258             my $orig = shift;
259             my $self = shift;
260             $self->$orig(@_);
261             return 1;
262             };
263              
264 125     125   4312 sub _build_schema { SQL::Translator::Schema->new(translator => shift) }
265              
266             sub translate {
267 119     119 1 7188501 my $self = shift;
268 119         548 my ($args, $parser, $parser_type, $producer, $producer_type);
269 119         0 my ($parser_output, $producer_output, @producer_output);
270              
271             # Parse arguments
272 119 100       2791 if (@_ == 1) {
273              
274             # Passed a reference to a hash?
275 52 50       217 if (isa($_[0], 'HASH')) {
    50          
    100          
    50          
276              
277             # yep, a hashref
278 0         0 $self->debug("translate: Got a hashref\n");
279 0         0 $args = $_[0];
280             }
281              
282             # Passed a GLOB reference, i.e., filehandle
283             elsif (isa($_[0], 'GLOB')) {
284 0         0 $self->debug("translate: Got a GLOB reference\n");
285 0         0 $self->data($_[0]);
286             }
287              
288             # Passed a reference to a string containing the data
289             elsif (isa($_[0], 'SCALAR')) {
290              
291             # passed a ref to a string
292 19         125 $self->debug("translate: Got a SCALAR reference (string)\n");
293 19         715 $self->data($_[0]);
294             }
295              
296             # Not a reference; treat it as a filename
297             elsif (!ref $_[0]) {
298              
299             # Not a ref, it's a filename
300 33         174 $self->debug("translate: Got a filename\n");
301 33         1068 $self->filename($_[0]);
302             }
303              
304             # Passed something else entirely.
305             else {
306             # We're not impressed. Take your empty string and leave.
307             # return "";
308              
309             # Actually, if data, parser, and producer are set, then we
310             # can continue. Too bad, because I like my comment
311             # (above)...
312 0 0 0     0 return ""
      0        
313             unless ($self->data
314             && $self->producer
315             && $self->parser);
316             }
317             } else {
318             # You must pass in a hash, or you get nothing.
319 67 50       353 return "" if @_ % 2;
320 67         426 $args = {@_};
321             }
322              
323             # ----------------------------------------------------------------------
324             # Can specify the data to be transformed using "filename", "file",
325             # "data", or "datasource".
326             # ----------------------------------------------------------------------
327 119 100 100     2172 if (my $filename = ($args->{'filename'} || $args->{'file'})) {
328 20         711 $self->filename($filename);
329             }
330              
331 119 100 66     1525 if (my $data = ($args->{'data'} || $args->{'datasource'})) {
332 36         1409 $self->data($data);
333             }
334              
335             # ----------------------------------------------------------------
336             # Get the data.
337             # ----------------------------------------------------------------
338 119         3926 my $data = $self->data;
339              
340             # ----------------------------------------------------------------
341             # Local reference to the parser subroutine
342             # ----------------------------------------------------------------
343 119 100 100     4888 if ($parser = ($args->{'parser'} || $args->{'from'})) {
344 33         967 $self->parser($parser);
345             }
346 119         3462 $parser = $self->parser;
347 119         3097 $parser_type = $self->parser_type;
348              
349             # ----------------------------------------------------------------
350             # Local reference to the producer subroutine
351             # ----------------------------------------------------------------
352 119 100 100     974 if ($producer = ($args->{'producer'} || $args->{'to'})) {
353 42         5500 $self->producer($producer);
354             }
355 119         3046 $producer = $self->producer;
356 119         3141 $producer_type = $self->producer_type;
357              
358             # ----------------------------------------------------------------
359             # Execute the parser, the filters and then execute the producer.
360             # Allowances are made for each piece to die, or fail to compile,
361             # since the referenced subroutines could be almost anything. In
362             # the future, each of these might happen in a Safe environment,
363             # depending on how paranoid we want to be.
364             # ----------------------------------------------------------------
365              
366             # Run parser
367 119 100       3871 unless ($self->_has_schema) {
368 84         228 eval { $parser_output = $parser->($self, $$data) };
  84         528  
369 84 100 66     109738 if ($@ || !$parser_output) {
370 2 50       43 my $msg = sprintf "translate: Error with parser '%s': %s", $parser_type, ($@) ? $@ : " no results";
371 2         118 return $self->error($msg);
372             }
373             }
374 117 50       4927 $self->debug("Schema =\n", Dumper($self->schema), "\n")
375             if $self->debugging;
376              
377             # Validate the schema if asked to.
378 117 50       4428 if ($self->validate) {
379 0         0 my $schema = $self->schema;
380 0 0       0 return $self->error('Invalid schema') unless $schema->is_valid;
381             }
382              
383             # Run filters
384 117         1271 my $filt_num = 0;
385 117         3004 foreach ($self->filters) {
386 10         30 $filt_num++;
387 10         23 my ($code, @args) = @$_;
388 10         16 eval { $code->($self->schema, @args) };
  10         134  
389 10   50     5190 my $err = $@ || $self->error || 0;
390 10 50       24 return $self->error("Error with filter $filt_num : $err") if $err;
391             }
392              
393             # Run producer
394             # Calling wantarray in the eval no work, wrong scope.
395 117 100       1426 my $wantarray = wantarray ? 1 : 0;
396 117         279 eval {
397 117 100       362 if ($wantarray) {
398 10         60 @producer_output = $producer->($self);
399             } else {
400 107         658 $producer_output = $producer->($self);
401             }
402             };
403 117 50 66     324185 if ($@ || !($producer_output || @producer_output)) {
      33        
404 0   0     0 my $err = $@ || $self->error || "no results";
405 0         0 my $msg = "translate: Error with producer '$producer_type': $err";
406 0         0 return $self->error($msg);
407             }
408              
409 117 100       1515 return wantarray ? @producer_output : $producer_output;
410             }
411              
412             sub list_parsers {
413 8     8 0 41 return shift->_list("parser");
414             }
415              
416             sub list_producers {
417 0     0 0 0 return shift->_list("producer");
418             }
419              
420             # ======================================================================
421             # Private Methods
422             # ======================================================================
423              
424             # ----------------------------------------------------------------------
425             # _args($type, \%args);
426             #
427             # Gets or sets ${type}_args. Called by parser_args and producer_args.
428             # ----------------------------------------------------------------------
429             sub _args {
430 212     212   527 my $self = shift;
431 212         598 my $orig = shift;
432              
433 212 100       935 if (@_) {
434              
435             # If the first argument is an explicit undef (remember, we
436             # don't get here unless there is stuff in @_), then we clear
437             # out the producer_args hash.
438 3 50       9 if (!defined $_[0]) {
439 0         0 shift @_;
440 0         0 $self->$orig({});
441             }
442              
443 3 100       8 my $args = isa($_[0], 'HASH') ? shift : {@_};
444 3         6 return $self->$orig({ %{ $self->$orig }, %$args });
  3         21  
445             }
446              
447 209         2325 return $self->$orig;
448             }
449              
450             # ----------------------------------------------------------------------
451             # Does the get/set work for parser and producer. e.g.
452             # return $self->_tool({
453             # name => 'producer',
454             # path => "SQL::Translator::Producer",
455             # default_sub => "produce",
456             # }, @_);
457             # ----------------------------------------------------------------------
458             sub _tool {
459 917     917   1977 my ($self, $args) = (shift, shift);
460 917         1914 my $name = $args->{name};
461 917         1629 my $orig = $args->{orig};
462 917 100       10399 return $self->{$name} unless @_; # get accessor
463              
464 387         1083 my $path = $args->{path};
465 387         765 my $default_sub = $args->{default_sub};
466 387         998 my $tool = shift;
467              
468             # passed an anonymous subroutine reference
469 387 100       1322 if (isa($tool, 'CODE')) {
470 228         976 $self->$orig($tool);
471 228         523 $self->${ \"_set_${name}_type" }("CODE");
  228         1515  
472 228         1339 $self->debug("Got $name: code ref\n");
473             }
474              
475             # Module name was passed directly
476             # We try to load the name; if it doesn't load, there's a
477             # possibility that it has a function name attached to it,
478             # so we give it a go.
479             else {
480 159 100       939 $tool =~ s/-/::/g if $tool !~ /::/;
481 159         388 my ($code, $sub);
482 159         865 ($code, $sub) = _load_sub("$tool\::$default_sub", $path);
483 159 100       685 unless ($code) {
484 1 50       35 if (__PACKAGE__->error =~ m/Can't find module/) {
485              
486             # Mod not found so try sub
487 1 50       5 ($code, $sub) = _load_sub("$tool", $path) unless $code;
488 1 50       6 die "Can't load $name subroutine '$tool' : " . __PACKAGE__->error
489             unless $code;
490             } else {
491 0         0 die "Can't load $name '$tool' : " . __PACKAGE__->error;
492             }
493             }
494              
495             # get code reference and assign
496 159         1420 my (undef, $module, undef) = $sub =~ m/((.*)::)?(\w+)$/;
497 159         805 $self->$orig($code);
498 159 50       590 $self->${ \"_set_$name\_type" }($sub eq "CODE" ? "CODE" : $module);
  159         1421  
499 159         868 $self->debug("Got $name: $sub\n");
500             }
501              
502             # At this point, $self->{$name} contains a subroutine
503             # reference that is ready to run
504              
505             # Anything left? If so, it's args
506 387         5005 my $meth = "$name\_args";
507 387 100       1143 $self->$meth(@_) if (@_);
508              
509 387         3127 return $self->{$name};
510             }
511              
512             # ----------------------------------------------------------------------
513             # _list($type)
514             # ----------------------------------------------------------------------
515             sub _list {
516 8     8   19 my $self = shift;
517 8   50     68 my $type = shift || return ();
518 8         32 my $uctype = ucfirst lc $type;
519              
520             #
521             # First find all the directories where SQL::Translator
522             # parsers or producers (the "type") appear to live.
523             #
524 8 50       39 load("SQL::Translator::$uctype") or return ();
525 8         71 my $path = catfile "SQL", "Translator", $uctype;
526 8         20 my @dirs;
527 8         27 for (@INC) {
528 64         330 my $dir = catfile $_, $path;
529 64         293 $self->debug("_list_${type}s searching $dir\n");
530 64 100       1637 next unless -d $dir;
531 24         87 push @dirs, $dir;
532             }
533              
534             #
535             # Now use File::File::find to look recursively in those
536             # directories for all the *.pm files, then present them
537             # with the slashes turned into dashes.
538             #
539 8         20 my %found;
540             find(
541             sub {
542 672 100 66 672   19330 if (-f && m/\.pm$/) {
543 576         993 my $mod = $_;
544 576         1774 $mod =~ s/\.pm$//;
545 576         926 my $cur_dir = $File::Find::dir;
546 576         2585 my $base_dir = quotemeta catfile 'SQL', 'Translator', $uctype;
547              
548             #
549             # See if the current directory is below the base directory.
550             #
551 576 50       3373 if ($cur_dir =~ m/$base_dir(.*)/) {
552 576         1300 $cur_dir = $1;
553 576         1103 $cur_dir =~ s!^/!!; # kill leading slash
554 576         886 $cur_dir =~ s!/!-!g; # turn other slashes into dashes
555             } else {
556 0         0 $cur_dir = '';
557             }
558              
559 576 100       1019 $found{ join '-', map { $_ || () } $cur_dir, $mod } = 1;
  1152         15018  
560             }
561             },
562             @dirs
563 8         990 );
564              
565 8         270 return sort { lc $a cmp lc $b } keys %found;
  649         1112  
566             }
567              
568             # ----------------------------------------------------------------------
569             # load(MODULE [,PATH[,PATH]...])
570             #
571             # Loads a Perl module. Short circuits if a module is already loaded.
572             #
573             # MODULE - is the name of the module to load.
574             #
575             # PATH - optional list of 'package paths' to look for the module in. e.g
576             # If you called load('Super::Foo' => 'My', 'Other') it will
577             # try to load the mod Super::Foo then My::Super::Foo then Other::Super::Foo.
578             #
579             # Returns package name of the module actually loaded or false and sets error.
580             #
581             # Note, you can't load a name from the root namespace (ie one without '::' in
582             # it), therefore a single word name without a path fails.
583             # ----------------------------------------------------------------------
584             sub load {
585 173     173 0 432 my $name = shift;
586 173         338 my @path;
587 173 100       798 push @path, "" if $name =~ /::/; # Empty path to check name on its own first
588 173 100       658 push @path, @_ if @_;
589              
590 173         511 foreach (@path) {
591 197 100       843 my $module = $_ ? "$_\::$name" : $name;
592 197         469 my $file = $module;
593 197         1218 $file =~ s[::][/]g;
594 197         498 $file .= ".pm";
595 197         1430 __PACKAGE__->debug("Loading $name as $file\n");
596 197 100       1361 return $module if $INC{$file}; # Already loaded
597              
598 64         150 eval { require $file };
  64         42726  
599 64 100       1840 next if $@ =~ /Can't locate $file in \@INC/;
600 39 50       174 eval { $module->import() } unless $@;
  39         849  
601 39 50 33     192 return __PACKAGE__->error("Error loading $name as $module : $@")
602             if $@ && $@ !~ /"SQL::Translator::Producer" is not exported/;
603              
604 39         252 return $module; # Module loaded ok
605             }
606              
607 1         30 return __PACKAGE__->error("Can't find module $name. Path:" . join(",", @path));
608             }
609              
610             # ----------------------------------------------------------------------
611             # Load the sub name given (including package), optionally using a base package
612             # path. Returns code ref and name of sub loaded, including its package.
613             # (\&code, $sub) = load_sub( 'MySQL::produce', "SQL::Translator::Producer" );
614             # (\&code, $sub) = load_sub( 'MySQL::produce', @path );
615             # ----------------------------------------------------------------------
616             sub _load_sub {
617 165     165   544 my ($tool, @path) = @_;
618              
619 165         1502 my (undef, $module, $func_name) = $tool =~ m/((.*)::)?(\w+)$/;
620 165 100       655 if (my $module = load($module => @path)) {
621 164         450 my $sub = "$module\::$func_name";
622 164 100       657 return wantarray ? (\&{$sub}, $sub) : \&$sub;
  159         1606  
623             }
624 1         4 return undef;
625             }
626              
627             sub format_table_name {
628 6     6 0 3151 return shift->_format_name('_format_table_name', @_);
629             }
630              
631             sub format_package_name {
632 6     6 0 2419 return shift->_format_name('_format_package_name', @_);
633             }
634              
635             sub format_fk_name {
636 6     6 0 1715 return shift->_format_name('_format_fk_name', @_);
637             }
638              
639             sub format_pk_name {
640 6     6 0 2739 return shift->_format_name('_format_pk_name', @_);
641             }
642              
643             # ----------------------------------------------------------------------
644             # The other format_*_name methods rely on this one. It optionally
645             # accepts a subroutine ref as the first argument (or uses an identity
646             # sub if one isn't provided or it doesn't already exist), and applies
647             # it to the rest of the arguments (if any).
648             # ----------------------------------------------------------------------
649             sub _format_name {
650 24     24   32 my $self = shift;
651 24         29 my $field = shift;
652 24         42 my @args = @_;
653              
654 24 100       76 if (ref($args[0]) eq 'CODE') {
    100          
655 12         29 $self->{$field} = shift @args;
656             } elsif (!exists $self->{$field}) {
657 4     4   17 $self->{$field} = sub { return shift };
  4         19  
658             }
659              
660 24 100       90 return @args ? $self->{$field}->(@args) : $self->{$field};
661             }
662              
663             sub isa($$) {
664 901     901 0 2383 my ($ref, $type) = @_;
665 901         8779 return UNIVERSAL::isa($ref, $type);
666             }
667              
668             sub version {
669 9     9 1 57586 my $self = shift;
670 9         89 return $VERSION;
671             }
672              
673             # Must come after all 'has' declarations
674             around new => \&ex2err;
675              
676             1;
677              
678             # ----------------------------------------------------------------------
679             # Who killed the pork chops?
680             # What price bananas?
681             # Are you my Angel?
682             # Allen Ginsberg
683             # ----------------------------------------------------------------------
684              
685             =pod
686              
687             =head1 NAME
688              
689             SQL::Translator - manipulate structured data definitions (SQL and more)
690              
691             =head1 SYNOPSIS
692              
693             use SQL::Translator;
694              
695             my $translator = SQL::Translator->new(
696             # Print debug info
697             debug => 1,
698             # Print Parse::RecDescent trace
699             trace => 0,
700             # Don't include comments in output
701             no_comments => 0,
702             # Print name mutations, conflicts
703             show_warnings => 0,
704             # Add "drop table" statements
705             add_drop_table => 1,
706             # to quote or not to quote, thats the question
707             quote_identifiers => 1,
708             # Validate schema object
709             validate => 1,
710             # Make all table names CAPS in producers which support this option
711             format_table_name => sub {my $tablename = shift; return uc($tablename)},
712             # Null-op formatting, only here for documentation's sake
713             format_package_name => sub {return shift},
714             format_fk_name => sub {return shift},
715             format_pk_name => sub {return shift},
716             );
717              
718             my $output = $translator->translate(
719             from => 'MySQL',
720             to => 'Oracle',
721             # Or an arrayref of filenames, i.e. [ $file1, $file2, $file3 ]
722             filename => $file,
723             ) or die $translator->error;
724              
725             print $output;
726              
727             =head1 DESCRIPTION
728              
729             This documentation covers the API for SQL::Translator. For a more general
730             discussion of how to use the modules and scripts, please see
731             L.
732              
733             SQL::Translator is a group of Perl modules that converts
734             vendor-specific SQL table definitions into other formats, such as
735             other vendor-specific SQL, ER diagrams, documentation (POD and HTML),
736             XML, and Class::DBI classes. The main focus of SQL::Translator is
737             SQL, but parsers exist for other structured data formats, including
738             Excel spreadsheets and arbitrarily delimited text files. Through the
739             separation of the code into parsers and producers with an object model
740             in between, it's possible to combine any parser with any producer, to
741             plug in custom parsers or producers, or to manipulate the parsed data
742             via the built-in object model. Presently only the definition parts of
743             SQL are handled (CREATE, ALTER), not the manipulation of data (INSERT,
744             UPDATE, DELETE).
745              
746             =head1 CONSTRUCTOR
747              
748             =head2 new
749              
750             The constructor is called C, and accepts a optional hash of options.
751             Valid options are:
752              
753             =over 4
754              
755             =item *
756              
757             parser / from
758              
759             =item *
760              
761             parser_args
762              
763             =item *
764              
765             producer / to
766              
767             =item *
768              
769             producer_args
770              
771             =item *
772              
773             filters
774              
775             =item *
776              
777             filename / file
778              
779             =item *
780              
781             data
782              
783             =item *
784              
785             debug
786              
787             =item *
788              
789             add_drop_table
790              
791             =item *
792              
793             quote_identifiers
794              
795             =item *
796              
797             quote_table_names (DEPRECATED)
798              
799             =item *
800              
801             quote_field_names (DEPRECATED)
802              
803             =item *
804              
805             no_comments
806              
807             =item *
808              
809             trace
810              
811             =item *
812              
813             validate
814              
815             =back
816              
817             All options are, well, optional; these attributes can be set via
818             instance methods. Internally, they are; no (non-syntactical)
819             advantage is gained by passing options to the constructor.
820              
821             =head1 METHODS
822              
823             =head2 add_drop_table
824              
825             Toggles whether or not to add "DROP TABLE" statements just before the
826             create definitions.
827              
828             =head2 quote_identifiers
829              
830             Toggles whether or not to quote identifiers (table, column, constraint, etc.)
831             with a quoting mechanism suitable for the chosen Producer. The default (true)
832             is to quote them.
833              
834             =head2 quote_table_names
835              
836             DEPRECATED - A legacy proxy to L
837              
838             =head2 quote_field_names
839              
840             DEPRECATED - A legacy proxy to L
841              
842             =head2 no_comments
843              
844             Toggles whether to print comments in the output. Accepts a true or false
845             value, returns the current value.
846              
847             =head2 producer
848              
849             The C method is an accessor/mutator, used to retrieve or
850             define what subroutine is called to produce the output. A subroutine
851             defined as a producer will be invoked as a function (I)
852             and passed its container C instance, which it should
853             call the C method on, to get the C
854             generated by the parser. It is expected that the function transform the
855             schema structure to a string. The C instance is also useful
856             for informational purposes; for example, the type of the parser can be
857             retrieved using the C method, and the C and
858             C methods can be called when needed.
859              
860             When defining a producer, one of several things can be passed in: A
861             module name (e.g., C), a module name relative to
862             the C namespace (e.g., C), a module
863             name and function combination (C),
864             or a reference to an anonymous subroutine. If a full module name is
865             passed in (for the purposes of this method, a string containing "::"
866             is considered to be a module name), it is treated as a package, and a
867             function called "produce" will be invoked: C<$modulename::produce>.
868             If $modulename cannot be loaded, the final portion is stripped off and
869             treated as a function. In other words, if there is no file named
870             F, C will attempt
871             to load F and use C as the name of
872             the function, instead of the default C.
873              
874             my $tr = SQL::Translator->new;
875              
876             # This will invoke My::Groovy::Producer::produce($tr, $data)
877             $tr->producer("My::Groovy::Producer");
878              
879             # This will invoke SQL::Translator::Producer::Sybase::produce($tr, $data)
880             $tr->producer("Sybase");
881              
882             # This will invoke My::Groovy::Producer::transmogrify($tr, $data),
883             # assuming that My::Groovy::Producer::transmogrify is not a module
884             # on disk.
885             $tr->producer("My::Groovy::Producer::transmogrify");
886              
887             # This will invoke the referenced subroutine directly, as
888             # $subref->($tr, $data);
889             $tr->producer(\&my_producer);
890              
891             There is also a method named C, which is a string
892             containing the classname to which the above C function
893             belongs. In the case of anonymous subroutines, this method returns
894             the string "CODE".
895              
896             Finally, there is a method named C, which is both an
897             accessor and a mutator. Arbitrary data may be stored in name => value
898             pairs for the producer subroutine to access:
899              
900             sub My::Random::producer {
901             my ($tr, $data) = @_;
902             my $pr_args = $tr->producer_args();
903              
904             # $pr_args is a hashref.
905              
906             Extra data passed to the C method is passed to
907             C:
908              
909             $tr->producer("xSV", delimiter => ',\s*');
910              
911             # In SQL::Translator::Producer::xSV:
912             my $args = $tr->producer_args;
913             my $delimiter = $args->{'delimiter'}; # value is ,\s*
914              
915             =head2 parser
916              
917             The C method defines or retrieves a subroutine that will be
918             called to perform the parsing. The basic idea is the same as that of
919             C (see above), except the default subroutine name is
920             "parse", and will be invoked as C<$module_name::parse($tr, $data)>.
921             Also, the parser subroutine will be passed a string containing the
922             entirety of the data to be parsed.
923              
924             # Invokes SQL::Translator::Parser::MySQL::parse()
925             $tr->parser("MySQL");
926              
927             # Invokes My::Groovy::Parser::parse()
928             $tr->parser("My::Groovy::Parser");
929              
930             # Invoke an anonymous subroutine directly
931             $tr->parser(sub {
932             my $dumper = Data::Dumper->new([ $_[1] ], [ "SQL" ]);
933             $dumper->Purity(1)->Terse(1)->Deepcopy(1);
934             return $dumper->Dump;
935             });
936              
937             There is also C and C, which perform
938             analogously to C and C
939              
940             =head2 filters
941              
942             Set or retrieve the filters to run over the schema during the
943             translation, before the producer creates its output. Filters are sub
944             routines called, in order, with the schema object to filter as the 1st
945             arg and a hash of options (passed as a list) for the rest of the args.
946             They are free to do whatever they want to the schema object, which will be
947             handed to any following filters, then used by the producer.
948              
949             Filters are set as an array, which gives the order they run in.
950             Like parsers and producers, they can be defined by a module name, a
951             module name relative to the SQL::Translator::Filter namespace, a module
952             name and function name together or a reference to an anonymous subroutine.
953             When using a module name a function called C will be invoked in
954             that package to do the work.
955              
956             To pass args to the filter set it as an array ref with the 1st value giving
957             the filter (name or sub) and the rest its args. e.g.
958              
959             $tr->filters(
960             sub {
961             my $schema = shift;
962             # Do stuff to schema here!
963             },
964             DropFKeys,
965             [ "Names", table => 'lc' ],
966             [ "Foo", foo => "bar", hello => "world" ],
967             [ "Filter5" ],
968             );
969              
970             Although you normally set them in the constructor, which calls
971             through to filters. i.e.
972              
973             my $translator = SQL::Translator->new(
974             ...
975             filters => [
976             sub { ... },
977             [ "Names", table => 'lc' ],
978             ],
979             ...
980             );
981              
982             See F for more examples.
983              
984             Multiple set calls to filters are cumulative with new filters added to
985             the end of the current list.
986              
987             Returns the filters as a list of array refs, the 1st value being a
988             reference to the filter sub and the rest its args.
989              
990             =head2 show_warnings
991              
992             Toggles whether to print warnings of name conflicts, identifier
993             mutations, etc. Probably only generated by producers to let the user
994             know when something won't translate very smoothly (e.g., MySQL "enum"
995             fields into Oracle). Accepts a true or false value, returns the
996             current value.
997              
998             =head2 translate
999              
1000             The C method calls the subroutine referenced by the
1001             C data member, then calls any C and finally calls
1002             the C sub routine (these members are described above).
1003             It accepts as arguments a number of things, in key => value format,
1004             including (potentially) a parser and a producer (they are passed
1005             directly to the C and C methods).
1006              
1007             Here is how the parameter list to C is parsed:
1008              
1009             =over
1010              
1011             =item *
1012              
1013             1 argument means it's the data to be parsed; which could be a string
1014             (filename) or a reference to a scalar (a string stored in memory), or a
1015             reference to a hash, which is parsed as being more than one argument
1016             (see next section).
1017              
1018             # Parse the file /path/to/datafile
1019             my $output = $tr->translate("/path/to/datafile");
1020              
1021             # Parse the data contained in the string $data
1022             my $output = $tr->translate(\$data);
1023              
1024             =item *
1025              
1026             More than 1 argument means its a hash of things, and it might be
1027             setting a parser, producer, or datasource (this key is named
1028             "filename" or "file" if it's a file, or "data" for a SCALAR reference.
1029              
1030             # As above, parse /path/to/datafile, but with different producers
1031             for my $prod ("MySQL", "XML", "Sybase") {
1032             print $tr->translate(
1033             producer => $prod,
1034             filename => "/path/to/datafile",
1035             );
1036             }
1037              
1038             # The filename hash key could also be:
1039             datasource => \$data,
1040              
1041             You get the idea.
1042              
1043             =back
1044              
1045             =head2 filename, data
1046              
1047             Using the C method, the filename of the data to be parsed
1048             can be set. This method can be used in conjunction with the C
1049             method, below. If both the C and C methods are
1050             invoked as mutators, the data set in the C method is used.
1051              
1052             $tr->filename("/my/data/files/create.sql");
1053              
1054             or:
1055              
1056             my $create_script = do {
1057             local $/;
1058             open CREATE, "/my/data/files/create.sql" or die $!;
1059             ;
1060             };
1061             $tr->data(\$create_script);
1062              
1063             C takes a string, which is interpreted as a filename.
1064             C takes a reference to a string, which is used as the data to be
1065             parsed. If a filename is set, then that file is opened and read when
1066             the C method is called, as long as the data instance
1067             variable is not set.
1068              
1069             =head2 schema
1070              
1071             Returns the SQL::Translator::Schema object.
1072              
1073             =head2 trace
1074              
1075             Turns on/off the tracing option of Parse::RecDescent.
1076              
1077             =head2 validate
1078              
1079             Whether or not to validate the schema object after parsing and before
1080             producing.
1081              
1082             =head2 version
1083              
1084             Returns the version of the SQL::Translator release.
1085              
1086             =head1 AUTHORS
1087              
1088             See the included AUTHORS file:
1089             L
1090              
1091             =head1 GETTING HELP/SUPPORT
1092              
1093             If you are stuck with a problem or have doubts about a particular
1094             approach do not hesitate to contact us via any of the following
1095             options (the list is sorted by "fastest response time"):
1096              
1097             =over
1098              
1099             =item * IRC: irc.perl.org#sql-translator
1100              
1101             =for html
1102             (click for instant chatroom login)
1103              
1104             =item * Mailing list: L
1105              
1106             =item * RT Bug Tracker: L
1107              
1108             =back
1109              
1110             =head1 HOW TO CONTRIBUTE
1111              
1112             Contributions are always welcome, in all usable forms (we especially
1113             welcome documentation improvements). The delivery methods include git-
1114             or unified-diff formatted patches, GitHub pull requests, or plain bug
1115             reports either via RT or the Mailing list. Contributors are generally
1116             granted access to the official repository after their first several
1117             patches pass successful review. Don't hesitate to
1118             L us with any further questions you may
1119             have.
1120              
1121             This project is maintained in a git repository. The code and related tools are
1122             accessible at the following locations:
1123              
1124             =over
1125              
1126             =item * Official repo: L
1127              
1128             =item * Official gitweb: L
1129              
1130             =item * GitHub mirror: L
1131              
1132             =item * Authorized committers: L
1133              
1134             =item * Travis-CI log: L
1135              
1136             =for html
1137             ↪ Stable branch CI status:
1138              
1139             =back
1140              
1141             =head1 COPYRIGHT
1142              
1143             Copyright 2012 the SQL::Translator authors, as listed in L.
1144              
1145             =head1 LICENSE
1146              
1147             This library is free software and may be distributed under the same terms as
1148             Perl 5 itself.
1149              
1150             =head1 PRAISE
1151              
1152             If you find this module useful, please use
1153             L to rate it.
1154              
1155             =head1 SEE ALSO
1156              
1157             L,
1158             L,
1159             L,
1160             L,
1161             L,
1162             L,
1163             L,
1164             L,
1165             L.