Awesome non-quoted numeric default patch by Stephen Clouse
[dbsrgits/SQL-Translator.git] / lib / SQL / Translator / Producer / SQLite.pm
index 377dab4..2e7aa6a 100644 (file)
@@ -1,9 +1,7 @@
 package SQL::Translator::Producer::SQLite;
 
 # -------------------------------------------------------------------
-# $Id$
-# -------------------------------------------------------------------
-# Copyright (C) 2002-4 SQLFairy Authors
+# Copyright (C) 2002-2009 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
@@ -38,20 +36,19 @@ This module will produce text output of the schema suitable for SQLite.
 =cut
 
 use strict;
+use warnings;
 use Data::Dumper;
 use SQL::Translator::Schema::Constants;
-use SQL::Translator::Utils qw(debug header_comment);
+use SQL::Translator::Utils qw(debug header_comment parse_dbms_version);
 
 use vars qw[ $VERSION $DEBUG $WARN ];
 
-$VERSION = sprintf "%d.%02d", q$Revision$ =~ /(\d+)\.(\d+)/;
+$VERSION = '1.59';
 $DEBUG = 0 unless defined $DEBUG;
 $WARN = 0 unless defined $WARN;
 
-my %used_identifiers = ();
-my $max_id_length    = 30;
+our $max_id_length    = 30;
 my %global_names;
-my %truncated;
 
 sub produce {
     my $translator     = shift;
@@ -61,13 +58,21 @@ sub produce {
     my $add_drop_table = $translator->add_drop_table;
     my $schema         = $translator->schema;
     my $producer_args  = $translator->producer_args;
-    my $sqlite_version  = $producer_args->{sqlite_version} || 0;
+    my $sqlite_version = parse_dbms_version(
+        $producer_args->{sqlite_version}, 'perl'
+    );
+    my $no_txn         = $producer_args->{no_transaction};
 
     debug("PKG: Beginning production\n");
 
+    %global_names = ();   #reset
+
+
+    my $head = (header_comment() . "\n") unless $no_comments;
+
     my @create = ();
-    push @create, header_comment unless ($no_comments);
-    push @create, 'BEGIN TRANSACTION';
+
+    push @create, "BEGIN TRANSACTION" unless $no_txn;
 
     for my $table ( $schema->get_tables ) {
         push @create, create_table($table, { no_comments => $no_comments,
@@ -82,27 +87,29 @@ sub produce {
       });
     }
 
-    return wantarray ? (@create, "COMMIT") : join(";\n\n", (@create, "COMMIT;\n"));
+    for my $trigger ( $schema->get_triggers ) {
+      push @create, create_trigger($trigger, {
+        add_drop_trigger => $add_drop_table,
+        no_comments   => $no_comments,
+      });
+    }
+
+    push @create, "COMMIT" unless $no_txn;
+
+    if (wantarray) {
+      return ($head||(), @create);
+    } else {
+      return join ('',
+        $head||(),
+        join(";\n\n", @create ),
+        ";\n",
+      );
+    }
 }
 
 # -------------------------------------------------------------------
 sub mk_name {
-    my ($basename, $type, $scope, $critical) = @_;
-    my $basename_orig = $basename;
-    my $max_name      = $type 
-                        ? $max_id_length - (length($type) + 1) 
-                        : $max_id_length;
-    $basename         = substr( $basename, 0, $max_name ) 
-                        if length( $basename ) > $max_name;
-    $basename         =~ s/\./_/g;
-    my $name          = $type ? "${type}_$basename" : $basename;
-
-    if ( $basename ne $basename_orig and $critical ) {
-        my $show_type = $type ? "+'$type'" : "";
-        warn "Truncating '$basename_orig'$show_type to $max_id_length ",
-            "character limit to make '$name'\n" if $WARN;
-        $truncated{ $basename_orig } = $name;
-    }
+    my ($name, $scope, $critical) = @_;
 
     $scope ||= \%global_names;
     if ( my $prev = $scope->{ $name } ) {
@@ -130,19 +137,26 @@ sub create_view {
 
     # Header.  Should this look like what mysqldump produces?
     my $extra = $view->extra;
-    my $create = '';
-    $create .= "--\n-- View: ${view_name}\n--\n" unless $options->{no_comments};
-    $create .= "DROP VIEW IF EXISTS $view_name;\n" if $add_drop_view;
-    $create .= 'CREATE';
-    $create .= " TEMPORARY" if exists($extra->{temporary}) && $extra->{temporary};
-    $create .= ' VIEW';
-    $create .= " IF NOT EXISTS" if exists($extra->{if_not_exists}) && $extra->{if_not_exists};
-    $create .= " ${view_name}";
+    my @create;
+    push @create, "DROP VIEW IF EXISTS $view_name" if $add_drop_view;
+
+    my $create_view = 'CREATE';
+    $create_view .= " TEMPORARY" if exists($extra->{temporary}) && $extra->{temporary};
+    $create_view .= ' VIEW';
+    $create_view .= " IF NOT EXISTS" if exists($extra->{if_not_exists}) && $extra->{if_not_exists};
+    $create_view .= " ${view_name}";
 
     if( my $sql = $view->sql ){
-      $create .= " AS\n    ${sql}";
+      $create_view .= " AS\n    ${sql}";
     }
-    return $create;
+    push @create, $create_view;
+
+    # Tack the comment onto the first statement.
+    unless ($options->{no_comments}) {
+      $create[0] = "--\n-- View: ${view_name}\n--\n" . $create[0];
+    }
+
+    return @create;
 }
 
 
@@ -157,18 +171,24 @@ sub create_table
 
     debug("PKG: Looking at table '$table_name'\n");
 
-    my ( @index_defs, @constraint_defs, @trigger_defs );
+    my ( @index_defs, @constraint_defs );
     my @fields = $table->get_fields or die "No fields in $table_name";
 
     my $temp = $options->{temporary_table} ? 'TEMPORARY ' : '';
     #
     # Header.
     #
-    my $exists = ($sqlite_version >= 3.3) ? ' IF EXISTS' : '';
+    my $exists = ($sqlite_version >= 3.003) ? ' IF EXISTS' : '';
     my @create;
-    push @create, "--\n-- Table: $table_name\n--\n" unless $no_comments;
-    push @create, qq[DROP TABLE$exists $table_name] if $add_drop_table;
-    my $create_table = "CREATE ${temp}TABLE $table_name (\n";
+    my ($comment, $create_table) = "";
+    $comment =  "--\n-- Table: $table_name\n--\n" unless $no_comments;
+    if ($add_drop_table) {
+      push @create, $comment . qq[DROP TABLE$exists $table_name];
+    } else {
+      $create_table = $comment;
+    }
+
+    $create_table .= "CREATE ${temp}TABLE $table_name (\n";
 
     #
     # Comments
@@ -220,7 +240,7 @@ sub create_table
 
     $create_table .= join(",\n", map { "  $_" } @field_defs ) . "\n)";
 
-    return (@create, $create_table, @index_defs, @constraint_defs, @trigger_defs );
+    return (@create, $create_table, @index_defs, @constraint_defs );
 }
 
 sub create_field
@@ -285,19 +305,16 @@ sub create_field
     # Null?
     $field_def .= ' NOT NULL' unless $field->is_nullable;
 
-    # Default?  XXX Need better quoting!
-    my $default = $field->default_value;
-    if (defined $default) {
-        SQL::Translator::Producer->_apply_default_value(
-            \$field_def,
-            $default, 
-            [
-             'NULL'              => \'NULL',
-             'now()'             => 'now()',
-             'CURRENT_TIMESTAMP' => 'CURRENT_TIMESTAMP',
-            ],
-        );
-    }
+    # Default?
+    SQL::Translator::Producer->_apply_default_value(
+        $field,
+        \$field_def,
+        [
+         'NULL'              => \'NULL',
+         'now()'             => 'now()',
+         'CURRENT_TIMESTAMP' => 'CURRENT_TIMESTAMP',
+        ],
+    );
 
     return $field_def;
 
@@ -308,7 +325,7 @@ sub create_index
     my ($index, $options) = @_;
 
     my $name   = $index->name;
-    $name      = mk_name($index->table->name, $name);
+    $name      = mk_name($name);
 
     my $type   = $index->type eq 'UNIQUE' ? "UNIQUE " : ''; 
 
@@ -328,7 +345,7 @@ sub create_constraint
     my ($c, $options) = @_;
 
     my $name   = $c->name;
-    $name      = mk_name($c->table->name, $name);
+    $name      = mk_name($name);
     my @fields = $c->fields;
     (my $index_table_name = $c->table->name) =~ s/^.+?\.//; # table name may not specify schema
     warn "removing schema name from '" . $c->table->name . "' to make '$index_table_name'\n" if $WARN;
@@ -340,6 +357,59 @@ sub create_constraint
     return $c_def;
 }
 
+sub create_trigger {
+  my ($trigger, $options) = @_;
+  my $add_drop = $options->{add_drop_trigger};
+
+  my @statements;
+
+  my $trigger_name = $trigger->name;
+  my $events = $trigger->database_events;
+  for my $evt ( @$events ) {
+
+    my $trig_name = $trigger_name;
+    if (@$events > 1) {
+      $trig_name .= "_$evt";
+
+      warn "Multiple database events supplied for trigger '$trigger_name', ",
+        "creating trigger '$trig_name' for the '$evt' event.\n" if $WARN;
+    }
+
+    push @statements,  "DROP TRIGGER IF EXISTS $trig_name" if $add_drop;
+
+
+    $DB::single = 1;
+    my $action = "";
+    if (not ref $trigger->action) {
+      $action .= "BEGIN " . $trigger->action . " END";
+    }
+    else {
+      $action = $trigger->action->{for_each} . " "
+        if $trigger->action->{for_each};
+
+      $action = $trigger->action->{when} . " "
+        if $trigger->action->{when};
+
+      my $steps = $trigger->action->{steps} || [];
+
+      $action .= "BEGIN ";
+      $action .= $_ . "; " for (@$steps);
+      $action .= "END";
+    }
+
+    push @statements, sprintf (
+      'CREATE TRIGGER %s %s %s on %s %s',
+      $trig_name,
+      $trigger->perform_action_when,
+      $evt,
+      $trigger->on_table,
+      $action
+    );
+  }
+
+  return @statements;
+}
+
 sub alter_table { } # Noop
 
 sub add_field {
@@ -468,7 +538,7 @@ SQL::Translator, http://www.sqlite.org/.
 
 =head1 AUTHOR
 
-Ken Y. Clark C<< <kclark@cpan.orgE> >>.
+Ken Youens-Clark C<< <kclark@cpan.orgE> >>.
 
 Diff code added by Ash Berlin C<< <ash@cpan.org> >>.