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