Fix typo, no_comments arg wasnt getting passed. Thanks Penguin!
[dbsrgits/SQL-Translator.git] / lib / SQL / Translator / Producer / SQLite.pm
index e2013c0..b2bc63a 100644 (file)
@@ -1,11 +1,9 @@
 package SQL::Translator::Producer::SQLite;
 
 # -------------------------------------------------------------------
-# $Id: SQLite.pm,v 1.1 2003-03-04 21:24:13 kycl4rk Exp $
+# $Id: SQLite.pm,v 1.15 2006-08-26 11:35:31 schiffbruechige Exp $
 # -------------------------------------------------------------------
-# Copyright (C) 2003 Ken Y. Clark <kclark@cpan.org>,
-#                    darren chamberlain <darren@cpan.org>,
-#                    Chris Mungall <cjm@fruitfly.org>
+# Copyright (C) 2002-4 SQLFairy Authors
 #
 # This program is free software; you can redistribute it and/or
 # modify it under the terms of the GNU General Public License as
@@ -22,152 +20,62 @@ package SQL::Translator::Producer::SQLite;
 # 02111-1307  USA
 # -------------------------------------------------------------------
 
-use strict;
-use Data::Dumper;
+=head1 NAME
 
-use vars qw[ $VERSION $DEBUG $WARN ];
-$VERSION = sprintf "%d.%02d", q$Revision: 1.1 $ =~ /(\d+)\.(\d+)/;
+SQL::Translator::Producer::SQLite - SQLite producer for SQL::Translator
 
-my %used_identifiers = ();
-my $max_id_length    = 30;
-my %global_names;
-my %truncated;
+=head1 SYNOPSIS
 
-sub import {
-    warn "loading " . __PACKAGE__ . "...\n";
-}
+  use SQL::Translator;
 
-sub produce {
-    my ($translator, $data) = @_;
-    $DEBUG                  = $translator->debug;
-    $WARN                   = $translator->show_warnings;
-    my $no_comments         = $translator->no_comments;
-    my $add_drop_table      = $translator->add_drop_table;
-
-    debug("Beginning production\n");
-
-    my $create; 
-    unless ( $no_comments ) {
-        $create .= sprintf "--\n-- Created by %s\n-- Created on %s\n--\n\n",
-            __PACKAGE__, scalar localtime;
-    }
-
-    for my $table ( keys %{ $data } ) {
-        debug("Looking at table '$table'\n");
-        my $table_data = $data->{$table};
-        my @fields = sort { 
-            $table_data->{'fields'}->{$a}->{'order'} 
-            <=>
-            $table_data->{'fields'}->{$b}->{'order'}
-        } keys %{$table_data->{'fields'}};
-
-        #
-        # Header.  Should this look like what mysqldump produces?
-        #
-        $create .= "--\n-- Table: $table\n--\n" unless $no_comments;
-        $create .= qq[DROP TABLE $table;\n] if $add_drop_table;
-        $create .= "CREATE TABLE $table (";
-
-        #
-        # Fields
-        #
-        for (my $i = 0; $i <= $#fields; $i++) {
-            my $field = $fields[$i];
-            debug("Looking at field '$field'\n");
-            my $field_data = $table_data->{'fields'}->{$field};
-            my @fdata = ("", $field);
-            $create .= "\n";
-
-            # data type and size
-            my $data_type = lc $field_data->{'data_type'};
-            my $list      = $field_data->{'list'} || [];
-            my $commalist = join ",", @$list;
-            my $size;
-
-            if ( $data_type eq 'set' ) {
-                $data_type = 'varchar';
-                $size      = length $commalist;
-            }
-            else {
-                $size = join( ', ', @{ $field_data->{'size'} || [] } );
-            }
-
-            push @fdata, sprintf "%s%s", $data_type, ($size) ? "($size)" : '';
-
-            # MySQL qualifiers
-#            for my $qual ( qw[ binary unsigned zerofill ] ) {
-#                push @fdata, $qual 
-#                    if $field_data->{ $qual } ||
-#                       $field_data->{ uc $qual };
-#            }
+  my $t = SQL::Translator->new( parser => '...', producer => 'SQLite' );
+  $t->translate;
 
-            # Null?
-            push @fdata, "NOT NULL" unless $field_data->{'null'};
+=head1 DESCRIPTION
 
-            # Default?  XXX Need better quoting!
-            my $default = $field_data->{'default'};
-            if ( defined $default ) {
-                if ( uc $default eq 'NULL') {
-                    push @fdata, "DEFAULT NULL";
-                } else {
-                    push @fdata, "DEFAULT '$default'";
-                }
-            }
+This module will produce text output of the schema suitable for SQLite.
 
-            # auto_increment?
-#            push @fdata, "auto_increment" if $field_data->{'is_auto_inc'};
-
-            # primary key?
-            # This is taken care of in the indices, could be duplicated here
-            # push @fdata, "PRIMARY KEY" if $field_data->{'is_primary_key'};
+=cut
 
+use strict;
+use Data::Dumper;
+use SQL::Translator::Schema::Constants;
+use SQL::Translator::Utils qw(debug header_comment);
 
-            $create .= (join " ", '', @fdata);
-            $create .= "," unless ($i == $#fields);
-        }
-        #
-        # Indices
-        #
-        my @index_creates;
-        my $idx_name_default;
-        for my $index ( @{ $table_data->{'indices'} || [] } ) {
-            my ($name, $type, $fields) = @{ $index }{ qw[ name type fields ] };
-            $name ||= '';
-            my $index_type = 
-                $type eq 'primary_key' ? 'PRIMARY KEY' :
-                $type eq 'unique'      ? 'UNIQUE INDEX'  : 'INDEX';
-            if ( $type eq 'primary_key' ) {
-                $create .= join(",\n", '', 
-                    "  $index_type $name (" . join( ', ', @$fields ) . ')'
-                );
-            }
-            else {
-                $name = mk_name( 
-                    $table, $name || ++$idx_name_default
-                );
-                push @index_creates, 
-                    "CREATE $index_type $name on $table ".
-                    '(' . join( ', ', @$fields ) . ')';
-            }
-        }
+use vars qw[ $VERSION $DEBUG $WARN ];
 
-        $create .= "\n);\n";
+$VERSION = sprintf "%d.%02d", q$Revision: 1.15 $ =~ /(\d+)\.(\d+)/;
+$DEBUG = 0 unless defined $DEBUG;
+$WARN = 0 unless defined $WARN;
 
-        for my $index_create ( @index_creates ) {
-            $create .= "$index_create;\n";
-        }
+my %used_identifiers = ();
+my $max_id_length    = 30;
+my %global_names;
+my %truncated;
 
-        $create .= "\n";
+sub produce {
+    my $translator     = shift;
+    local $DEBUG       = $translator->debug;
+    local $WARN        = $translator->show_warnings;
+    my $no_comments    = $translator->no_comments;
+    my $add_drop_table = $translator->add_drop_table;
+    my $schema         = $translator->schema;
+
+    debug("PKG: Beginning production\n");
+
+    my $create = '';
+    $create .= header_comment unless ($no_comments);
+    $create .= "BEGIN TRANSACTION;\n\n";
+
+    my @table_defs = ();
+    for my $table ( $schema->get_tables ) {
+        push @table_defs, create_table($table, { no_comments => $no_comments,
+                                                 add_drop_table => $add_drop_table,});
     }
 
-    return $create;
-}
+#    $create .= "COMMIT;\n";
 
-# -------------------------------------------------------------------
-sub debug {
-    if ($DEBUG) {
-        map { warn "[" . __PACKAGE__ . "] $_" } @_;
-    }
+    return wantarray ? ($create, @table_defs, "COMMIT;\n") : join("\n", ($create, @table_defs, "COMMIT;\n"));
 }
 
 # -------------------------------------------------------------------
@@ -205,13 +113,207 @@ sub mk_name {
     return $name;
 }
 
+sub create_table
+{
+    my ($table, $options) = @_;
+
+    my $table_name = $table->name;
+    my $no_comments = $options->{no_comments};
+    my $add_drop_table = $options->{add_drop_table};
+
+    debug("PKG: Looking at table '$table_name'\n");
+
+    my ( @index_defs, @constraint_defs, @trigger_defs );
+    my @fields = $table->get_fields or die "No fields in $table_name";
+
+    #
+    # Header.
+    #
+    my $create = '';
+    $create .= "--\n-- Table: $table_name\n--\n" unless $no_comments;
+    $create .= qq[DROP TABLE $table_name;\n] if $add_drop_table;
+    $create .= "CREATE TABLE $table_name (\n";
+
+    #
+    # Comments
+    #
+    if ( $table->comments and !$no_comments ){
+        $create .= "-- Comments: \n-- ";
+        $create .= join "\n-- ",  $table->comments;
+        $create .= "\n--\n\n";
+    }
+
+    #
+    # How many fields in PK?
+    #
+    my $pk        = $table->primary_key;
+    my @pk_fields = $pk ? $pk->fields : ();
+
+    #
+    # Fields
+    #
+    my ( @field_defs, $pk_set );
+    for my $field ( @fields ) {
+        push @field_defs, create_field($field);
+    }
+
+    if ( 
+         scalar @pk_fields > 1 
+         || 
+         ( @pk_fields && !grep /INTEGER PRIMARY KEY/, @field_defs ) 
+         ) {
+        push @field_defs, 'PRIMARY KEY (' . join(', ', @pk_fields ) . ')';
+    }
+
+    #
+    # Indices
+    #
+    my $idx_name_default = 'A';
+    for my $index ( $table->get_indices ) {
+        push @index_defs, create_index($index);
+    }
+
+    #
+    # Constraints
+    #
+    my $c_name_default = 'A';
+    for my $c ( $table->get_constraints ) {
+        next unless $c->type eq UNIQUE; 
+        push @constraint_defs, create_constraint($c);
+    }
+
+    $create .= join(",\n", map { "  $_" } @field_defs ) . "\n);\n";
+
+    $create .= "\n";
+
+    for my $def ( @index_defs, @constraint_defs, @trigger_defs ) {
+        $create .= "$def\n";
+    }
+    return $create;
+}
+
+sub create_field
+{
+    my ($field, $options) = @_;
+
+    my $field_name = $field->name;
+    debug("PKG: Looking at field '$field_name'\n");
+    my $field_comments = $field->comments 
+        ? "-- " . $field->comments . "\n  " 
+        : '';
+
+    my $field_def = $field_comments.$field_name;
+
+    # data type and size
+    my $size      = $field->size;
+    my $data_type = $field->data_type;
+    $data_type    = 'varchar' if lc $data_type eq 'set';
+    $data_type  = 'blob' if lc $data_type eq 'bytea';
+
+    if ( lc $data_type =~ /(text|blob)/i ) {
+        $size = undef;
+    }
+
+#             if ( $data_type =~ /timestamp/i ) {
+#                 push @trigger_defs, 
+#                     "CREATE TRIGGER ts_${table_name} ".
+#                     "after insert on $table_name\n".
+#                     "begin\n".
+#                     "  update $table_name set $field_name=timestamp() ".
+#                        "where id=new.id;\n".
+#                     "end;\n"
+#                 ;
+#
+#            }
+
+    #
+    # SQLite is generally typeless, but newer versions will
+    # make a field autoincrement if it is declared as (and
+    # *only* as) INTEGER PRIMARY KEY
+    #
+    my $pk        = $field->table->primary_key;
+    my @pk_fields = $pk ? $pk->fields : ();
+
+    if ( 
+         $field->is_primary_key && 
+         scalar @pk_fields == 1 &&
+         (
+          $data_type =~ /int(eger)?$/i
+          ||
+          ( $data_type =~ /^number?$/i && $size !~ /,/ )
+          )
+         ) {
+        $data_type = 'INTEGER PRIMARY KEY';
+        $size      = undef;
+#        $pk_set    = 1;
+    }
+
+    $field_def .= sprintf " %s%s", $data_type, 
+    ( !$field->is_auto_increment && $size ) ? "($size)" : '';
+
+    # Null?
+    $field_def .= ' NOT NULL' unless $field->is_nullable;
+
+    # Default?  XXX Need better quoting!
+    my $default = $field->default_value;
+    if ( defined $default ) {
+        if ( uc $default eq 'NULL') {
+            $field_def .= ' DEFAULT NULL';
+        } elsif ( $default eq 'now()' ||
+                  $default eq 'CURRENT_TIMESTAMP' ) {
+            $field_def .= ' DEFAULT CURRENT_TIMESTAMP';
+        } elsif ( $default =~ /val\(/ ) {
+            next;
+        } else {
+            $field_def .= " DEFAULT '$default'";
+        }
+    }
+
+    return $field_def;
+
+}
+
+sub create_index
+{
+    my ($index, $options) = @_;
+
+    my $name   = $index->name;
+    $name      = mk_name($index->table->name, $name); #  || ++$idx_name_default);
+
+    # strip any field size qualifiers as SQLite doesn't like these
+    my @fields = map { s/\(\d+\)$//; $_ } $index->fields;
+    my $index_def =  
+    "CREATE INDEX $name on " . $index->table->name .
+        ' (' . join( ', ', @fields ) . ');';
+
+    return $index_def;
+}
+
+sub create_constraint
+{
+    my ($c, $options) = @_;
+
+    my $name   = $c->name;
+    $name      = mk_name($c->table->name, $name); # || ++$idx_name_default);
+    my @fields = $c->fields;
+
+    my $c_def =  
+    "CREATE UNIQUE INDEX $name on " . $c->table->name .
+        ' (' . join( ', ', @fields ) . ');';
+
+    return $c_def;
+}
+
 1;
-__END__
 
-=head1 NAME
+=pod
 
-SQL::Translator::Producer::SQLite - SQLite-specific producer for SQL::Translator
+=head1 SEE ALSO
+
+SQL::Translator, http://www.sqlite.org/.
 
 =head1 AUTHOR
 
-Ken Y. Clark E<lt>kclark@cpan.orgE<gt>
+Ken Y. Clark E<lt>kclark@cpan.orgE<gt>.
+
+=cut