1 package DBIx::Class::Schema::Loader::SQLite;
4 use base 'DBIx::Class::Schema::Loader::Generic';
5 use Text::Balanced qw( extract_bracketed );
11 DBIx::Class::Schema::Loader::SQLite - DBIx::Class::Schema::Loader SQLite Implementation.
15 use DBIx::Class::Schema::Loader;
17 # $loader is a DBIx::Class::Schema::Loader::SQLite
18 my $loader = DBIx::Class::Schema::Loader->new(
19 dsn => "dbi:SQLite:dbname=/path/to/dbfile",
25 See L<DBIx::Class::Schema::Loader>.
30 return qw/DBIx::Class::PK::Auto::SQLite/;
35 foreach my $table ( $self->tables ) {
37 my $dbh = $self->{_storage}->dbh;
38 my $sth = $dbh->prepare(<<"");
39 SELECT sql FROM sqlite_master WHERE tbl_name = ?
41 $sth->execute($table);
42 my ($sql) = $sth->fetchrow_array;
45 # Cut "CREATE TABLE ( )" blabla...
46 $sql =~ /^[\w\s]+\((.*)\)$/si;
49 # strip single-line comments
50 $cols =~ s/\-\-.*\n/\n/g;
52 # temporarily replace any commas inside parens,
53 # so we don't incorrectly split on them below
54 my $cols_no_bracketed_commas = $cols;
55 while ( my $extracted =
56 ( extract_bracketed( $cols, "()", "[^(]*" ) )[0] )
58 my $replacement = $extracted;
59 $replacement =~ s/,/--comma--/g;
60 $replacement =~ s/^\(//;
61 $replacement =~ s/\)$//;
62 $cols_no_bracketed_commas =~ s/$extracted/$replacement/m;
65 # Split column definitions
66 for my $col ( split /,/, $cols_no_bracketed_commas ) {
68 # put the paren-bracketed commas back, to help
69 # find multi-col fks below
70 $col =~ s/\-\-comma\-\-/,/g;
72 # CDBI doesn't have built-in support multi-col fks, so ignore them
73 next if $col =~ s/^\s*FOREIGN\s+KEY\s*//i && $col =~ /^\([^,)]+,/;
75 # Strip punctuations around key and table names
76 $col =~ s/[()\[\]'"]/ /g;
80 if ( $col =~ /^(\w+).*REFERENCES\s+(\w+)\s*(\w+)?/i ) {
82 warn qq/\# Found foreign key definition "$col"\n\n/
84 eval { $self->_belongs_to_many( $table, $1, $2, $3 ) };
85 warn qq/\# belongs_to_many failed "$@"\n\n/
86 if $@ && $self->debug;
94 my $dbh = $self->{_storage}->dbh;
95 my $sth = $dbh->prepare("SELECT * FROM sqlite_master");
98 while ( my $row = $sth->fetchrow_hashref ) {
99 next unless lc( $row->{type} ) eq 'table';
100 push @tables, $row->{tbl_name};
106 my ( $self, $table ) = @_;
109 my $dbh = $self->{_storage}->dbh;
110 my $sth = $dbh->prepare("PRAGMA table_info('$table')");
113 while ( my $row = $sth->fetchrow_hashref ) {
114 push @columns, $row->{name};
118 # find primary key. so complex ;-(
119 $sth = $dbh->prepare(<<'SQL');
120 SELECT sql FROM sqlite_master WHERE tbl_name = ?
122 $sth->execute($table);
123 my ($sql) = $sth->fetchrow_array;
125 my ($primary) = $sql =~ m/
126 (?:\(|\,) # either a ( to start the definition or a , for next
127 \s* # maybe some whitespace
129 [^,]* # anything but the end or a ',' for next column
137 my ($pks) = $sql =~ m/PRIMARY\s+KEY\s*\(\s*([^)]+)\s*\)/;
138 @pks = split( m/\s*\,\s*/, $pks ) if $pks;
140 return ( \@columns, \@pks );
145 L<DBIx::Schema::Class::Loader>