File: SQLite.pm

package info (click to toggle)
sqlfairy 0.07-5
  • links: PTS
  • area: main
  • in suites: etch, etch-m68k
  • size: 3,672 kB
  • ctags: 1,470
  • sloc: perl: 55,380; sql: 2,106; xml: 68; makefile: 4
file content (255 lines) | stat: -rw-r--r-- 7,821 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
package SQL::Translator::Producer::SQLite;

# -------------------------------------------------------------------
# $Id: SQLite.pm,v 1.11 2004/03/16 13:29:11 kycl4rk Exp $
# -------------------------------------------------------------------
# Copyright (C) 2002-4 SQLFairy Authors
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; version 2.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
# 02111-1307  USA
# -------------------------------------------------------------------

=head1 NAME

SQL::Translator::Producer::SQLite - SQLite producer for SQL::Translator

=head1 SYNOPSIS

  use SQL::Translator;

  my $t = SQL::Translator->new( parser => '...', producer => 'SQLite' );
  $t->translate;

=head1 DESCRIPTION

This module will produce text output of the schema suitable for SQLite.

=cut

use strict;
use Data::Dumper;
use SQL::Translator::Schema::Constants;
use SQL::Translator::Utils qw(debug header_comment);

use vars qw[ $VERSION $DEBUG $WARN ];

$VERSION = sprintf "%d.%02d", q$Revision: 1.11 $ =~ /(\d+)\.(\d+)/;
$DEBUG = 0 unless defined $DEBUG;
$WARN = 0 unless defined $WARN;

my %used_identifiers = ();
my $max_id_length    = 30;
my %global_names;
my %truncated;

sub produce {
    my $translator     = shift;
    local $DEBUG       = $translator->debug;
    local $WARN        = $translator->show_warnings;
    my $no_comments    = $translator->no_comments;
    my $add_drop_table = $translator->add_drop_table;
    my $schema         = $translator->schema;

    debug("PKG: Beginning production\n");

    my $create = '';
    $create .= header_comment unless ($no_comments);
    $create .= "BEGIN TRANSACTION;\n\n";

    my ( @index_defs, @constraint_defs, @trigger_defs );
    for my $table ( $schema->get_tables ) {
        my $table_name = $table->name;
        debug("PKG: Looking at table '$table_name'\n");

        my @fields = $table->get_fields or die "No fields in $table_name";

        #
        # Header.
        #
        $create .= "--\n-- Table: $table_name\n--\n" unless $no_comments;
        $create .= qq[DROP TABLE $table_name;\n] if $add_drop_table;
        $create .= "CREATE TABLE $table_name (\n";

        #
        # How many fields in PK?
        #
        my $pk        = $table->primary_key;
        my @pk_fields = $pk ? $pk->fields : ();

        #
        # Fields
        #
        my ( @field_defs, $pk_set );
        for my $field ( @fields ) {
            my $field_name = $field->name;
            debug("PKG: Looking at field '$field_name'\n");
            my $field_def = $field_name;

            # data type and size
            my $size      = $field->size;
            my $data_type = $field->data_type;
            $data_type    = 'varchar' if lc $data_type eq 'set';

            if ( $data_type =~ /timestamp/i ) {
                push @trigger_defs, 
                    "CREATE TRIGGER ts_${table_name} ".
                    "after insert on $table_name\n".
                    "begin\n".
                    "  update $table_name set $field_name=timestamp() ".
                       "where id=new.id;\n".
                    "end;\n"
                ;

            }

            #
            # SQLite is generally typeless, but newer versions will
            # make a field autoincrement if it is declared as (and
            # *only* as) INTEGER PRIMARY KEY
            #
            if ( 
                $field->is_primary_key && 
                scalar @pk_fields == 1 &&
                (
                    $data_type =~ /int(eger)?$/i
                    ||
                    ( $data_type =~ /^number?$/i && $size !~ /,/ )
                )
            ) {
                $data_type = 'INTEGER PRIMARY KEY';
                $size      = undef;
                $pk_set    = 1;
            }

            $field_def .= sprintf " %s%s", $data_type, 
                ( !$field->is_auto_increment && $size ) ? "($size)" : '';

            # Null?
            $field_def .= ' NOT NULL' unless $field->is_nullable;

            # Default?  XXX Need better quoting!
            my $default = $field->default_value;
            if ( defined $default ) {
                if ( uc $default eq 'NULL') {
                    $field_def .= ' DEFAULT NULL';
                } else {
                    $field_def .= " DEFAULT '$default'";
                }
            }

            push @field_defs, $field_def;
        }

        if ( 
            scalar @pk_fields > 1 
            || 
            ( @pk_fields && !$pk_set ) 
        ) {
            push @field_defs, 'PRIMARY KEY (' . join(', ', @pk_fields ) . ')';
        }

        #
        # Indices
        #
        my $idx_name_default = 'A';
        for my $index ( $table->get_indices ) {
            my $name   = $index->name;
            $name      = mk_name($table_name, $name || ++$idx_name_default);

            # strip any field size qualifiers as SQLite doesn't like these
            my @fields = map { s/\(\d+\)$//; $_ } $index->fields;
            push @index_defs, 
                "CREATE INDEX $name on $table_name ".
                '(' . join( ', ', @fields ) . ');';
        }

        #
        # Constraints
        #
        my $c_name_default = 'A';
        for my $c ( $table->get_constraints ) {
            next unless $c->type eq UNIQUE; 
            my $name   = $c->name;
            $name      = mk_name($table_name, $name || ++$idx_name_default);
            my @fields = $c->fields;

            push @constraint_defs, 
                "CREATE UNIQUE INDEX $name on $table_name ".
                '(' . join( ', ', @fields ) . ');';
        }

        $create .= join(",\n", map { "  $_" } @field_defs ) . "\n);\n";

        $create .= "\n";
    }

    for my $def ( @index_defs, @constraint_defs, @trigger_defs ) {
        $create .= "$def\n";
    }

    $create .= "COMMIT;\n";

    return $create;
}

# -------------------------------------------------------------------
sub mk_name {
    my ($basename, $type, $scope, $critical) = @_;
    my $basename_orig = $basename;
    my $max_name      = $type 
                        ? $max_id_length - (length($type) + 1) 
                        : $max_id_length;
    $basename         = substr( $basename, 0, $max_name ) 
                        if length( $basename ) > $max_name;
    my $name          = $type ? "${type}_$basename" : $basename;

    if ( $basename ne $basename_orig and $critical ) {
        my $show_type = $type ? "+'$type'" : "";
        warn "Truncating '$basename_orig'$show_type to $max_id_length ",
            "character limit to make '$name'\n" if $WARN;
        $truncated{ $basename_orig } = $name;
    }

    $scope ||= \%global_names;
    if ( my $prev = $scope->{ $name } ) {
        my $name_orig = $name;
        $name        .= sprintf( "%02d", ++$prev );
        substr($name, $max_id_length - 3) = "00" 
            if length( $name ) > $max_id_length;

        warn "The name '$name_orig' has been changed to ",
             "'$name' to make it unique.\n" if $WARN;

        $scope->{ $name_orig }++;
    }

    $scope->{ $name }++;
    return $name;
}

1;

# -------------------------------------------------------------------

=pod

=head1 SEE ALSO

SQL::Translator, http://www.sqlite.org/.

=head1 AUTHOR

Ken Y. Clark E<lt>kclark@cpan.orgE<gt>.

=cut