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 $max_id_length = 30;
54 my $translator = shift;
55 local $DEBUG = $translator->debug;
56 local $WARN = $translator->show_warnings;
57 my $no_comments = $translator->no_comments;
58 my $add_drop_table = $translator->add_drop_table;
59 my $schema = $translator->schema;
60 my $producer_args = $translator->producer_args;
61 my $sqlite_version = $producer_args->{sqlite_version} || 0;
62 my $no_txn = $producer_args->{no_transaction};
64 debug("PKG: Beginning production\n");
66 %global_names = (); #reset
69 my $head = (header_comment() . "\n") unless $no_comments;
73 push @create, "BEGIN TRANSACTION" unless $no_txn;
75 for my $table ( $schema->get_tables ) {
76 push @create, create_table($table, { no_comments => $no_comments,
77 sqlite_version => $sqlite_version,
78 add_drop_table => $add_drop_table,});
81 for my $view ( $schema->get_views ) {
82 push @create, create_view($view, {
83 add_drop_view => $add_drop_table,
84 no_comments => $no_comments,
88 for my $trigger ( $schema->get_triggers ) {
89 push @create, create_trigger($trigger, {
90 add_drop_trigger => $add_drop_table,
91 no_comments => $no_comments,
95 push @create, "COMMIT" unless $no_txn;
98 return ($head||(), @create);
102 join(";\n\n", @create ),
108 # -------------------------------------------------------------------
110 my ($name, $scope, $critical) = @_;
112 $scope ||= \%global_names;
113 if ( my $prev = $scope->{ $name } ) {
114 my $name_orig = $name;
115 $name .= sprintf( "%02d", ++$prev );
116 substr($name, $max_id_length - 3) = "00"
117 if length( $name ) > $max_id_length;
119 warn "The name '$name_orig' has been changed to ",
120 "'$name' to make it unique.\n" if $WARN;
122 $scope->{ $name_orig }++;
130 my ($view, $options) = @_;
131 my $add_drop_view = $options->{add_drop_view};
133 my $view_name = $view->name;
134 debug("PKG: Looking at view '${view_name}'\n");
136 # Header. Should this look like what mysqldump produces?
137 my $extra = $view->extra;
139 $create .= "--\n-- View: ${view_name}\n--\n" unless $options->{no_comments};
140 $create .= "DROP VIEW IF EXISTS $view_name;\n" if $add_drop_view;
142 $create .= " TEMPORARY" if exists($extra->{temporary}) && $extra->{temporary};
144 $create .= " IF NOT EXISTS" if exists($extra->{if_not_exists}) && $extra->{if_not_exists};
145 $create .= " ${view_name}";
147 if( my $sql = $view->sql ){
148 $create .= " AS\n ${sql}";
156 my ($table, $options) = @_;
158 my $table_name = $table->name;
159 my $no_comments = $options->{no_comments};
160 my $add_drop_table = $options->{add_drop_table};
161 my $sqlite_version = $options->{sqlite_version} || 0;
163 debug("PKG: Looking at table '$table_name'\n");
165 my ( @index_defs, @constraint_defs );
166 my @fields = $table->get_fields or die "No fields in $table_name";
168 my $temp = $options->{temporary_table} ? 'TEMPORARY ' : '';
172 my $exists = ($sqlite_version >= 3.3) ? ' IF EXISTS' : '';
174 my ($comment, $create_table) = "";
175 $comment = "--\n-- Table: $table_name\n--\n" unless $no_comments;
176 if ($add_drop_table) {
177 push @create, $comment . qq[DROP TABLE$exists $table_name];
179 $create_table = $comment;
182 $create_table .= "CREATE ${temp}TABLE $table_name (\n";
187 if ( $table->comments and !$no_comments ){
188 $create_table .= "-- Comments: \n-- ";
189 $create_table .= join "\n-- ", $table->comments;
190 $create_table .= "\n--\n\n";
194 # How many fields in PK?
196 my $pk = $table->primary_key;
197 my @pk_fields = $pk ? $pk->fields : ();
202 my ( @field_defs, $pk_set );
203 for my $field ( @fields ) {
204 push @field_defs, create_field($field);
208 scalar @pk_fields > 1
210 ( @pk_fields && !grep /INTEGER PRIMARY KEY/, @field_defs )
212 push @field_defs, 'PRIMARY KEY (' . join(', ', @pk_fields ) . ')';
218 my $idx_name_default = 'A';
219 for my $index ( $table->get_indices ) {
220 push @index_defs, create_index($index);
226 my $c_name_default = 'A';
227 for my $c ( $table->get_constraints ) {
228 next unless $c->type eq UNIQUE;
229 push @constraint_defs, create_constraint($c);
232 $create_table .= join(",\n", map { " $_" } @field_defs ) . "\n)";
234 return (@create, $create_table, @index_defs, @constraint_defs );
239 my ($field, $options) = @_;
241 my $field_name = $field->name;
242 debug("PKG: Looking at field '$field_name'\n");
243 my $field_comments = $field->comments
244 ? "-- " . $field->comments . "\n "
247 my $field_def = $field_comments.$field_name;
250 my $size = $field->size;
251 my $data_type = $field->data_type;
252 $data_type = 'varchar' if lc $data_type eq 'set';
253 $data_type = 'blob' if lc $data_type eq 'bytea';
255 if ( lc $data_type =~ /(text|blob)/i ) {
259 # if ( $data_type =~ /timestamp/i ) {
260 # push @trigger_defs,
261 # "CREATE TRIGGER ts_${table_name} ".
262 # "after insert on $table_name\n".
264 # " update $table_name set $field_name=timestamp() ".
265 # "where id=new.id;\n".
272 # SQLite is generally typeless, but newer versions will
273 # make a field autoincrement if it is declared as (and
274 # *only* as) INTEGER PRIMARY KEY
276 my $pk = $field->table->primary_key;
277 my @pk_fields = $pk ? $pk->fields : ();
280 $field->is_primary_key &&
281 scalar @pk_fields == 1 &&
283 $data_type =~ /int(eger)?$/i
285 ( $data_type =~ /^number?$/i && $size !~ /,/ )
288 $data_type = 'INTEGER PRIMARY KEY';
293 $field_def .= sprintf " %s%s", $data_type,
294 ( !$field->is_auto_increment && $size ) ? "($size)" : '';
297 $field_def .= ' NOT NULL' unless $field->is_nullable;
299 # Default? XXX Need better quoting!
300 my $default = $field->default_value;
301 if (defined $default) {
302 SQL::Translator::Producer->_apply_default_value(
308 'CURRENT_TIMESTAMP' => 'CURRENT_TIMESTAMP',
319 my ($index, $options) = @_;
321 my $name = $index->name;
322 $name = mk_name($name);
324 my $type = $index->type eq 'UNIQUE' ? "UNIQUE " : '';
326 # strip any field size qualifiers as SQLite doesn't like these
327 my @fields = map { s/\(\d+\)$//; $_ } $index->fields;
328 (my $index_table_name = $index->table->name) =~ s/^.+?\.//; # table name may not specify schema
329 warn "removing schema name from '" . $index->table->name . "' to make '$index_table_name'\n" if $WARN;
331 "CREATE ${type}INDEX $name ON " . $index_table_name .
332 ' (' . join( ', ', @fields ) . ')';
337 sub create_constraint
339 my ($c, $options) = @_;
342 $name = mk_name($name);
343 my @fields = $c->fields;
344 (my $index_table_name = $c->table->name) =~ s/^.+?\.//; # table name may not specify schema
345 warn "removing schema name from '" . $c->table->name . "' to make '$index_table_name'\n" if $WARN;
348 "CREATE UNIQUE INDEX $name ON " . $index_table_name .
349 ' (' . join( ', ', @fields ) . ')';
355 my ($trigger, $options) = @_;
356 my $add_drop = $options->{add_drop_trigger};
360 my $trigger_name = $trigger->name;
361 my $events = $trigger->database_events;
362 for my $evt ( @$events ) {
364 my $trig_name = $trigger_name;
366 $trig_name .= "_$evt";
368 warn "Multiple database events supplied for trigger '$trigger_name', ",
369 "creating trigger '$trig_name' for the '$evt' event.\n" if $WARN;
372 push @statements, "DROP TRIGGER IF EXISTS $trig_name" if $add_drop;
377 if (not ref $trigger->action) {
378 $action .= "BEGIN " . $trigger->action . " END";
381 $action = $trigger->action->{for_each} . " "
382 if $trigger->action->{for_each};
384 $action = $trigger->action->{when} . " "
385 if $trigger->action->{when};
387 my $steps = $trigger->action->{steps} || [];
390 $action .= $_ . "; " for (@$steps);
394 push @statements, sprintf (
395 'CREATE TRIGGER %s %s %s on %s %s',
397 $trigger->perform_action_when,
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 Youens-Clark C<< <kclark@cpan.orgE> >>.
537 Diff code added by Ash Berlin C<< <ash@cpan.org> >>.