1 package SQL::Translator;
3 # ----------------------------------------------------------------------
4 # Copyright (C) 2002-2009 The SQLFairy Authors
6 # This program is free software; you can redistribute it and/or
7 # modify it under the terms of the GNU General Public License as
8 # published by the Free Software Foundation; version 2.
10 # This program is distributed in the hope that it will be useful, but
11 # WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 # General Public License for more details.
15 # You should have received a copy of the GNU General Public License
16 # along with this program; if not, write to the Free Software
17 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
19 # -------------------------------------------------------------------
22 use vars qw( $VERSION $DEFAULT_SUB $DEBUG $ERROR );
23 use base 'Class::Base';
28 $DEBUG = 0 unless defined $DEBUG;
35 use File::Spec::Functions qw(catfile);
36 use File::Basename qw(dirname);
38 use SQL::Translator::Producer;
39 use SQL::Translator::Schema;
41 # ----------------------------------------------------------------------
42 # The default behavior is to "pass through" values (note that the
43 # SQL::Translator instance is the first value ($_[0]), and the stuff
44 # to be parsed is the second value ($_[1])
45 # ----------------------------------------------------------------------
46 $DEFAULT_SUB = sub { $_[0]->schema } unless defined $DEFAULT_SUB;
48 # ----------------------------------------------------------------------
52 # new takes an optional hash of arguments. These arguments may
53 # include a parser, specified with the keys "parser" or "from",
54 # and a producer, specified with the keys "producer" or "to".
56 # The values that can be passed as the parser or producer are
57 # given directly to the parser or producer methods, respectively.
58 # See the appropriate method description below for details about
59 # what each expects/accepts.
60 # ----------------------------------------------------------------------
62 my ( $self, $config ) = @_;
64 # Set the parser and producer.
66 # If a 'parser' or 'from' parameter is passed in, use that as the
67 # parser; if a 'producer' or 'to' parameter is passed in, use that
68 # as the producer; both default to $DEFAULT_SUB.
70 $self->parser ($config->{'parser'} || $config->{'from'} || $DEFAULT_SUB);
71 $self->producer($config->{'producer'} || $config->{'to'} || $DEFAULT_SUB);
74 # Set up callbacks for formatting of pk,fk,table,package names in producer
75 # MOVED TO PRODUCER ARGS
77 #$self->format_table_name($config->{'format_table_name'});
78 #$self->format_package_name($config->{'format_package_name'});
79 #$self->format_fk_name($config->{'format_fk_name'});
80 #$self->format_pk_name($config->{'format_pk_name'});
83 # Set the parser_args and producer_args
85 for my $pargs ( qw[ parser_args producer_args ] ) {
86 $self->$pargs( $config->{$pargs} ) if defined $config->{ $pargs };
90 # Initialize the filters.
92 if ( $config->{filters} && ref $config->{filters} eq "ARRAY" ) {
93 $self->filters( @{$config->{filters}} )
94 || return $self->error('Error inititializing filters: '.$self->error);
98 # Set the data source, if 'filename' or 'file' is provided.
100 $config->{'filename'} ||= $config->{'file'} || "";
101 $self->filename( $config->{'filename'} ) if $config->{'filename'};
104 # Finally, if there is a 'data' parameter, use that in
105 # preference to filename and file
107 if ( my $data = $config->{'data'} ) {
108 $self->data( $data );
112 # Set various other options.
114 $self->{'debug'} = defined $config->{'debug'} ? $config->{'debug'} : $DEBUG;
116 $self->add_drop_table( $config->{'add_drop_table'} );
118 $self->no_comments( $config->{'no_comments'} );
120 $self->show_warnings( $config->{'show_warnings'} );
122 $self->trace( $config->{'trace'} );
124 $self->validate( $config->{'validate'} );
126 $self->quote_table_names( (defined $config->{'quote_table_names'}
127 ? $config->{'quote_table_names'} : 1) );
128 $self->quote_field_names( (defined $config->{'quote_field_names'}
129 ? $config->{'quote_field_names'} : 1) );
134 # ----------------------------------------------------------------------
135 # add_drop_table([$bool])
136 # ----------------------------------------------------------------------
139 if ( defined (my $arg = shift) ) {
140 $self->{'add_drop_table'} = $arg ? 1 : 0;
142 return $self->{'add_drop_table'} || 0;
145 # ----------------------------------------------------------------------
146 # no_comments([$bool])
147 # ----------------------------------------------------------------------
151 if ( defined $arg ) {
152 $self->{'no_comments'} = $arg ? 1 : 0;
154 return $self->{'no_comments'} || 0;
158 # ----------------------------------------------------------------------
159 # quote_table_names([$bool])
160 # ----------------------------------------------------------------------
161 sub quote_table_names {
163 if ( defined (my $arg = shift) ) {
164 $self->{'quote_table_names'} = $arg ? 1 : 0;
166 return $self->{'quote_table_names'} || 0;
169 # ----------------------------------------------------------------------
170 # quote_field_names([$bool])
171 # ----------------------------------------------------------------------
172 sub quote_field_names {
174 if ( defined (my $arg = shift) ) {
175 $self->{'quote_field_names'} = $arg ? 1 : 0;
177 return $self->{'quote_field_names'} || 0;
180 # ----------------------------------------------------------------------
181 # producer([$producer_spec])
183 # Get or set the producer for the current translator.
184 # ----------------------------------------------------------------------
188 path => "SQL::Translator::Producer",
189 default_sub => "produce",
193 # ----------------------------------------------------------------------
196 # producer_type is an accessor that allows producer subs to get
197 # information about their origin. This is poptentially important;
198 # since all producer subs are called as subroutine references, there is
199 # no way for a producer to find out which package the sub lives in
200 # originally, for example.
201 # ----------------------------------------------------------------------
202 sub producer_type { $_[0]->{'producer_type'} }
204 # ----------------------------------------------------------------------
205 # producer_args([\%args])
207 # Arbitrary name => value pairs of paramters can be passed to a
208 # producer using this method.
210 # If the first argument passed in is undef, then the hash of arguments
211 # is cleared; all subsequent elements are added to the hash of name,
212 # value pairs stored as producer_args.
213 # ----------------------------------------------------------------------
214 sub producer_args { shift->_args("producer", @_); }
216 # ----------------------------------------------------------------------
217 # parser([$parser_spec])
218 # ----------------------------------------------------------------------
222 path => "SQL::Translator::Parser",
223 default_sub => "parse",
227 sub parser_type { $_[0]->{'parser_type'}; }
229 sub parser_args { shift->_args("parser", @_); }
231 # ----------------------------------------------------------------------
233 # $sqlt->filters => [
235 # [ "NormalizeNames", field => "lc", tabel => "ucfirst" ],
238 # "TEXT" => "BIGTEXT",
241 # ----------------------------------------------------------------------
244 my $filters = $self->{filters} ||= [];
245 return @$filters unless @_;
247 # Set. Convert args to list of [\&code,@args]
249 my ($filt,@args) = ref($_) eq "ARRAY" ? @$_ : $_;
250 if ( isa($filt,"CODE") ) {
251 push @$filters, [$filt,@args];
255 $self->debug("Adding $filt filter. Args:".Dumper(\@args)."\n");
256 $filt = _load_sub("$filt\::filter", "SQL::Translator::Filter")
257 || return $self->error(__PACKAGE__->error);
258 push @$filters, [$filt,@args];
264 # ----------------------------------------------------------------------
268 if ( defined $arg ) {
269 $self->{'show_warnings'} = $arg ? 1 : 0;
271 return $self->{'show_warnings'} || 0;
275 # filename - get or set the filename
279 my $filename = shift;
281 my $msg = "Cannot use directory '$filename' as input source";
282 return $self->error($msg);
283 } elsif (ref($filename) eq 'ARRAY') {
284 $self->{'filename'} = $filename;
285 $self->debug("Got array of files: ".join(', ',@$filename)."\n");
286 } elsif (-f _ && -r _) {
287 $self->{'filename'} = $filename;
288 $self->debug("Got filename: '$self->{'filename'}'\n");
290 my $msg = "Cannot use '$filename' as input source: ".
291 "file does not exist or is not readable.";
292 return $self->error($msg);
299 # ----------------------------------------------------------------------
302 # if $self->{'data'} is not set, but $self->{'filename'} is, then
303 # $self->{'filename'} is opened and read, with the results put into
305 # ----------------------------------------------------------------------
309 # Set $self->{'data'} based on what was passed in. We will
310 # accept a number of things; do our best to get it right.
313 if (isa($data, "SCALAR")) {
314 $self->{'data'} = $data;
317 if (isa($data, 'ARRAY')) {
318 $data = join '', @$data;
320 elsif (isa($data, 'GLOB')) {
324 elsif (! ref $data && @_) {
325 $data = join '', $data, @_;
327 $self->{'data'} = \$data;
331 # If we have a filename but no data yet, populate.
332 if (not $self->{'data'} and my $filename = $self->filename) {
333 $self->debug("Opening '$filename' to get contents.\n");
338 my @files = ref($filename) eq 'ARRAY' ? @$filename : ($filename);
340 foreach my $file (@files) {
341 unless (open FH, $file) {
342 return $self->error("Can't read file '$file': $!");
348 return $self->error("Can't close file '$file': $!");
352 $self->{'data'} = \$data;
355 return $self->{'data'};
358 # ----------------------------------------------------------------------
361 # Deletes the existing Schema object so that future calls to translate
362 # don't append to the existing.
365 $self->{'schema'} = undef;
369 # ----------------------------------------------------------------------
372 # Returns the SQL::Translator::Schema object
376 unless ( defined $self->{'schema'} ) {
377 $self->{'schema'} = SQL::Translator::Schema->new(
382 return $self->{'schema'};
385 # ----------------------------------------------------------------------
389 if ( defined $arg ) {
390 $self->{'trace'} = $arg ? 1 : 0;
392 return $self->{'trace'} || 0;
395 # ----------------------------------------------------------------------
396 # translate([source], [\%args])
398 # translate does the actual translation. The main argument is the
399 # source of the data to be translated, which can be a filename, scalar
400 # reference, or glob reference.
402 # Alternatively, translate takes optional arguements, which are passed
403 # to the appropriate places. Most notable of these arguments are
404 # parser and producer, which can be used to set the parser and
405 # producer, respectively. This is the applications last chance to set
408 # translate returns a string.
409 # ----------------------------------------------------------------------
412 my ($args, $parser, $parser_type, $producer, $producer_type);
413 my ($parser_output, $producer_output, @producer_output);
417 # Passed a reference to a hash?
418 if (isa($_[0], 'HASH')) {
420 $self->debug("translate: Got a hashref\n");
424 # Passed a GLOB reference, i.e., filehandle
425 elsif (isa($_[0], 'GLOB')) {
426 $self->debug("translate: Got a GLOB reference\n");
430 # Passed a reference to a string containing the data
431 elsif (isa($_[0], 'SCALAR')) {
432 # passed a ref to a string
433 $self->debug("translate: Got a SCALAR reference (string)\n");
437 # Not a reference; treat it as a filename
438 elsif (! ref $_[0]) {
439 # Not a ref, it's a filename
440 $self->debug("translate: Got a filename\n");
441 $self->filename($_[0]);
444 # Passed something else entirely.
446 # We're not impressed. Take your empty string and leave.
449 # Actually, if data, parser, and producer are set, then we
450 # can continue. Too bad, because I like my comment
452 return "" unless ($self->data &&
458 # You must pass in a hash, or you get nothing.
463 # ----------------------------------------------------------------------
464 # Can specify the data to be transformed using "filename", "file",
465 # "data", or "datasource".
466 # ----------------------------------------------------------------------
467 if (my $filename = ($args->{'filename'} || $args->{'file'})) {
468 $self->filename($filename);
471 if (my $data = ($args->{'data'} || $args->{'datasource'})) {
475 # ----------------------------------------------------------------
477 # ----------------------------------------------------------------
478 my $data = $self->data;
480 # ----------------------------------------------------------------
481 # Local reference to the parser subroutine
482 # ----------------------------------------------------------------
483 if ($parser = ($args->{'parser'} || $args->{'from'})) {
484 $self->parser($parser);
486 $parser = $self->parser;
487 $parser_type = $self->parser_type;
489 # ----------------------------------------------------------------
490 # Local reference to the producer subroutine
491 # ----------------------------------------------------------------
492 if ($producer = ($args->{'producer'} || $args->{'to'})) {
493 $self->producer($producer);
495 $producer = $self->producer;
496 $producer_type = $self->producer_type;
498 # ----------------------------------------------------------------
499 # Execute the parser, the filters and then execute the producer.
500 # Allowances are made for each piece to die, or fail to compile,
501 # since the referenced subroutines could be almost anything. In
502 # the future, each of these might happen in a Safe environment,
503 # depending on how paranoid we want to be.
504 # ----------------------------------------------------------------
507 unless ( defined $self->{'schema'} ) {
508 eval { $parser_output = $parser->($self, $$data) };
509 if ($@ || ! $parser_output) {
510 my $msg = sprintf "translate: Error with parser '%s': %s",
511 $parser_type, ($@) ? $@ : " no results";
512 return $self->error($msg);
515 $self->debug("Schema =\n", Dumper($self->schema), "\n");
517 # Validate the schema if asked to.
518 if ($self->validate) {
519 my $schema = $self->schema;
520 return $self->error('Invalid schema') unless $schema->is_valid;
525 foreach ($self->filters) {
527 my ($code,@args) = @$_;
528 eval { $code->($self->schema, @args) };
529 my $err = $@ || $self->error || 0;
530 return $self->error("Error with filter $filt_num : $err") if $err;
534 # Calling wantarray in the eval no work, wrong scope.
535 my $wantarray = wantarray ? 1 : 0;
538 @producer_output = $producer->($self);
540 $producer_output = $producer->($self);
543 if ($@ || !( $producer_output || @producer_output)) {
544 my $err = $@ || $self->error || "no results";
545 my $msg = "translate: Error with producer '$producer_type': $err";
546 return $self->error($msg);
549 return wantarray ? @producer_output : $producer_output;
552 # ----------------------------------------------------------------------
555 # Hacky sort of method to list all available parsers. This has
558 # - Only finds things in the SQL::Translator::Parser namespace
560 # - Only finds things that are located in the same directory
561 # as SQL::Translator::Parser. Yeck.
563 # This method will fail in several very likely cases:
565 # - Parser modules in different namespaces
567 # - Parser modules in the SQL::Translator::Parser namespace that
568 # have any XS componenets will be installed in
569 # arch_lib/SQL/Translator.
571 # ----------------------------------------------------------------------
573 return shift->_list("parser");
576 # ----------------------------------------------------------------------
579 # See notes for list_parsers(), above; all the problems apply to
580 # list_producers as well.
581 # ----------------------------------------------------------------------
583 return shift->_list("producer");
587 # ======================================================================
589 # ======================================================================
591 # ----------------------------------------------------------------------
592 # _args($type, \%args);
594 # Gets or sets ${type}_args. Called by parser_args and producer_args.
595 # ----------------------------------------------------------------------
599 $type = "${type}_args" unless $type =~ /_args$/;
601 unless (defined $self->{$type} && isa($self->{$type}, 'HASH')) {
602 $self->{$type} = { };
606 # If the first argument is an explicit undef (remember, we
607 # don't get here unless there is stuff in @_), then we clear
608 # out the producer_args hash.
609 if (! defined $_[0]) {
611 %{$self->{$type}} = ();
614 my $args = isa($_[0], 'HASH') ? shift : { @_ };
615 %{$self->{$type}} = (%{$self->{$type}}, %$args);
621 # ----------------------------------------------------------------------
622 # Does the get/set work for parser and producer. e.g.
623 # return $self->_tool({
624 # name => 'producer',
625 # path => "SQL::Translator::Producer",
626 # default_sub => "produce",
628 # ----------------------------------------------------------------------
630 my ($self,$args) = (shift, shift);
631 my $name = $args->{name};
632 return $self->{$name} unless @_; # get accessor
634 my $path = $args->{path};
635 my $default_sub = $args->{default_sub};
638 # passed an anonymous subroutine reference
639 if (isa($tool, 'CODE')) {
640 $self->{$name} = $tool;
641 $self->{"$name\_type"} = "CODE";
642 $self->debug("Got $name: code ref\n");
645 # Module name was passed directly
646 # We try to load the name; if it doesn't load, there's a
647 # possibility that it has a function name attached to it,
648 # so we give it a go.
650 $tool =~ s/-/::/g if $tool !~ /::/;
652 ($code,$sub) = _load_sub("$tool\::$default_sub", $path);
654 if ( __PACKAGE__->error =~ m/Can't find module/ ) {
655 # Mod not found so try sub
656 ($code,$sub) = _load_sub("$tool", $path) unless $code;
657 die "Can't load $name subroutine '$tool' : ".__PACKAGE__->error
661 die "Can't load $name '$tool' : ".__PACKAGE__->error;
665 # get code reference and assign
666 my (undef,$module,undef) = $sub =~ m/((.*)::)?(\w+)$/;
667 $self->{$name} = $code;
668 $self->{"$name\_type"} = $sub eq "CODE" ? "CODE" : $module;
669 $self->debug("Got $name: $sub\n");
672 # At this point, $self->{$name} contains a subroutine
673 # reference that is ready to run
675 # Anything left? If so, it's args
676 my $meth = "$name\_args";
677 $self->$meth(@_) if (@_);
679 return $self->{$name};
682 # ----------------------------------------------------------------------
684 # ----------------------------------------------------------------------
687 my $type = shift || return ();
688 my $uctype = ucfirst lc $type;
691 # First find all the directories where SQL::Translator
692 # parsers or producers (the "type") appear to live.
694 load("SQL::Translator::$uctype") or return ();
695 my $path = catfile "SQL", "Translator", $uctype;
698 my $dir = catfile $_, $path;
699 $self->debug("_list_${type}s searching $dir\n");
705 # Now use File::File::find to look recursively in those
706 # directories for all the *.pm files, then present them
707 # with the slashes turned into dashes.
712 if ( -f && m/\.pm$/ ) {
715 my $cur_dir = $File::Find::dir;
716 my $base_dir = quotemeta catfile 'SQL', 'Translator', $uctype;
719 # See if the current directory is below the base directory.
721 if ( $cur_dir =~ m/$base_dir(.*)/ ) {
723 $cur_dir =~ s!^/!!; # kill leading slash
724 $cur_dir =~ s!/!-!g; # turn other slashes into dashes
730 $found{ join '-', map { $_ || () } $cur_dir, $mod } = 1;
736 return sort { lc $a cmp lc $b } keys %found;
739 # ----------------------------------------------------------------------
740 # load(MODULE [,PATH[,PATH]...])
742 # Loads a Perl module. Short circuits if a module is already loaded.
744 # MODULE - is the name of the module to load.
746 # PATH - optional list of 'package paths' to look for the module in. e.g
747 # If you called load('Super::Foo' => 'My', 'Other') it will
748 # try to load the mod Super::Foo then My::Super::Foo then Other::Super::Foo.
750 # Returns package name of the module actually loaded or false and sets error.
752 # Note, you can't load a name from the root namespace (ie one without '::' in
753 # it), therefore a single word name without a path fails.
754 # ----------------------------------------------------------------------
758 push @path, "" if $name =~ /::/; # Empty path to check name on its own first
759 push @path, @_ if @_;
762 my $module = $_ ? "$_\::$name" : $name;
763 my $file = $module; $file =~ s[::][/]g; $file .= ".pm";
764 __PACKAGE__->debug("Loading $name as $file\n");
765 return $module if $INC{$file}; # Already loaded
767 eval { require $file };
768 next if $@ =~ /Can't locate $file in \@INC/;
769 eval { $module->import() } unless $@;
770 return __PACKAGE__->error("Error loading $name as $module : $@")
771 if $@ && $@ !~ /"SQL::Translator::Producer" is not exported/;
773 return $module; # Module loaded ok
776 return __PACKAGE__->error("Can't find module $name. Path:".join(",",@path));
779 # ----------------------------------------------------------------------
780 # Load the sub name given (including package), optionally using a base package
781 # path. Returns code ref and name of sub loaded, including its package.
782 # (\&code, $sub) = load_sub( 'MySQL::produce', "SQL::Translator::Producer" );
783 # (\&code, $sub) = load_sub( 'MySQL::produce', @path );
784 # ----------------------------------------------------------------------
786 my ($tool, @path) = @_;
788 my (undef,$module,$func_name) = $tool =~ m/((.*)::)?(\w+)$/;
789 if ( my $module = load($module => @path) ) {
790 my $sub = "$module\::$func_name";
791 return wantarray ? ( \&{ $sub }, $sub ) : \&$sub;
796 # ----------------------------------------------------------------------
797 sub format_table_name {
798 return shift->_format_name('_format_table_name', @_);
801 # ----------------------------------------------------------------------
802 sub format_package_name {
803 return shift->_format_name('_format_package_name', @_);
806 # ----------------------------------------------------------------------
808 return shift->_format_name('_format_fk_name', @_);
811 # ----------------------------------------------------------------------
813 return shift->_format_name('_format_pk_name', @_);
816 # ----------------------------------------------------------------------
817 # The other format_*_name methods rely on this one. It optionally
818 # accepts a subroutine ref as the first argument (or uses an identity
819 # sub if one isn't provided or it doesn't already exist), and applies
820 # it to the rest of the arguments (if any).
821 # ----------------------------------------------------------------------
827 if (ref($args[0]) eq 'CODE') {
828 $self->{$field} = shift @args;
830 elsif (! exists $self->{$field}) {
831 $self->{$field} = sub { return shift };
834 return @args ? $self->{$field}->(@args) : $self->{$field};
837 # ----------------------------------------------------------------------
840 # Calls UNIVERSAL::isa($ref, $type). I think UNIVERSAL::isa is ugly,
841 # but I like function overhead.
842 # ----------------------------------------------------------------------
844 my ($ref, $type) = @_;
845 return UNIVERSAL::isa($ref, $type);
848 # ----------------------------------------------------------------------
851 # Returns the $VERSION of the main SQL::Translator package.
852 # ----------------------------------------------------------------------
858 # ----------------------------------------------------------------------
860 my ( $self, $arg ) = @_;
861 if ( defined $arg ) {
862 $self->{'validate'} = $arg ? 1 : 0;
864 return $self->{'validate'} || 0;
869 # ----------------------------------------------------------------------
870 # Who killed the pork chops?
871 # What price bananas?
874 # ----------------------------------------------------------------------
880 SQL::Translator - manipulate structured data definitions (SQL and more)
886 my $translator = SQL::Translator->new(
889 # Print Parse::RecDescent trace
891 # Don't include comments in output
893 # Print name mutations, conflicts
895 # Add "drop table" statements
897 # to quote or not to quote, thats the question
898 quote_table_names => 1,
899 quote_field_names => 1,
900 # Validate schema object
902 # Make all table names CAPS in producers which support this option
903 format_table_name => sub {my $tablename = shift; return uc($tablename)},
904 # Null-op formatting, only here for documentation's sake
905 format_package_name => sub {return shift},
906 format_fk_name => sub {return shift},
907 format_pk_name => sub {return shift},
910 my $output = $translator->translate(
913 # Or an arrayref of filenames, i.e. [ $file1, $file2, $file3 ]
915 ) or die $translator->error;
921 This documentation covers the API for SQL::Translator. For a more general
922 discussion of how to use the modules and scripts, please see
923 L<SQL::Translator::Manual>.
925 SQL::Translator is a group of Perl modules that converts
926 vendor-specific SQL table definitions into other formats, such as
927 other vendor-specific SQL, ER diagrams, documentation (POD and HTML),
928 XML, and Class::DBI classes. The main focus of SQL::Translator is
929 SQL, but parsers exist for other structured data formats, including
930 Excel spreadsheets and arbitrarily delimited text files. Through the
931 separation of the code into parsers and producers with an object model
932 in between, it's possible to combine any parser with any producer, to
933 plug in custom parsers or producers, or to manipulate the parsed data
934 via the built-in object model. Presently only the definition parts of
935 SQL are handled (CREATE, ALTER), not the manipulation of data (INSERT,
940 The constructor is called C<new>, and accepts a optional hash of options.
1003 All options are, well, optional; these attributes can be set via
1004 instance methods. Internally, they are; no (non-syntactical)
1005 advantage is gained by passing options to the constructor.
1009 =head2 add_drop_table
1011 Toggles whether or not to add "DROP TABLE" statements just before the
1014 =head2 quote_table_names
1016 Toggles whether or not to quote table names with " in DROP and CREATE
1017 statements. The default (true) is to quote them.
1019 =head2 quote_field_names
1021 Toggles whether or not to quote field names with " in most
1022 statements. The default (true), is to quote them.
1026 Toggles whether to print comments in the output. Accepts a true or false
1027 value, returns the current value.
1031 The C<producer> method is an accessor/mutator, used to retrieve or
1032 define what subroutine is called to produce the output. A subroutine
1033 defined as a producer will be invoked as a function (I<not a method>)
1034 and passed its container C<SQL::Translator> instance, which it should
1035 call the C<schema> method on, to get the C<SQL::Translator::Schema>
1036 generated by the parser. It is expected that the function transform the
1037 schema structure to a string. The C<SQL::Translator> instance is also useful
1038 for informational purposes; for example, the type of the parser can be
1039 retrieved using the C<parser_type> method, and the C<error> and
1040 C<debug> methods can be called when needed.
1042 When defining a producer, one of several things can be passed in: A
1043 module name (e.g., C<My::Groovy::Producer>), a module name relative to
1044 the C<SQL::Translator::Producer> namespace (e.g., C<MySQL>), a module
1045 name and function combination (C<My::Groovy::Producer::transmogrify>),
1046 or a reference to an anonymous subroutine. If a full module name is
1047 passed in (for the purposes of this method, a string containing "::"
1048 is considered to be a module name), it is treated as a package, and a
1049 function called "produce" will be invoked: C<$modulename::produce>.
1050 If $modulename cannot be loaded, the final portion is stripped off and
1051 treated as a function. In other words, if there is no file named
1052 F<My/Groovy/Producer/transmogrify.pm>, C<SQL::Translator> will attempt
1053 to load F<My/Groovy/Producer.pm> and use C<transmogrify> as the name of
1054 the function, instead of the default C<produce>.
1056 my $tr = SQL::Translator->new;
1058 # This will invoke My::Groovy::Producer::produce($tr, $data)
1059 $tr->producer("My::Groovy::Producer");
1061 # This will invoke SQL::Translator::Producer::Sybase::produce($tr, $data)
1062 $tr->producer("Sybase");
1064 # This will invoke My::Groovy::Producer::transmogrify($tr, $data),
1065 # assuming that My::Groovy::Producer::transmogrify is not a module
1067 $tr->producer("My::Groovy::Producer::transmogrify");
1069 # This will invoke the referenced subroutine directly, as
1070 # $subref->($tr, $data);
1071 $tr->producer(\&my_producer);
1073 There is also a method named C<producer_type>, which is a string
1074 containing the classname to which the above C<produce> function
1075 belongs. In the case of anonymous subroutines, this method returns
1078 Finally, there is a method named C<producer_args>, which is both an
1079 accessor and a mutator. Arbitrary data may be stored in name => value
1080 pairs for the producer subroutine to access:
1082 sub My::Random::producer {
1083 my ($tr, $data) = @_;
1084 my $pr_args = $tr->producer_args();
1086 # $pr_args is a hashref.
1088 Extra data passed to the C<producer> method is passed to
1091 $tr->producer("xSV", delimiter => ',\s*');
1093 # In SQL::Translator::Producer::xSV:
1094 my $args = $tr->producer_args;
1095 my $delimiter = $args->{'delimiter'}; # value is ,\s*
1099 The C<parser> method defines or retrieves a subroutine that will be
1100 called to perform the parsing. The basic idea is the same as that of
1101 C<producer> (see above), except the default subroutine name is
1102 "parse", and will be invoked as C<$module_name::parse($tr, $data)>.
1103 Also, the parser subroutine will be passed a string containing the
1104 entirety of the data to be parsed.
1106 # Invokes SQL::Translator::Parser::MySQL::parse()
1107 $tr->parser("MySQL");
1109 # Invokes My::Groovy::Parser::parse()
1110 $tr->parser("My::Groovy::Parser");
1112 # Invoke an anonymous subroutine directly
1114 my $dumper = Data::Dumper->new([ $_[1] ], [ "SQL" ]);
1115 $dumper->Purity(1)->Terse(1)->Deepcopy(1);
1116 return $dumper->Dump;
1119 There is also C<parser_type> and C<parser_args>, which perform
1120 analogously to C<producer_type> and C<producer_args>
1124 Set or retreive the filters to run over the schema during the
1125 translation, before the producer creates its output. Filters are sub
1126 routines called, in order, with the schema object to filter as the 1st
1127 arg and a hash of options (passed as a list) for the rest of the args.
1128 They are free to do whatever they want to the schema object, which will be
1129 handed to any following filters, then used by the producer.
1131 Filters are set as an array, which gives the order they run in.
1132 Like parsers and producers, they can be defined by a module name, a
1133 module name relative to the SQL::Translator::Filter namespace, a module
1134 name and function name together or a reference to an anonymous subroutine.
1135 When using a module name a function called C<filter> will be invoked in
1136 that package to do the work.
1138 To pass args to the filter set it as an array ref with the 1st value giving
1139 the filter (name or sub) and the rest its args. e.g.
1144 # Do stuff to schema here!
1147 [ "Names", table => 'lc' ],
1148 [ "Foo", foo => "bar", hello => "world" ],
1152 Although you normally set them in the constructor, which calls
1153 through to filters. i.e.
1155 my $translator = SQL::Translator->new(
1159 [ "Names", table => 'lc' ],
1164 See F<t/36-filters.t> for more examples.
1166 Multiple set calls to filters are cumulative with new filters added to
1167 the end of the current list.
1169 Returns the filters as a list of array refs, the 1st value being a
1170 reference to the filter sub and the rest its args.
1172 =head2 show_warnings
1174 Toggles whether to print warnings of name conflicts, identifier
1175 mutations, etc. Probably only generated by producers to let the user
1176 know when something won't translate very smoothly (e.g., MySQL "enum"
1177 fields into Oracle). Accepts a true or false value, returns the
1182 The C<translate> method calls the subroutine referenced by the
1183 C<parser> data member, then calls any C<filters> and finally calls
1184 the C<producer> sub routine (these members are described above).
1185 It accepts as arguments a number of things, in key => value format,
1186 including (potentially) a parser and a producer (they are passed
1187 directly to the C<parser> and C<producer> methods).
1189 Here is how the parameter list to C<translate> is parsed:
1195 1 argument means it's the data to be parsed; which could be a string
1196 (filename) or a reference to a scalar (a string stored in memory), or a
1197 reference to a hash, which is parsed as being more than one argument
1200 # Parse the file /path/to/datafile
1201 my $output = $tr->translate("/path/to/datafile");
1203 # Parse the data contained in the string $data
1204 my $output = $tr->translate(\$data);
1208 More than 1 argument means its a hash of things, and it might be
1209 setting a parser, producer, or datasource (this key is named
1210 "filename" or "file" if it's a file, or "data" for a SCALAR reference.
1212 # As above, parse /path/to/datafile, but with different producers
1213 for my $prod ("MySQL", "XML", "Sybase") {
1214 print $tr->translate(
1216 filename => "/path/to/datafile",
1220 # The filename hash key could also be:
1221 datasource => \$data,
1227 =head2 filename, data
1229 Using the C<filename> method, the filename of the data to be parsed
1230 can be set. This method can be used in conjunction with the C<data>
1231 method, below. If both the C<filename> and C<data> methods are
1232 invoked as mutators, the data set in the C<data> method is used.
1234 $tr->filename("/my/data/files/create.sql");
1238 my $create_script = do {
1240 open CREATE, "/my/data/files/create.sql" or die $!;
1243 $tr->data(\$create_script);
1245 C<filename> takes a string, which is interpreted as a filename.
1246 C<data> takes a reference to a string, which is used as the data to be
1247 parsed. If a filename is set, then that file is opened and read when
1248 the C<translate> method is called, as long as the data instance
1249 variable is not set.
1253 Returns the SQL::Translator::Schema object.
1257 Turns on/off the tracing option of Parse::RecDescent.
1261 Whether or not to validate the schema object after parsing and before
1266 Returns the version of the SQL::Translator release.
1270 See the included AUTHORS file:
1271 L<http://search.cpan.org/dist/SQL-Translator/AUTHORS>
1273 If you would like to contribute to the project, you can send patches
1274 to the developers mailing list:
1276 sqlfairy-developers@lists.sourceforge.net
1278 Or send us a message (with your Sourceforge username) asking to be
1279 added to the project and what you'd like to contribute.
1284 This program is free software; you can redistribute it and/or modify
1285 it under the terms of the GNU General Public License as published by
1286 the Free Software Foundation; version 2.
1288 This program is distributed in the hope that it will be useful, but
1289 WITHOUT ANY WARRANTY; without even the implied warranty of
1290 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
1291 General Public License for more details.
1293 You should have received a copy of the GNU General Public License
1294 along with this program; if not, write to the Free Software
1295 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
1300 Please use L<http://rt.cpan.org/> for reporting bugs.
1304 If you find this module useful, please use
1305 L<http://cpanratings.perl.org/rate/?distribution=SQL-Translator> to rate it.
1310 L<SQL::Translator::Parser>,
1311 L<SQL::Translator::Producer>,
1312 L<Parse::RecDescent>,
1315 L<Text::RecordParser>,