1 package SQL::Translator::Producer::SQLite;
3 # -------------------------------------------------------------------
4 # Copyright (C) 2002-2009 SQLFairy Authors
6 # This program is free software; you can redistribute it and/or
7 # modify it under the terms of the GNU General Public License as
8 # published by the Free Software Foundation; version 2.
10 # This program is distributed in the hope that it will be useful, but
11 # WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 # General Public License for more details.
15 # You should have received a copy of the GNU General Public License
16 # along with this program; if not, write to the Free Software
17 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
19 # -------------------------------------------------------------------
23 SQL::Translator::Producer::SQLite - SQLite producer for SQL::Translator
29 my $t = SQL::Translator->new( parser => '...', producer => 'SQLite' );
34 This module will produce text output of the schema suitable for SQLite.
41 use SQL::Translator::Schema::Constants;
42 use SQL::Translator::Utils qw(debug header_comment);
44 use vars qw[ $VERSION $DEBUG $WARN ];
47 $DEBUG = 0 unless defined $DEBUG;
48 $WARN = 0 unless defined $WARN;
50 our %used_identifiers = ();
51 our $max_id_length = 30;
56 my $translator = shift;
57 local $DEBUG = $translator->debug;
58 local $WARN = $translator->show_warnings;
59 my $no_comments = $translator->no_comments;
60 my $add_drop_table = $translator->add_drop_table;
61 my $schema = $translator->schema;
62 my $producer_args = $translator->producer_args;
63 my $sqlite_version = $producer_args->{sqlite_version} || 0;
64 my $no_txn = $producer_args->{no_transaction};
66 debug("PKG: Beginning production\n");
69 push @create, header_comment unless ($no_comments);
70 $create[0] .= "\n\nBEGIN TRANSACTION" unless $no_txn;
72 for my $table ( $schema->get_tables ) {
73 push @create, create_table($table, { no_comments => $no_comments,
74 sqlite_version => $sqlite_version,
75 add_drop_table => $add_drop_table,});
78 for my $view ( $schema->get_views ) {
79 push @create, create_view($view, {
80 add_drop_view => $add_drop_table,
81 no_comments => $no_comments,
85 for my $trigger ( $schema->get_triggers ) {
86 push @create, create_trigger($trigger, {
87 add_drop_trigger => $add_drop_table,
88 no_comments => $no_comments,
93 push @create, "COMMIT" unless $no_txn;
96 push @create, "COMMIT;\n" unless $no_txn;
97 return join(";\n\n", @create );
101 # -------------------------------------------------------------------
103 my ($basename, $type, $scope, $critical) = @_;
104 my $basename_orig = $basename;
105 my $max_name = !$max_id_length
108 ? $max_id_length - (length($type) + 1)
110 $basename = substr( $basename, 0, $max_name )
111 if length( $basename ) > $max_name;
112 $basename =~ s/\./_/g;
113 my $name = $type ? "${type}_$basename" : $basename;
115 if ( $basename ne $basename_orig and $critical ) {
116 my $show_type = $type ? "+'$type'" : "";
117 warn "Truncating '$basename_orig'$show_type to $max_id_length ",
118 "character limit to make '$name'\n" if $WARN;
119 $truncated{ $basename_orig } = $name;
122 $scope ||= \%global_names;
123 if ( my $prev = $scope->{ $name } ) {
124 my $name_orig = $name;
125 $name .= sprintf( "%02d", ++$prev );
126 substr($name, $max_id_length - 3) = "00"
127 if length( $name ) > $max_id_length;
129 warn "The name '$name_orig' has been changed to ",
130 "'$name' to make it unique.\n" if $WARN;
132 $scope->{ $name_orig }++;
140 my ($view, $options) = @_;
141 my $add_drop_view = $options->{add_drop_view};
143 my $view_name = $view->name;
144 debug("PKG: Looking at view '${view_name}'\n");
146 # Header. Should this look like what mysqldump produces?
147 my $extra = $view->extra;
149 $create .= "--\n-- View: ${view_name}\n--\n" unless $options->{no_comments};
150 $create .= "DROP VIEW IF EXISTS $view_name;\n" if $add_drop_view;
152 $create .= " TEMPORARY" if exists($extra->{temporary}) && $extra->{temporary};
154 $create .= " IF NOT EXISTS" if exists($extra->{if_not_exists}) && $extra->{if_not_exists};
155 $create .= " ${view_name}";
157 if( my $sql = $view->sql ){
158 $create .= " AS\n ${sql}";
166 my ($table, $options) = @_;
168 my $table_name = $table->name;
169 my $no_comments = $options->{no_comments};
170 my $add_drop_table = $options->{add_drop_table};
171 my $sqlite_version = $options->{sqlite_version} || 0;
173 debug("PKG: Looking at table '$table_name'\n");
175 my ( @index_defs, @constraint_defs );
176 my @fields = $table->get_fields or die "No fields in $table_name";
178 my $temp = $options->{temporary_table} ? 'TEMPORARY ' : '';
182 my $exists = ($sqlite_version >= 3.3) ? ' IF EXISTS' : '';
184 my ($comment, $create_table) = "";
185 $comment = "--\n-- Table: $table_name\n--\n" unless $no_comments;
186 if ($add_drop_table) {
187 push @create, $comment . qq[DROP TABLE$exists $table_name];
189 $create_table = $comment;
192 $create_table .= "CREATE ${temp}TABLE $table_name (\n";
197 if ( $table->comments and !$no_comments ){
198 $create_table .= "-- Comments: \n-- ";
199 $create_table .= join "\n-- ", $table->comments;
200 $create_table .= "\n--\n\n";
204 # How many fields in PK?
206 my $pk = $table->primary_key;
207 my @pk_fields = $pk ? $pk->fields : ();
212 my ( @field_defs, $pk_set );
213 for my $field ( @fields ) {
214 push @field_defs, create_field($field);
218 scalar @pk_fields > 1
220 ( @pk_fields && !grep /INTEGER PRIMARY KEY/, @field_defs )
222 push @field_defs, 'PRIMARY KEY (' . join(', ', @pk_fields ) . ')';
228 my $idx_name_default = 'A';
229 for my $index ( $table->get_indices ) {
230 push @index_defs, create_index($index);
236 my $c_name_default = 'A';
237 for my $c ( $table->get_constraints ) {
238 next unless $c->type eq UNIQUE;
239 push @constraint_defs, create_constraint($c);
242 $create_table .= join(",\n", map { " $_" } @field_defs ) . "\n)";
244 return (@create, $create_table, @index_defs, @constraint_defs );
249 my ($field, $options) = @_;
251 my $field_name = $field->name;
252 debug("PKG: Looking at field '$field_name'\n");
253 my $field_comments = $field->comments
254 ? "-- " . $field->comments . "\n "
257 my $field_def = $field_comments.$field_name;
260 my $size = $field->size;
261 my $data_type = $field->data_type;
262 $data_type = 'varchar' if lc $data_type eq 'set';
263 $data_type = 'blob' if lc $data_type eq 'bytea';
265 if ( lc $data_type =~ /(text|blob)/i ) {
269 # if ( $data_type =~ /timestamp/i ) {
270 # push @trigger_defs,
271 # "CREATE TRIGGER ts_${table_name} ".
272 # "after insert on $table_name\n".
274 # " update $table_name set $field_name=timestamp() ".
275 # "where id=new.id;\n".
282 # SQLite is generally typeless, but newer versions will
283 # make a field autoincrement if it is declared as (and
284 # *only* as) INTEGER PRIMARY KEY
286 my $pk = $field->table->primary_key;
287 my @pk_fields = $pk ? $pk->fields : ();
290 $field->is_primary_key &&
291 scalar @pk_fields == 1 &&
293 $data_type =~ /int(eger)?$/i
295 ( $data_type =~ /^number?$/i && $size !~ /,/ )
298 $data_type = 'INTEGER PRIMARY KEY';
303 $field_def .= sprintf " %s%s", $data_type,
304 ( !$field->is_auto_increment && $size ) ? "($size)" : '';
307 $field_def .= ' NOT NULL' unless $field->is_nullable;
309 # Default? XXX Need better quoting!
310 my $default = $field->default_value;
311 if (defined $default) {
312 SQL::Translator::Producer->_apply_default_value(
318 'CURRENT_TIMESTAMP' => 'CURRENT_TIMESTAMP',
329 my ($index, $options) = @_;
331 my $name = $index->name;
332 $name = mk_name($index->table->name, $name);
334 my $type = $index->type eq 'UNIQUE' ? "UNIQUE " : '';
336 # strip any field size qualifiers as SQLite doesn't like these
337 my @fields = map { s/\(\d+\)$//; $_ } $index->fields;
338 (my $index_table_name = $index->table->name) =~ s/^.+?\.//; # table name may not specify schema
339 warn "removing schema name from '" . $index->table->name . "' to make '$index_table_name'\n" if $WARN;
341 "CREATE ${type}INDEX $name ON " . $index_table_name .
342 ' (' . join( ', ', @fields ) . ')';
347 sub create_constraint
349 my ($c, $options) = @_;
352 $name = mk_name($c->table->name, $name);
353 my @fields = $c->fields;
354 (my $index_table_name = $c->table->name) =~ s/^.+?\.//; # table name may not specify schema
355 warn "removing schema name from '" . $c->table->name . "' to make '$index_table_name'\n" if $WARN;
358 "CREATE UNIQUE INDEX $name ON " . $index_table_name .
359 ' (' . join( ', ', @fields ) . ')';
365 my ($trigger, $options) = @_;
366 my $add_drop = $options->{add_drop_trigger};
368 my $name = $trigger->name;
371 push @create, "DROP TRIGGER IF EXISTS $name" if $add_drop;
373 my $events = $trigger->database_events;
374 die "Can't handle multiple events in triggers" if @$events > 1;
379 unless (ref $trigger->action) {
380 $action .= "BEGIN " . $trigger->action . " END";
382 $action = $trigger->action->{for_each} . " "
383 if $trigger->action->{for_each};
385 $action = $trigger->action->{when} . " "
386 if $trigger->action->{when};
388 my $steps = $trigger->action->{steps} || [];
397 push @create, "CREATE TRIGGER $name " .
398 $trigger->perform_action_when . " " .
400 " on " . $trigger->on_table . " " .
407 sub alter_table { } # Noop
412 return sprintf("ALTER TABLE %s ADD COLUMN %s",
413 $field->table->name, create_field($field))
416 sub alter_create_index {
419 # This might cause name collisions
420 return create_index($index);
423 sub alter_create_constraint {
424 my ($constraint) = @_;
426 return create_constraint($constraint) if $constraint->type eq 'UNIQUE';
429 sub alter_drop_constraint { alter_drop_index(@_) }
431 sub alter_drop_index {
432 my ($constraint) = @_;
434 return sprintf("DROP INDEX %s",
438 sub batch_alter_table {
439 my ($table, $diffs) = @_;
441 # If we have any of the following
447 # we need to do the following <http://www.sqlite.org/faq.html#q11>
450 # CREATE TEMPORARY TABLE t1_backup(a,b);
451 # INSERT INTO t1_backup SELECT a,b FROM t1;
453 # CREATE TABLE t1(a,b);
454 # INSERT INTO t1 SELECT a,b FROM t1_backup;
455 # DROP TABLE t1_backup;
460 # If we have rename_field we do similarly.
462 my $table_name = $table->name;
463 my $renaming = $diffs->{rename_table} && @{$diffs->{rename_table}};
465 if ( @{$diffs->{rename_field}} == 0 &&
466 @{$diffs->{alter_field}} == 0 &&
467 @{$diffs->{drop_field}} == 0
469 # return join("\n", map {
471 my $meth = __PACKAGE__->can($_) or die __PACKAGE__ . " cant $_";
472 map { my $sql = $meth->(ref $_ eq 'ARRAY' ? @$_ : $_); $sql ? ("$sql") : () } @{ $diffs->{$_} }
474 } grep { @{$diffs->{$_}} }
476 alter_drop_constraint
483 alter_create_constraint
489 my $old_table = $renaming ? $diffs->{rename_table}[0][0] : $table;
492 local $table->{name} = $table_name . '_temp_alter';
493 # We only want the table - dont care about indexes on tmp table
494 my ($table_sql) = create_table($table, {no_comments => 1, temporary_table => 1});
495 push @sql,$table_sql;
498 push @sql, "INSERT INTO @{[$table_name]}_temp_alter SELECT @{[ join(', ', $old_table->get_fields)]} FROM @{[$old_table]}",
499 "DROP TABLE @{[$old_table]}",
500 create_table($table, { no_comments => 1 }),
501 "INSERT INTO @{[$table_name]} SELECT @{[ join(', ', $old_table->get_fields)]} FROM @{[$table_name]}_temp_alter",
502 "DROP TABLE @{[$table_name]}_temp_alter";
505 # return join("", @sql, "");
510 return "DROP TABLE $table";
514 my ($old_table, $new_table, $options) = @_;
516 my $qt = $options->{quote_table_names} || '';
518 return "ALTER TABLE $qt$old_table$qt RENAME TO $qt$new_table$qt";
522 # No-op. Just here to signify that we are a new style parser.
523 sub preproces_schema { }
531 SQL::Translator, http://www.sqlite.org/.
535 Ken Y. Clark C<< <kclark@cpan.orgE> >>.
537 Diff code added by Ash Berlin C<< <ash@cpan.org> >>.