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