1DBD::SQLite(3)        User Contributed Perl Documentation       DBD::SQLite(3)
2
3
4

NAME

6       DBD::SQLite - Self Contained RDBMS in a DBI Driver
7

SYNOPSIS

9         use DBI;
10         my $dbh = DBI->connect("dbi:SQLite:dbname=dbfile","","");
11

DESCRIPTION

13       SQLite is a public domain RDBMS database engine that you can find at
14       http://www.hwaci.com/sw/sqlite/.
15
16       Rather than ask you to install SQLite first, because SQLite is public
17       domain, DBD::SQLite includes the entire thing in the distribution. So
18       in order to get a fast transaction capable RDBMS working for your perl
19       project you simply have to install this module, and nothing else.
20
21       SQLite supports the following features:
22
23       Implements a large subset of SQL92
24           See http://www.hwaci.com/sw/sqlite/lang.html for details.
25
26       A complete DB in a single disk file
27           Everything for your database is stored in a single disk file, mak‐
28           ing it easier to move things around than with DBD::CSV.
29
30       Atomic commit and rollback
31           Yes, DBD::SQLite is small and light, but it supports full transac‐
32           tions!
33
34       Extensible
35           User-defined aggregate or regular functions can be registered with
36           the SQL parser.
37
38       There's lots more to it, so please refer to the docs on the SQLite web
39       page, listed above, for SQL details. Also refer to DBI for details on
40       how to use DBI itself.
41

CONFORMANCE WITH DBI SPECIFICATION

43       The API works like every DBI module does. Please see DBI for more
44       details about core features.
45
46       Currently many statement attributes are not implemented or are limited
47       by the typeless nature of the SQLite database.
48

DRIVER PRIVATE ATTRIBUTES

50       Database Handle Attributes
51
52       sqlite_version
53           Returns the version of the SQLite library which DBD::SQLite is
54           using, e.g., "2.8.0". Can only be read.
55
56       unicode
57           If set to a true value, DBD::SQLite will turn the UTF-8 flag on for
58           all text strings coming out of the database. For more details on
59           the UTF-8 flag see perlunicode. The default is for the UTF-8 flag
60           to be turned off.
61
62           Also note that due to some bizareness in SQLite's type system (see
63           http://www.sqlite.org/datatype3.html), if you want to retain blob-
64           style behavior for some columns under "$dbh->{unicode} = 1" (say,
65           to store images in the database), you have to state so explicitely
66           using the 3-argument form of "bind_param" in DBI when doing
67           updates:
68
69               use DBI qw(:sql_types);
70               $dbh->{unicode} = 1;
71               my $sth = $dbh->prepare
72                    ("INSERT INTO mytable (blobcolumn) VALUES (?)");
73               $sth->bind_param(1, $binary_data, SQL_BLOB); # binary_data will
74               # be stored as-is.
75
76           Defining the column type as BLOB in the DDL is not sufficient.
77

DRIVER PRIVATE METHODS

79       $dbh->func('last_insert_rowid')
80
81       This method returns the last inserted rowid. If you specify an INTEGER
82       PRIMARY KEY as the first column in your table, that is the column that
83       is returned.  Otherwise, it is the hidden ROWID column. See the sqlite
84       docs for details.
85
86       Note: You can now use $dbh->last_insert_id() if you have a recent ver‐
87       sion of DBI.
88
89       $dbh->func( 'busy_timeout' )
90
91       Retrieve the current busy timeout.
92
93       $dbh->func( $ms, 'busy_timeout' )
94
95       Set the current busy timeout. The timeout is in milliseconds.
96
97       $dbh->func( $name, $argc, $func_ref, "create_function" )
98
99       This method will register a new function which will be useable in SQL
100       query. The method's parameters are:
101
102       $name
103           The name of the function. This is the name of the function as it
104           will be used from SQL.
105
106       $argc
107           The number of arguments taken by the function. If this number is
108           -1, the function can take any number of arguments.
109
110       $func_ref
111           This should be a reference to the function's implementation.
112
113       For example, here is how to define a now() function which returns the
114       current number of seconds since the epoch:
115
116           $dbh->func( 'now', 0, sub { return time }, 'create_function' );
117
118       After this, it could be use from SQL as:
119
120           INSERT INTO mytable ( now() );
121
122       $dbh->func( $name, $argc, $pkg, 'create_aggregate' )
123
124       This method will register a new aggregate function which can then used
125       from SQL. The method's parameters are:
126
127       $name
128           The name of the aggregate function, this is the name under which
129           the function will be available from SQL.
130
131       $argc
132           This is an integer which tells the SQL parser how many arguments
133           the function takes. If that number is -1, the function can take any
134           number of arguments.
135
136       $pkg
137           This is the package which implements the aggregator interface.
138
139       The aggregator interface consists of defining three methods:
140
141       new()
142           This method will be called once to create an object which should be
143           used to aggregate the rows in a particular group. The step() and
144           finalize() methods will be called upon the reference return by the
145           method.
146
147       step(@_)
148           This method will be called once for each rows in the aggregate.
149
150       finalize()
151           This method will be called once all rows in the aggregate were pro‐
152           cessed and it should return the aggregate function's result. When
153           there is no rows in the aggregate, finalize() will be called right
154           after new().
155
156       Here is a simple aggregate function which returns the variance (example
157       adapted from pysqlite):
158
159           package variance;
160
161           sub new { bless [], shift; }
162
163           sub step {
164               my ( $self, $value ) = @_;
165
166               push @$self, $value;
167           }
168
169           sub finalize {
170               my $self = $_[0];
171
172               my $n = @$self;
173
174               # Variance is NULL unless there is more than one row
175               return undef unless $n ⎪⎪ $n == 1;
176
177               my $mu = 0;
178               foreach my $v ( @$self ) {
179                   $mu += $v;
180               }
181               $mu /= $n;
182
183               my $sigma = 0;
184               foreach my $v ( @$self ) {
185                   $sigma += ($x - $mu)**2;
186               }
187               $sigma = $sigma / ($n - 1);
188
189               return $sigma;
190           }
191
192           $dbh->func( "variance", 1, 'variance', "create_aggregate" );
193
194       The aggregate function can then be used as:
195
196           SELECT group_name, variance(score) FROM results
197           GROUP BY group_name;
198

BLOBS

200       As of version 1.11, blobs should "just work" in SQLite as text columns.
201       However this will cause the data to be treated as a string, so SQL
202       statements such as length(x) will return the length of the column as a
203       NUL terminated string, rather than the size of the blob in bytes. In
204       order to store natively as a BLOB use the following code:
205
206         use DBI qw(:sql_types);
207         my $dbh = DBI->connect("dbi:sqlite:/path/to/db");
208
209         my $blob = `cat foo.jpg`;
210         my $sth = $dbh->prepare("INSERT INTO mytable VALUES (1, ?)");
211         $sth->bind_param(1, $blob, SQL_BLOB);
212         $sth->execute();
213
214       And then retreival just works:
215
216         $sth = $dbh->prepare("SELECT * FROM mytable WHERE id = 1");
217         $sth->execute();
218         my $row = $sth->fetch;
219         my $blobo = $row->[1];
220
221         # now $blobo == $blob
222

NOTES

224       To access the database from the command line, try using dbish which
225       comes with the DBI module. Just type:
226
227         dbish dbi:SQLite:foo.db
228
229       On the command line to access the file foo.db.
230
231       Alternatively you can install SQLite from the link above without con‐
232       flicting with DBD::SQLite and use the supplied "sqlite" command line
233       tool.
234

PERFORMANCE

236       SQLite is fast, very fast. I recently processed my 72MB log file with
237       it, inserting the data (400,000+ rows) by using transactions and only
238       committing every 1000 rows (otherwise the insertion is quite slow), and
239       then performing queries on the data.
240
241       Queries like count(*) and avg(bytes) took fractions of a second to
242       return, but what surprised me most of all was:
243
244         SELECT url, count(*) as count FROM access_log
245           GROUP BY url
246           ORDER BY count desc
247           LIMIT 20
248
249       To discover the top 20 hit URLs on the site (http://axkit.org), and it
250       returned within 2 seconds. I'm seriously considering switching my log
251       analysis code to use this little speed demon!
252
253       Oh yeah, and that was with no indexes on the table, on a 400MHz PIII.
254
255       For best performance be sure to tune your hdparm settings if you are
256       using linux. Also you might want to set:
257
258         PRAGMA default_synchronous = OFF
259
260       Which will prevent sqlite from doing fsync's when writing (which slows
261       down non-transactional writes significantly) at the expense of some
262       peace of mind. Also try playing with the cache_size pragma.
263

BUGS

265       Likely to be many, please use http://rt.cpan.org/ for reporting bugs.
266

AUTHOR

268       Matt Sergeant, matt@sergeant.org
269
270       Perl extension functions contributed by Francis J. Lacoste <fla‐
271       coste@logreport.org> and Wolfgang Sourdeau <wolfgang@logreport.org>
272

SEE ALSO

274       DBI.
275
276
277
278perl v5.8.8                       2006-04-09                    DBD::SQLite(3)
Impressum