1package Class::DBI::SQLite;
2
3use strict;
4use vars qw($VERSION);
5$VERSION = "0.11";
6
7require Class::DBI;
8use base qw(Class::DBI);
9
10sub _auto_increment_value {
11    my $self = shift;
12    return $self->db_Main->func("last_insert_rowid");
13}
14
15sub set_up_table {
16    my($class, $table) = @_;
17
18    # find all columns.
19    my $sth = $class->db_Main->prepare("PRAGMA table_info('$table')");
20    $sth->execute();
21    my @columns;
22    while (my $row = $sth->fetchrow_hashref) {
23	push @columns, $row->{name};
24    }
25    $sth->finish;
26
27    # find primary key. so complex ;-(
28    $sth = $class->db_Main->prepare(<<'SQL');
29SELECT sql FROM sqlite_master WHERE tbl_name = ?
30SQL
31    $sth->execute($table);
32    my($sql) = $sth->fetchrow_array;
33    $sth->finish;
34    my ($primary) = $sql =~ m/
35    (?:\(|\,) # either a ( to start the definition or a , for next
36    \s*       # maybe some whitespace
37    (\w+)     # the col name
38    [^,]*     # anything but the end or a ',' for next column
39    PRIMARY\sKEY/sxi;
40    my @pks;
41    if ($primary) {
42        @pks = ($primary);
43    } else {
44        my ($pks)= $sql =~ m/PRIMARY\s+KEY\s*\(\s*([^)]+)\s*\)/;
45        @pks = split(m/\s*\,\s*/, $pks) if $pks;
46    }
47    $class->table($table);
48    $class->columns(Primary => @pks);
49    $class->columns(All => @columns);
50}
51
521;
53
54__END__
55
56=head1 NAME
57
58Class::DBI::SQLite - Extension to Class::DBI for sqlite
59
60=head1 SYNOPSIS
61
62  package Film;
63  use base qw(Class::DBI::SQLite);
64  __PACKAGE__->set_db('Main', 'dbi:SQLite:dbname=dbfile', '', '');
65  __PACKAGE__->set_up_table('Movies');
66
67  package main;
68  my $film = Film->create({
69     name  => 'Bad Taste',
70     title => 'Peter Jackson',
71  });
72  my $id = $film->id;		# auto-incremented
73
74=head1 DESCRIPTION
75
76Class::DBI::SQLite is an extension to Class::DBI for DBD::SQLite.
77It allows you to populate an auto-incremented row id after insert.
78
79The C<set_up_table> method automates the setup of columns and
80primary key(s) via the SQLite PRAGMA statement.
81
82=head1 AUTHOR
83
84Tatsuhiko Miyagawa E<lt>miyagawa@bulknews.netE<gt>
85
86C<set_up_table> implementation by Tomohiro Ikebe E<lt>ikebe@cpan.orgE<gt>
87
88This library is free software; you can redistribute it and/or modify
89it under the same terms as Perl itself.
90
91=head1 SEE ALSO
92
93L<Class::DBI>, L<DBD::SQLite>
94
95=cut
96