1 package SQL::Translator::Producer::SQLite;
5 SQL::Translator::Producer::SQLite - SQLite producer for SQL::Translator
11 my $t = SQL::Translator->new( parser => '...', producer => 'SQLite' );
16 This module will produce text output of the schema suitable for SQLite.
23 use SQL::Translator::Schema::Constants;
24 use SQL::Translator::Utils qw(debug header_comment parse_dbms_version batch_alter_table_statements);
25 use SQL::Translator::Generator::DDL::SQLite;
27 our ( $DEBUG, $WARN );
28 our $VERSION = '1.59';
29 $DEBUG = 0 unless defined $DEBUG;
30 $WARN = 0 unless defined $WARN;
32 our $max_id_length = 30;
35 # HIDEOUS TEMPORARY DEFAULT WITHOUT QUOTING!
39 my ($quoting_generator, $nonquoting_generator);
42 ? $nonquoting_generator ||= SQL::Translator::Generator::DDL::SQLite->new(quote_chars => [])
43 : $quoting_generator ||= SQL::Translator::Generator::DDL::SQLite->new
48 my $translator = shift;
49 local $DEBUG = $translator->debug;
50 local $WARN = $translator->show_warnings;
51 my $no_comments = $translator->no_comments;
52 my $add_drop_table = $translator->add_drop_table;
53 my $schema = $translator->schema;
54 my $producer_args = $translator->producer_args;
55 my $sqlite_version = parse_dbms_version(
56 $producer_args->{sqlite_version}, 'perl'
58 my $no_txn = $producer_args->{no_transaction};
60 debug("PKG: Beginning production\n");
62 %global_names = (); #reset
64 # only quote if quotes were requested for real
65 # 0E0 indicates "the default of true" was assumed
67 if $translator->quote_identifiers and $translator->quote_identifiers ne '0E0';
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 ),
109 my ($name, $scope, $critical) = @_;
111 $scope ||= \%global_names;
112 if ( my $prev = $scope->{ $name } ) {
113 my $name_orig = $name;
114 $name .= sprintf( "%02d", ++$prev );
115 substr($name, $max_id_length - 3) = "00"
116 if length( $name ) > $max_id_length;
118 warn "The name '$name_orig' has been changed to ",
119 "'$name' to make it unique.\n" if $WARN;
121 $scope->{ $name_orig }++;
125 return _generator()->quote($name);
129 my ($view, $options) = @_;
130 my $add_drop_view = $options->{add_drop_view};
132 my $view_name = _generator()->quote($view->name);
133 $global_names{$view->name} = 1;
135 debug("PKG: Looking at view '${view_name}'\n");
137 # Header. Should this look like what mysqldump produces?
138 my $extra = $view->extra;
140 push @create, "DROP VIEW IF EXISTS $view_name" if $add_drop_view;
142 my $create_view = 'CREATE';
143 $create_view .= " TEMPORARY" if exists($extra->{temporary}) && $extra->{temporary};
144 $create_view .= ' VIEW';
145 $create_view .= " IF NOT EXISTS" if exists($extra->{if_not_exists}) && $extra->{if_not_exists};
146 $create_view .= " ${view_name}";
148 if( my $sql = $view->sql ){
149 $create_view .= " AS\n ${sql}";
151 push @create, $create_view;
153 # Tack the comment onto the first statement.
154 unless ($options->{no_comments}) {
155 $create[0] = "--\n-- View: ${view_name}\n--\n" . $create[0];
164 my ($table, $options) = @_;
166 my $table_name = _generator()->quote($table->name);
167 $global_names{$table->name} = 1;
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.003) ? ' 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(', ', map _generator()->quote($_), @pk_fields ) . ')';
228 for my $index ( $table->get_indices ) {
229 push @index_defs, create_index($index);
235 for my $c ( $table->get_constraints ) {
236 if ($c->type eq "FOREIGN KEY") {
237 push @field_defs, create_foreignkey($c);
239 elsif ($c->type eq "CHECK") {
240 push @field_defs, create_check_constraint($c);
242 next unless $c->type eq UNIQUE;
243 push @constraint_defs, create_constraint($c);
246 $create_table .= join(",\n", map { " $_" } @field_defs ) . "\n)";
248 return (@create, $create_table, @index_defs, @constraint_defs );
251 sub create_check_constraint {
254 $check .= 'CONSTRAINT ' . _generator->quote( $c->name ) . ' ' if $c->name;
255 $check .= 'CHECK(' . $c->expression . ')';
259 sub create_foreignkey {
262 my @fields = $c->fields;
263 my @rfields = map { $_ || () } $c->reference_fields;
264 unless ( @rfields ) {
265 my $rtable_name = $c->reference_table;
266 if ( my $ref_table = $c->schema->get_table( $rtable_name ) ) {
267 push @rfields, $ref_table->primary_key;
269 die "FK constraint on " . $rtable_name . '.' . join('', @fields) . " has no reference fields\n"
273 die "Can't find reference table '$rtable_name' in schema\n";
277 my $fk_sql = sprintf 'FOREIGN KEY (%s) REFERENCES %s(%s)',
278 join (', ', map { _generator()->quote($_) } @fields ),
279 _generator()->quote($c->reference_table),
280 join (', ', map { _generator()->quote($_) } @rfields )
283 $fk_sql .= " ON DELETE " . $c->{on_delete} if $c->{on_delete};
284 $fk_sql .= " ON UPDATE " . $c->{on_update} if $c->{on_update};
289 sub create_field { return _generator()->field($_[0]) }
293 my ($index, $options) = @_;
295 (my $index_table_name = $index->table->name) =~ s/^.+?\.//; # table name may not specify schema
296 my $name = mk_name($index->name || "${index_table_name}_idx");
298 my $type = $index->type eq 'UNIQUE' ? "UNIQUE " : '';
300 # strip any field size qualifiers as SQLite doesn't like these
301 my @fields = map { s/\(\d+\)$//; _generator()->quote($_) } $index->fields;
302 $index_table_name = _generator()->quote($index_table_name);
303 warn "removing schema name from '" . $index->table->name . "' to make '$index_table_name'\n" if $WARN;
305 "CREATE ${type}INDEX $name ON " . $index_table_name .
306 ' (' . join( ', ', @fields ) . ')';
311 sub create_constraint
313 my ($c, $options) = @_;
315 (my $index_table_name = $c->table->name) =~ s/^.+?\.//; # table name may not specify schema
316 my $name = mk_name($c->name || "${index_table_name}_idx");
317 my @fields = map _generator()->quote($_), $c->fields;
318 $index_table_name = _generator()->quote($index_table_name);
319 warn "removing schema name from '" . $c->table->name . "' to make '$index_table_name'\n" if $WARN;
322 "CREATE UNIQUE INDEX $name ON " . $index_table_name .
323 ' (' . join( ', ', @fields ) . ')';
329 my ($trigger, $options) = @_;
330 my $add_drop = $options->{add_drop_trigger};
334 my $trigger_name = $trigger->name;
335 $global_names{$trigger_name} = 1;
337 my $events = $trigger->database_events;
338 for my $evt ( @$events ) {
340 my $trig_name = $trigger_name;
342 $trig_name .= "_$evt";
344 warn "Multiple database events supplied for trigger '$trigger_name', ",
345 "creating trigger '$trig_name' for the '$evt' event.\n" if $WARN;
348 $trig_name = _generator()->quote($trig_name);
349 push @statements, "DROP TRIGGER IF EXISTS $trig_name" if $add_drop;
354 if (not ref $trigger->action) {
355 $action = $trigger->action;
356 $action = "BEGIN " . $action . " END"
357 unless $action =~ /^ \s* BEGIN [\s\;] .*? [\s\;] END [\s\;]* $/six;
360 $action = $trigger->action->{for_each} . " "
361 if $trigger->action->{for_each};
363 $action = $trigger->action->{when} . " "
364 if $trigger->action->{when};
366 my $steps = $trigger->action->{steps} || [];
369 $action .= $_ . "; " for (@$steps);
373 push @statements, sprintf (
374 'CREATE TRIGGER %s %s %s on %s %s',
376 $trigger->perform_action_when,
378 _generator()->quote($trigger->on_table),
386 sub alter_table { () } # Noop
391 return sprintf("ALTER TABLE %s ADD COLUMN %s",
392 _generator()->quote($field->table->name), create_field($field))
395 sub alter_create_index {
398 # This might cause name collisions
399 return create_index($index);
402 sub alter_create_constraint {
403 my ($constraint) = @_;
405 return create_constraint($constraint) if $constraint->type eq 'UNIQUE';
408 sub alter_drop_constraint { alter_drop_index(@_) }
410 sub alter_drop_index {
411 my ($constraint) = @_;
413 return sprintf("DROP INDEX %s",
414 _generator()->quote($constraint->name));
417 sub batch_alter_table {
418 my ($table, $diffs, $options) = @_;
420 # If we have any of the following
426 # we need to do the following <http://www.sqlite.org/faq.html#q11>
429 # CREATE TEMPORARY TABLE t1_backup(a,b);
430 # INSERT INTO t1_backup SELECT a,b FROM t1;
432 # CREATE TABLE t1(a,b);
433 # INSERT INTO t1 SELECT a,b FROM t1_backup;
434 # DROP TABLE t1_backup;
439 # If we have rename_field we do similarly.
441 # We create the temporary table as a copy of the new table, copy all data
442 # to temp table, create new table and then copy as appropriate taking note
445 my $table_name = $table->name;
447 if ( @{$diffs->{rename_field}} == 0 &&
448 @{$diffs->{alter_field}} == 0 &&
449 @{$diffs->{drop_field}} == 0
451 return batch_alter_table_statements($diffs, $options);
456 # $table is the new table but we may need an old one
457 # TODO: this is NOT very well tested at the moment so add more tests
459 my $old_table = $table;
461 if ( $diffs->{rename_table} && @{$diffs->{rename_table}} ) {
462 $old_table = $diffs->{rename_table}[0][0];
465 my $temp_table_name = $table_name . '_temp_alter';
467 # CREATE TEMPORARY TABLE t1_backup(a,b);
469 my %temp_table_fields;
471 local $table->{name} = $temp_table_name;
472 # We only want the table - don't care about indexes on tmp table
473 my ($table_sql) = create_table($table, {no_comments => 1, temporary_table => 1});
474 push @sql,$table_sql;
476 %temp_table_fields = map { $_ => 1} $table->get_fields;
479 # record renamed fields for later
480 my %rename_field = map { $_->[1]->name => $_->[0]->name } @{$diffs->{rename_field}};
482 # drop added fields from %temp_table_fields
483 delete @temp_table_fields{@{$diffs->{add_field}}};
485 # INSERT INTO t1_backup SELECT a,b FROM t1;
487 push @sql, sprintf( 'INSERT INTO %s( %s) SELECT %s FROM %s',
489 _generator()->quote( $temp_table_name ),
492 map _generator()->quote($_),
493 grep { $temp_table_fields{$_} } $table->get_fields ),
496 map _generator()->quote($_),
497 map { $rename_field{$_} ? $rename_field{$_} : $_ }
498 grep { $temp_table_fields{$_} } $table->get_fields ),
500 _generator()->quote( $old_table->name )
505 push @sql, sprintf('DROP TABLE %s', _generator()->quote($old_table->name));
507 # CREATE TABLE t1(a,b);
509 push @sql, create_table($table, { no_comments => 1 });
511 # INSERT INTO t1 SELECT a,b FROM t1_backup;
513 push @sql, sprintf('INSERT INTO %s SELECT %s FROM %s',
514 _generator()->quote($table_name),
515 join(', ', map _generator()->quote($_), $table->get_fields),
516 _generator()->quote($temp_table_name)
519 # DROP TABLE t1_backup;
521 push @sql, sprintf('DROP TABLE %s', _generator()->quote($temp_table_name));
523 return wantarray ? @sql : join(";\n", @sql);
528 $table = _generator()->quote($table);
529 return "DROP TABLE $table";
533 my ($old_table, $new_table, $options) = @_;
535 $old_table = _generator()->quote($old_table);
536 $new_table = _generator()->quote($new_table);
538 return "ALTER TABLE $old_table RENAME TO $new_table";
542 # No-op. Just here to signify that we are a new style parser.
543 sub preproces_schema { }
551 SQL::Translator, http://www.sqlite.org/.
555 Ken Youens-Clark C<< <kclark@cpan.orgE> >>.
557 Diff code added by Ash Berlin C<< <ash@cpan.org> >>.