1 package DBIx::Class::Loader::SQLite;
4 use base 'DBIx::Class::Loader::Generic';
5 use Text::Balanced qw( extract_bracketed );
11 DBIx::Class::Loader::SQLite - DBIx::Class::Loader SQLite Implementation.
15 use DBIx::Class::Loader;
17 # $loader is a DBIx::Class::Loader::SQLite
18 my $loader = DBIx::Class::Loader->new(
19 dsn => "dbi:SQLite:dbname=/path/to/dbfile",
22 my $class = $loader->find_class('film'); # $class => Data::Film
23 my $obj = $class->retrieve(1);
27 See L<DBIx::Class::Loader>.
32 return qw/DBIx::Class::PK::Auto::SQLite/;
37 foreach my $table ( $self->tables ) {
39 my $dbh = $self->{_storage}->dbh;
40 my $sth = $dbh->prepare(<<"");
41 SELECT sql FROM sqlite_master WHERE tbl_name = ?
43 $sth->execute($table);
44 my ($sql) = $sth->fetchrow_array;
47 # Cut "CREATE TABLE ( )" blabla...
48 $sql =~ /^[\w\s]+\((.*)\)$/si;
51 # strip single-line comments
52 $cols =~ s/\-\-.*\n/\n/g;
54 # temporarily replace any commas inside parens,
55 # so we don't incorrectly split on them below
56 my $cols_no_bracketed_commas = $cols;
57 while ( my $extracted =
58 ( extract_bracketed( $cols, "()", "[^(]*" ) )[0] )
60 my $replacement = $extracted;
61 $replacement =~ s/,/--comma--/g;
62 $replacement =~ s/^\(//;
63 $replacement =~ s/\)$//;
64 $cols_no_bracketed_commas =~ s/$extracted/$replacement/m;
67 # Split column definitions
68 for my $col ( split /,/, $cols_no_bracketed_commas ) {
70 # put the paren-bracketed commas back, to help
71 # find multi-col fks below
72 $col =~ s/\-\-comma\-\-/,/g;
74 # CDBI doesn't have built-in support multi-col fks, so ignore them
75 next if $col =~ s/^\s*FOREIGN\s+KEY\s*//i && $col =~ /^\([^,)]+,/;
77 # Strip punctuations around key and table names
78 $col =~ s/[()\[\]'"]/ /g;
82 if ( $col =~ /^(\w+).*REFERENCES\s+(\w+)\s*(\w+)?/i ) {
84 warn qq/\# Found foreign key definition "$col"\n\n/
86 eval { $self->_belongs_to_many( $table, $1, $2, $3 ) };
87 warn qq/\# belongs_to_many failed "$@"\n\n/
88 if $@ && $self->debug;
96 my $dbh = $self->{_storage}->dbh;
97 my $sth = $dbh->prepare("SELECT * FROM sqlite_master");
100 while ( my $row = $sth->fetchrow_hashref ) {
101 next unless lc( $row->{type} ) eq 'table';
102 push @tables, $row->{tbl_name};
108 my ( $self, $table ) = @_;
111 my $dbh = $self->{_storage}->dbh;
112 my $sth = $dbh->prepare("PRAGMA table_info('$table')");
115 while ( my $row = $sth->fetchrow_hashref ) {
116 push @columns, $row->{name};
120 # find primary key. so complex ;-(
121 $sth = $dbh->prepare(<<'SQL');
122 SELECT sql FROM sqlite_master WHERE tbl_name = ?
124 $sth->execute($table);
125 my ($sql) = $sth->fetchrow_array;
127 my ($primary) = $sql =~ m/
128 (?:\(|\,) # either a ( to start the definition or a , for next
129 \s* # maybe some whitespace
131 [^,]* # anything but the end or a ',' for next column
139 my ($pks) = $sql =~ m/PRIMARY\s+KEY\s*\(\s*([^)]+)\s*\)/;
140 @pks = split( m/\s*\,\s*/, $pks ) if $pks;
142 return ( \@columns, \@pks );
147 L<DBIx::Class::Loader>