Needed semicolon on end of constraint def.
[dbsrgits/SQL-Translator.git] / lib / SQL / Translator / Producer / SQLite.pm
1 package SQL::Translator::Producer::SQLite;
2
3 # -------------------------------------------------------------------
4 # $Id: SQLite.pm,v 1.8 2003-10-08 23:00:42 kycl4rk Exp $
5 # -------------------------------------------------------------------
6 # Copyright (C) 2003 Ken Y. Clark <kclark@cpan.org>,
7 #                    darren chamberlain <darren@cpan.org>,
8 #                    Chris Mungall <cjm@fruitfly.org>
9 #
10 # This program is free software; you can redistribute it and/or
11 # modify it under the terms of the GNU General Public License as
12 # published by the Free Software Foundation; version 2.
13 #
14 # This program is distributed in the hope that it will be useful, but
15 # WITHOUT ANY WARRANTY; without even the implied warranty of
16 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17 # General Public License for more details.
18 #
19 # You should have received a copy of the GNU General Public License
20 # along with this program; if not, write to the Free Software
21 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
22 # 02111-1307  USA
23 # -------------------------------------------------------------------
24
25 use strict;
26 use Data::Dumper;
27 use SQL::Translator::Schema::Constants;
28 use SQL::Translator::Utils qw(debug header_comment);
29
30 use vars qw[ $VERSION $DEBUG $WARN ];
31
32 $VERSION = sprintf "%d.%02d", q$Revision: 1.8 $ =~ /(\d+)\.(\d+)/;
33 $DEBUG = 0 unless defined $DEBUG;
34 $WARN = 0 unless defined $WARN;
35
36 my %used_identifiers = ();
37 my $max_id_length    = 30;
38 my %global_names;
39 my %truncated;
40
41 sub produce {
42     my $translator     = shift;
43     local $DEBUG       = $translator->debug;
44     local $WARN        = $translator->show_warnings;
45     my $no_comments    = $translator->no_comments;
46     my $add_drop_table = $translator->add_drop_table;
47     my $schema         = $translator->schema;
48
49     debug("PKG: Beginning production\n");
50
51     my $create = '';
52     $create .= header_comment unless ($no_comments);
53     $create .= "BEGIN TRANSACTION;\n\n";
54
55     my ( @index_defs, @constraint_defs, @trigger_defs );
56     for my $table ( $schema->get_tables ) {
57         my $table_name = $table->name;
58         debug("PKG: Looking at table '$table_name'\n");
59
60         my @fields = $table->get_fields or die "No fields in $table_name";
61
62         #
63         # Header.
64         #
65         $create .= "--\n-- Table: $table_name\n--\n" unless $no_comments;
66         $create .= qq[DROP TABLE $table_name;\n] if $add_drop_table;
67         $create .= "CREATE TABLE $table_name (\n";
68
69         #
70         # How many fields in PK?
71         #
72         my $pk        = $table->primary_key;
73         my @pk_fields = $pk ? $pk->fields : ();
74
75         #
76         # Fields
77         #
78         my ( @field_defs, $pk_set );
79         for my $field ( @fields ) {
80             my $field_name = $field->name;
81             debug("PKG: Looking at field '$field_name'\n");
82             my $field_def = $field_name;
83
84             # data type and size
85             my $size      = $field->size;
86             my $data_type = $field->data_type;
87             $data_type    = 'varchar' if lc $data_type eq 'set';
88
89             if ( $data_type =~ /timestamp/i ) {
90                 push @trigger_defs, 
91                     "CREATE TRIGGER ts_${table_name} ".
92                     "after insert on $table_name\n".
93                     "begin\n".
94                     "  update $table_name set $field_name=timestamp() ".
95                        "where id=new.id;\n".
96                     "end;\n"
97                 ;
98
99             }
100
101             #
102             # SQLite is generally typeless, but newer versions will
103             # make a field autoincrement if it is declared as (and
104             # *only* as) INTEGER PRIMARY KEY
105             #
106             if ( 
107                 $field->is_primary_key && 
108                 scalar @pk_fields == 1 &&
109                 (
110                     $data_type =~ /^int(eger)?$/i
111                     ||
112                     ( $data_type =~ /^number?$/i && $size !~ /,/ )
113                 )
114             ) {
115                 $data_type = 'INTEGER PRIMARY KEY';
116                 $size      = undef;
117                 $pk_set    = 1;
118             }
119
120             $field_def .= sprintf " %s%s", $data_type, 
121                 ( !$field->is_auto_increment && $size ) ? "($size)" : '';
122
123             # Null?
124             $field_def .= ' NOT NULL' unless $field->is_nullable;
125
126             # Default?  XXX Need better quoting!
127             my $default = $field->default_value;
128             if ( defined $default ) {
129                 if ( uc $default eq 'NULL') {
130                     $field_def .= ' DEFAULT NULL';
131                 } else {
132                     $field_def .= " DEFAULT '$default'";
133                 }
134             }
135
136             push @field_defs, $field_def;
137         }
138
139         if ( 
140             scalar @pk_fields > 1 
141             || 
142             ( @pk_fields && !$pk_set ) 
143         ) {
144             push @field_defs, 'PRIMARY KEY (' . join(', ', @pk_fields ) . ')';
145         }
146
147         #
148         # Indices
149         #
150         my $idx_name_default = 'A';
151         for my $index ( $table->get_indices ) {
152             my $name   = $index->name;
153             $name      = mk_name($table_name, $name || ++$idx_name_default);
154
155             # strip any field size qualifiers as SQLite doesn't like these
156             my @fields = map { s/\(\d+\)$//; $_ } $index->fields;
157             push @index_defs, 
158                 "CREATE INDEX $name on $table_name ".
159                 '(' . join( ', ', @fields ) . ');';
160         }
161
162         #
163         # Constraints
164         #
165         my $c_name_default = 'A';
166         for my $c ( $table->get_constraints ) {
167             next unless $c->type eq UNIQUE; 
168             my $name   = $c->name;
169             $name      = mk_name($table_name, $name || ++$idx_name_default);
170             my @fields = $c->fields;
171
172             push @constraint_defs, 
173                 "CREATE UNIQUE INDEX $name on $table_name ".
174                 '(' . join( ', ', @fields ) . ');';
175         }
176
177         $create .= join(",\n", map { "  $_" } @field_defs ) . "\n);\n";
178
179         $create .= "\n";
180     }
181
182     for my $def ( @index_defs, @constraint_defs, @trigger_defs ) {
183         $create .= "$def\n";
184     }
185
186     $create .= "COMMIT;\n";
187
188     return $create;
189 }
190
191 # -------------------------------------------------------------------
192 sub mk_name {
193     my ($basename, $type, $scope, $critical) = @_;
194     my $basename_orig = $basename;
195     my $max_name      = $type 
196                         ? $max_id_length - (length($type) + 1) 
197                         : $max_id_length;
198     $basename         = substr( $basename, 0, $max_name ) 
199                         if length( $basename ) > $max_name;
200     my $name          = $type ? "${type}_$basename" : $basename;
201
202     if ( $basename ne $basename_orig and $critical ) {
203         my $show_type = $type ? "+'$type'" : "";
204         warn "Truncating '$basename_orig'$show_type to $max_id_length ",
205             "character limit to make '$name'\n" if $WARN;
206         $truncated{ $basename_orig } = $name;
207     }
208
209     $scope ||= \%global_names;
210     if ( my $prev = $scope->{ $name } ) {
211         my $name_orig = $name;
212         $name        .= sprintf( "%02d", ++$prev );
213         substr($name, $max_id_length - 3) = "00" 
214             if length( $name ) > $max_id_length;
215
216         warn "The name '$name_orig' has been changed to ",
217              "'$name' to make it unique.\n" if $WARN;
218
219         $scope->{ $name_orig }++;
220     }
221
222     $scope->{ $name }++;
223     return $name;
224 }
225
226 1;
227
228 =head1 NAME
229
230 SQL::Translator::Producer::SQLite - SQLite producer for SQL::Translator
231
232 =head1 AUTHOR
233
234 Ken Y. Clark E<lt>kclark@cpan.orgE<gt>