1 package SQL::Translator::Producer::SQLite;
3 # -------------------------------------------------------------------
4 # $Id: SQLite.pm,v 1.15 2006-08-26 11:35:31 schiffbruechige Exp $
5 # -------------------------------------------------------------------
6 # Copyright (C) 2002-4 SQLFairy Authors
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.
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.
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
21 # -------------------------------------------------------------------
25 SQL::Translator::Producer::SQLite - SQLite producer for SQL::Translator
31 my $t = SQL::Translator->new( parser => '...', producer => 'SQLite' );
36 This module will produce text output of the schema suitable for SQLite.
42 use SQL::Translator::Schema::Constants;
43 use SQL::Translator::Utils qw(debug header_comment);
45 use vars qw[ $VERSION $DEBUG $WARN ];
47 $VERSION = sprintf "%d.%02d", q$Revision: 1.15 $ =~ /(\d+)\.(\d+)/;
48 $DEBUG = 0 unless defined $DEBUG;
49 $WARN = 0 unless defined $WARN;
51 my %used_identifiers = ();
52 my $max_id_length = 30;
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;
64 debug("PKG: Beginning production\n");
67 $create .= header_comment unless ($no_comments);
68 $create .= "BEGIN TRANSACTION;\n\n";
71 for my $table ( $schema->get_tables ) {
72 my @defs = create_table($table, { no_comments => $no_comments,
73 add_drop_table => $add_drop_table,});
74 my $create = shift @defs;
76 push @table_defs, $create, map( { "$_;" } @defs), "";
79 # $create .= "COMMIT;\n";
81 return wantarray ? ($create, @table_defs, "COMMIT;\n") : join("\n", ($create, @table_defs, "COMMIT;\n"));
84 # -------------------------------------------------------------------
86 my ($basename, $type, $scope, $critical) = @_;
87 my $basename_orig = $basename;
89 ? $max_id_length - (length($type) + 1)
91 $basename = substr( $basename, 0, $max_name )
92 if length( $basename ) > $max_name;
93 my $name = $type ? "${type}_$basename" : $basename;
95 if ( $basename ne $basename_orig and $critical ) {
96 my $show_type = $type ? "+'$type'" : "";
97 warn "Truncating '$basename_orig'$show_type to $max_id_length ",
98 "character limit to make '$name'\n" if $WARN;
99 $truncated{ $basename_orig } = $name;
102 $scope ||= \%global_names;
103 if ( my $prev = $scope->{ $name } ) {
104 my $name_orig = $name;
105 $name .= sprintf( "%02d", ++$prev );
106 substr($name, $max_id_length - 3) = "00"
107 if length( $name ) > $max_id_length;
109 warn "The name '$name_orig' has been changed to ",
110 "'$name' to make it unique.\n" if $WARN;
112 $scope->{ $name_orig }++;
121 my ($table, $options) = @_;
123 my $table_name = $table->name;
124 my $no_comments = $options->{no_comments};
125 my $add_drop_table = $options->{add_drop_table};
127 debug("PKG: Looking at table '$table_name'\n");
129 my ( @index_defs, @constraint_defs, @trigger_defs );
130 my @fields = $table->get_fields or die "No fields in $table_name";
132 my $temp = $options->{temporary_table} ? 'TEMPORARY ' : '';
137 $create .= "--\n-- Table: $table_name\n--\n" unless $no_comments;
138 $create .= qq[DROP TABLE $table_name;\n] if $add_drop_table;
139 $create .= "CREATE ${temp}TABLE $table_name (\n";
144 if ( $table->comments and !$no_comments ){
145 $create .= "-- Comments: \n-- ";
146 $create .= join "\n-- ", $table->comments;
147 $create .= "\n--\n\n";
151 # How many fields in PK?
153 my $pk = $table->primary_key;
154 my @pk_fields = $pk ? $pk->fields : ();
159 my ( @field_defs, $pk_set );
160 for my $field ( @fields ) {
161 push @field_defs, create_field($field);
165 scalar @pk_fields > 1
167 ( @pk_fields && !grep /INTEGER PRIMARY KEY/, @field_defs )
169 push @field_defs, 'PRIMARY KEY (' . join(', ', @pk_fields ) . ')';
175 my $idx_name_default = 'A';
176 for my $index ( $table->get_indices ) {
177 push @index_defs, create_index($index);
183 my $c_name_default = 'A';
184 for my $c ( $table->get_constraints ) {
185 next unless $c->type eq UNIQUE;
186 push @constraint_defs, create_constraint($c);
189 $create .= join(",\n", map { " $_" } @field_defs ) . "\n)";
191 return ($create, @index_defs, @constraint_defs, @trigger_defs );
196 my ($field, $options) = @_;
198 my $field_name = $field->name;
199 debug("PKG: Looking at field '$field_name'\n");
200 my $field_comments = $field->comments
201 ? "-- " . $field->comments . "\n "
204 my $field_def = $field_comments.$field_name;
207 my $size = $field->size;
208 my $data_type = $field->data_type;
209 $data_type = 'varchar' if lc $data_type eq 'set';
210 $data_type = 'blob' if lc $data_type eq 'bytea';
212 if ( lc $data_type =~ /(text|blob)/i ) {
216 # if ( $data_type =~ /timestamp/i ) {
217 # push @trigger_defs,
218 # "CREATE TRIGGER ts_${table_name} ".
219 # "after insert on $table_name\n".
221 # " update $table_name set $field_name=timestamp() ".
222 # "where id=new.id;\n".
229 # SQLite is generally typeless, but newer versions will
230 # make a field autoincrement if it is declared as (and
231 # *only* as) INTEGER PRIMARY KEY
233 my $pk = $field->table->primary_key;
234 my @pk_fields = $pk ? $pk->fields : ();
237 $field->is_primary_key &&
238 scalar @pk_fields == 1 &&
240 $data_type =~ /int(eger)?$/i
242 ( $data_type =~ /^number?$/i && $size !~ /,/ )
245 $data_type = 'INTEGER PRIMARY KEY';
250 $field_def .= sprintf " %s%s", $data_type,
251 ( !$field->is_auto_increment && $size ) ? "($size)" : '';
254 $field_def .= ' NOT NULL' unless $field->is_nullable;
256 # Default? XXX Need better quoting!
257 my $default = $field->default_value;
258 if ( defined $default ) {
259 if ( uc $default eq 'NULL') {
260 $field_def .= ' DEFAULT NULL';
261 } elsif ( $default eq 'now()' ||
262 $default eq 'CURRENT_TIMESTAMP' ) {
263 $field_def .= ' DEFAULT CURRENT_TIMESTAMP';
264 } elsif ( $default =~ /val\(/ ) {
267 $field_def .= " DEFAULT '$default'";
277 my ($index, $options) = @_;
279 my $name = $index->name;
280 $name = mk_name($index->table->name, $name);
282 my $type = $index->type eq 'UNIQUE' ? "UNIQUE " : '';
284 # strip any field size qualifiers as SQLite doesn't like these
285 my @fields = map { s/\(\d+\)$//; $_ } $index->fields;
287 "CREATE ${type}INDEX $name ON " . $index->table->name .
288 ' (' . join( ', ', @fields ) . ')';
293 sub create_constraint
295 my ($c, $options) = @_;
298 $name = mk_name($c->table->name, $name);
299 my @fields = $c->fields;
302 "CREATE UNIQUE INDEX $name ON " . $c->table->name .
303 ' (' . join( ', ', @fields ) . ')';
308 sub alter_table { } # Noop
313 return sprintf("ALTER TABLE %s ADD COLUMN %s",
314 $field->table->name, create_field($field))
317 sub alter_create_index {
320 # This might cause name collisions
321 return create_index($index);
324 sub alter_create_constraint {
325 my ($constraint) = @_;
327 return create_constraint($constraint) if $constraint->type eq 'UNIQUE';
330 sub alter_drop_constraint { alter_drop_index(@_) }
332 sub alter_drop_index {
333 my ($constraint) = @_;
335 return sprintf("DROP INDEX %s ON %s",
336 $constraint->name, $constraint->table->name);
339 sub batch_alter_table {
340 my ($table, $diffs) = @_;
342 $DB::single = 1 if $table->name eq 'deleted';
344 # If we have any of the following
350 # we need to do the following <http://www.sqlite.org/faq.html#q11>
353 # CREATE TEMPORARY TABLE t1_backup(a,b);
354 # INSERT INTO t1_backup SELECT a,b FROM t1;
356 # CREATE TABLE t1(a,b);
357 # INSERT INTO t1 SELECT a,b FROM t1_backup;
358 # DROP TABLE t1_backup;
363 if ( @{$diffs->{rename_field}} == 0 &&
364 @{$diffs->{alter_field}} == 0 &&
365 @{$diffs->{drop_field}} == 0) {
366 return join("\n", map {
367 my $meth = __PACKAGE__->can($_) or die __PACKAGE__ . " cant $_";
368 map { my $sql = $meth->(ref $_ eq 'ARRAY' ? @$_ : $_); $sql ? ("$sql;") : () } @{ $diffs->{$_} }
370 } grep { @{$diffs->{$_}} } keys %$diffs);
377 local $table->{name} = $table->name . '_temp_alter';
378 # We only want the table - dont care about indexes on tmp table
379 my ($table_sql) = create_table($table, {no_comments => 1, temporary_table => 1});
380 push @sql,$table_sql;
383 push @sql, "INSERT INTO @{[$table]}_temp_alter SELECT @{[ join(', ', $table->get_fields)]} FROM @{[$table]}",
384 "DROP TABLE @{[$table]}",
385 create_table($table, { no_comments => 1 }),
386 "INSERT INTO @{[$table]} SELECT @{[ join(', ', $table->get_fields)]} FROM @{[$table]}_temp_alter",
387 "DROP TABLE @{[$table]}_temp_alter";
389 return join(";\n", @sql, "");
394 return "DROP TABLE $table;";
403 SQL::Translator, http://www.sqlite.org/.
407 Ken Y. Clark C<< <kclark@cpan.orgE> >>.
409 Diff code added by Ash Berlin C<< <ash@cpan.org> >>.