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 $basename =~ s/\./_/g;
94 my $name = $type ? "${type}_$basename" : $basename;
96 if ( $basename ne $basename_orig and $critical ) {
97 my $show_type = $type ? "+'$type'" : "";
98 warn "Truncating '$basename_orig'$show_type to $max_id_length ",
99 "character limit to make '$name'\n" if $WARN;
100 $truncated{ $basename_orig } = $name;
103 $scope ||= \%global_names;
104 if ( my $prev = $scope->{ $name } ) {
105 my $name_orig = $name;
106 $name .= sprintf( "%02d", ++$prev );
107 substr($name, $max_id_length - 3) = "00"
108 if length( $name ) > $max_id_length;
110 warn "The name '$name_orig' has been changed to ",
111 "'$name' to make it unique.\n" if $WARN;
113 $scope->{ $name_orig }++;
122 my ($table, $options) = @_;
124 my $table_name = $table->name;
125 my $no_comments = $options->{no_comments};
126 my $add_drop_table = $options->{add_drop_table};
128 debug("PKG: Looking at table '$table_name'\n");
130 my ( @index_defs, @constraint_defs, @trigger_defs );
131 my @fields = $table->get_fields or die "No fields in $table_name";
133 my $temp = $options->{temporary_table} ? 'TEMPORARY ' : '';
138 $create .= "--\n-- Table: $table_name\n--\n" unless $no_comments;
139 $create .= qq[DROP TABLE $table_name;\n] if $add_drop_table;
140 $create .= "CREATE ${temp}TABLE $table_name (\n";
145 if ( $table->comments and !$no_comments ){
146 $create .= "-- Comments: \n-- ";
147 $create .= join "\n-- ", $table->comments;
148 $create .= "\n--\n\n";
152 # How many fields in PK?
154 my $pk = $table->primary_key;
155 my @pk_fields = $pk ? $pk->fields : ();
160 my ( @field_defs, $pk_set );
161 for my $field ( @fields ) {
162 push @field_defs, create_field($field);
166 scalar @pk_fields > 1
168 ( @pk_fields && !grep /INTEGER PRIMARY KEY/, @field_defs )
170 push @field_defs, 'PRIMARY KEY (' . join(', ', @pk_fields ) . ')';
176 my $idx_name_default = 'A';
177 for my $index ( $table->get_indices ) {
178 push @index_defs, create_index($index);
184 my $c_name_default = 'A';
185 for my $c ( $table->get_constraints ) {
186 next unless $c->type eq UNIQUE;
187 push @constraint_defs, create_constraint($c);
190 $create .= join(",\n", map { " $_" } @field_defs ) . "\n)";
192 return ($create, @index_defs, @constraint_defs, @trigger_defs );
197 my ($field, $options) = @_;
199 my $field_name = $field->name;
200 debug("PKG: Looking at field '$field_name'\n");
201 my $field_comments = $field->comments
202 ? "-- " . $field->comments . "\n "
205 my $field_def = $field_comments.$field_name;
208 my $size = $field->size;
209 my $data_type = $field->data_type;
210 $data_type = 'varchar' if lc $data_type eq 'set';
211 $data_type = 'blob' if lc $data_type eq 'bytea';
213 if ( lc $data_type =~ /(text|blob)/i ) {
217 # if ( $data_type =~ /timestamp/i ) {
218 # push @trigger_defs,
219 # "CREATE TRIGGER ts_${table_name} ".
220 # "after insert on $table_name\n".
222 # " update $table_name set $field_name=timestamp() ".
223 # "where id=new.id;\n".
230 # SQLite is generally typeless, but newer versions will
231 # make a field autoincrement if it is declared as (and
232 # *only* as) INTEGER PRIMARY KEY
234 my $pk = $field->table->primary_key;
235 my @pk_fields = $pk ? $pk->fields : ();
238 $field->is_primary_key &&
239 scalar @pk_fields == 1 &&
241 $data_type =~ /int(eger)?$/i
243 ( $data_type =~ /^number?$/i && $size !~ /,/ )
246 $data_type = 'INTEGER PRIMARY KEY';
251 $field_def .= sprintf " %s%s", $data_type,
252 ( !$field->is_auto_increment && $size ) ? "($size)" : '';
255 $field_def .= ' NOT NULL' unless $field->is_nullable;
257 # Default? XXX Need better quoting!
258 my $default = $field->default_value;
259 if ( defined $default ) {
260 if ( uc $default eq 'NULL') {
261 $field_def .= ' DEFAULT NULL';
262 } elsif ( $default eq 'now()' ||
263 $default eq 'CURRENT_TIMESTAMP' ) {
264 $field_def .= ' DEFAULT CURRENT_TIMESTAMP';
265 } elsif ( $default =~ /val\(/ ) {
268 $field_def .= " DEFAULT '$default'";
278 my ($index, $options) = @_;
280 my $name = $index->name;
281 $name = mk_name($index->table->name, $name);
283 my $type = $index->type eq 'UNIQUE' ? "UNIQUE " : '';
285 # strip any field size qualifiers as SQLite doesn't like these
286 my @fields = map { s/\(\d+\)$//; $_ } $index->fields;
287 (my $index_table_name = $index->table->name) =~ s/^.+?\.//; # table name may not specify schema
288 warn "removing schema name from '" . $index->table->name . "' to make '$index_table_name'\n" if $WARN;
290 "CREATE ${type}INDEX $name ON " . $index_table_name .
291 ' (' . join( ', ', @fields ) . ')';
296 sub create_constraint
298 my ($c, $options) = @_;
301 $name = mk_name($c->table->name, $name);
302 my @fields = $c->fields;
303 (my $index_table_name = $c->table->name) =~ s/^.+?\.//; # table name may not specify schema
304 warn "removing schema name from '" . $c->table->name . "' to make '$index_table_name'\n" if $WARN;
307 "CREATE UNIQUE INDEX $name ON " . $index_table_name .
308 ' (' . join( ', ', @fields ) . ')';
313 sub alter_table { } # Noop
318 return sprintf("ALTER TABLE %s ADD COLUMN %s",
319 $field->table->name, create_field($field))
322 sub alter_create_index {
325 # This might cause name collisions
326 return create_index($index);
329 sub alter_create_constraint {
330 my ($constraint) = @_;
332 return create_constraint($constraint) if $constraint->type eq 'UNIQUE';
335 sub alter_drop_constraint { alter_drop_index(@_) }
337 sub alter_drop_index {
338 my ($constraint) = @_;
340 return sprintf("DROP INDEX %s ON %s",
341 $constraint->name, $constraint->table->name);
344 sub batch_alter_table {
345 my ($table, $diffs) = @_;
347 # If we have any of the following
353 # we need to do the following <http://www.sqlite.org/faq.html#q11>
356 # CREATE TEMPORARY TABLE t1_backup(a,b);
357 # INSERT INTO t1_backup SELECT a,b FROM t1;
359 # CREATE TABLE t1(a,b);
360 # INSERT INTO t1 SELECT a,b FROM t1_backup;
361 # DROP TABLE t1_backup;
366 # If we have rename_field we do similarly.
368 my $table_name = $table->name;
369 my $renaming = $diffs->{rename_table} && @{$diffs->{rename_table}};
371 if ( @{$diffs->{rename_field}} == 0 &&
372 @{$diffs->{alter_field}} == 0 &&
373 @{$diffs->{drop_field}} == 0
375 return join("\n", map {
376 my $meth = __PACKAGE__->can($_) or die __PACKAGE__ . " cant $_";
377 map { my $sql = $meth->(ref $_ eq 'ARRAY' ? @$_ : $_); $sql ? ("$sql;") : () } @{ $diffs->{$_} }
379 } grep { @{$diffs->{$_}} }
381 alter_drop_constraint
388 alter_create_constraint
394 my $old_table = $renaming ? $diffs->{rename_table}[0][0] : $table;
397 local $table->{name} = $table_name . '_temp_alter';
398 # We only want the table - dont care about indexes on tmp table
399 my ($table_sql) = create_table($table, {no_comments => 1, temporary_table => 1});
400 push @sql,$table_sql;
403 push @sql, "INSERT INTO @{[$table_name]}_temp_alter SELECT @{[ join(', ', $old_table->get_fields)]} FROM @{[$old_table]}",
404 "DROP TABLE @{[$old_table]}",
405 create_table($table, { no_comments => 1 }),
406 "INSERT INTO @{[$table_name]} SELECT @{[ join(', ', $old_table->get_fields)]} FROM @{[$table_name]}_temp_alter",
407 "DROP TABLE @{[$table_name]}_temp_alter";
409 return join(";\n", @sql, "");
414 return "DROP TABLE $table;";
418 my ($old_table, $new_table, $options) = @_;
420 my $qt = $options->{quote_table_names} || '';
422 return "ALTER TABLE $qt$old_table$qt RENAME TO $qt$new_table$qt";
432 SQL::Translator, http://www.sqlite.org/.
436 Ken Y. Clark C<< <kclark@cpan.orgE> >>.
438 Diff code added by Ash Berlin C<< <ash@cpan.org> >>.