5a27a308662469382609daf10fff7f2d3b620efc
[dbsrgits/SQL-Translator.git] / lib / SQL / Translator / Producer / SQLite.pm
1 package SQL::Translator::Producer::SQLite;
2
3 # -------------------------------------------------------------------
4 # $Id: SQLite.pm,v 1.12 2005-06-13 18:23:10 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.12 $ =~ /(\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         # How many fields in PK?
86         #
87         my $pk        = $table->primary_key;
88         my @pk_fields = $pk ? $pk->fields : ();
89
90         #
91         # Fields
92         #
93         my ( @field_defs, $pk_set );
94         for my $field ( @fields ) {
95             my $field_name = $field->name;
96             debug("PKG: Looking at field '$field_name'\n");
97             my $field_def = $field_name;
98
99             # data type and size
100             my $size      = $field->size;
101             my $data_type = $field->data_type;
102             $data_type    = 'varchar' if lc $data_type eq 'set';
103             $data_type  = 'blob' if lc $data_type eq 'bytea';
104
105             if ( lc $data_type =~ /(text|blob)/i ) {
106                 $size = undef;
107             }
108
109             if ( $data_type =~ /timestamp/i ) {
110                 push @trigger_defs, 
111                     "CREATE TRIGGER ts_${table_name} ".
112                     "after insert on $table_name\n".
113                     "begin\n".
114                     "  update $table_name set $field_name=timestamp() ".
115                        "where id=new.id;\n".
116                     "end;\n"
117                 ;
118
119             }
120
121             #
122             # SQLite is generally typeless, but newer versions will
123             # make a field autoincrement if it is declared as (and
124             # *only* as) INTEGER PRIMARY KEY
125             #
126             if ( 
127                 $field->is_primary_key && 
128                 scalar @pk_fields == 1 &&
129                 (
130                     $data_type =~ /int(eger)?$/i
131                     ||
132                     ( $data_type =~ /^number?$/i && $size !~ /,/ )
133                 )
134             ) {
135                 $data_type = 'INTEGER PRIMARY KEY';
136                 $size      = undef;
137                 $pk_set    = 1;
138             }
139
140             $field_def .= sprintf " %s%s", $data_type, 
141                 ( !$field->is_auto_increment && $size ) ? "($size)" : '';
142
143             # Null?
144             $field_def .= ' NOT NULL' unless $field->is_nullable;
145
146             # Default?  XXX Need better quoting!
147             my $default = $field->default_value;
148             if ( defined $default ) {
149                 if ( uc $default eq 'NULL') {
150                     $field_def .= ' DEFAULT NULL';
151                 } elsif ( $default eq 'now()' ) {
152                     $field_def .= ' DEFAULT CURRENT_TIMESTAMP';
153                 } elsif ( $default =~ /val\(/ ) {
154                     next;
155                 } else {
156                     $field_def .= " DEFAULT '$default'";
157                 }
158             }
159
160             push @field_defs, $field_def;
161         }
162
163         if ( 
164             scalar @pk_fields > 1 
165             || 
166             ( @pk_fields && !$pk_set ) 
167         ) {
168             push @field_defs, 'PRIMARY KEY (' . join(', ', @pk_fields ) . ')';
169         }
170
171         #
172         # Indices
173         #
174         my $idx_name_default = 'A';
175         for my $index ( $table->get_indices ) {
176             my $name   = $index->name;
177             $name      = mk_name($table_name, $name || ++$idx_name_default);
178
179             # strip any field size qualifiers as SQLite doesn't like these
180             my @fields = map { s/\(\d+\)$//; $_ } $index->fields;
181             push @index_defs, 
182                 "CREATE INDEX $name on $table_name ".
183                 '(' . join( ', ', @fields ) . ');';
184         }
185
186         #
187         # Constraints
188         #
189         my $c_name_default = 'A';
190         for my $c ( $table->get_constraints ) {
191             next unless $c->type eq UNIQUE; 
192             my $name   = $c->name;
193             $name      = mk_name($table_name, $name || ++$idx_name_default);
194             my @fields = $c->fields;
195
196             push @constraint_defs, 
197                 "CREATE UNIQUE INDEX $name on $table_name ".
198                 '(' . join( ', ', @fields ) . ');';
199         }
200
201         $create .= join(",\n", map { "  $_" } @field_defs ) . "\n);\n";
202
203         $create .= "\n";
204     }
205
206     for my $def ( @index_defs, @constraint_defs, @trigger_defs ) {
207         $create .= "$def\n";
208     }
209
210     $create .= "COMMIT;\n";
211
212     return $create;
213 }
214
215 # -------------------------------------------------------------------
216 sub mk_name {
217     my ($basename, $type, $scope, $critical) = @_;
218     my $basename_orig = $basename;
219     my $max_name      = $type 
220                         ? $max_id_length - (length($type) + 1) 
221                         : $max_id_length;
222     $basename         = substr( $basename, 0, $max_name ) 
223                         if length( $basename ) > $max_name;
224     my $name          = $type ? "${type}_$basename" : $basename;
225
226     if ( $basename ne $basename_orig and $critical ) {
227         my $show_type = $type ? "+'$type'" : "";
228         warn "Truncating '$basename_orig'$show_type to $max_id_length ",
229             "character limit to make '$name'\n" if $WARN;
230         $truncated{ $basename_orig } = $name;
231     }
232
233     $scope ||= \%global_names;
234     if ( my $prev = $scope->{ $name } ) {
235         my $name_orig = $name;
236         $name        .= sprintf( "%02d", ++$prev );
237         substr($name, $max_id_length - 3) = "00" 
238             if length( $name ) > $max_id_length;
239
240         warn "The name '$name_orig' has been changed to ",
241              "'$name' to make it unique.\n" if $WARN;
242
243         $scope->{ $name_orig }++;
244     }
245
246     $scope->{ $name }++;
247     return $name;
248 }
249
250 1;
251
252 # -------------------------------------------------------------------
253
254 =pod
255
256 =head1 SEE ALSO
257
258 SQL::Translator, http://www.sqlite.org/.
259
260 =head1 AUTHOR
261
262 Ken Y. Clark E<lt>kclark@cpan.orgE<gt>.
263
264 =cut