SQLite.pm

filter: Statementstmt 99.0% 105 / 106 Branchbran 92.5% 37 / 40 Conditioncond 68.5% 24 / 35 MC/DCmcdc 29.4% 5 / 17 Subroutinesub 100% 27 / 27 Podpod 100% 4 / 4 totaltotal 88.2% 202 / 229 CC 33 SCAR 18.4
CC
33
Cov
92%
from_string
14.7
_dequeue
9.2
_prepare
5.1
CRAP 6.3
↑ Summary SQLite/Migrations.pm »
1 package Mojo::SQLite;
2 6 ▶use Mojo::Base 'Mojo::EventEmitter';
Subroutine BEGIN: called CC=1 SCAR=0.0
3  
4 6 ▶use Carp 'croak';
Subroutine BEGIN: called CC=1 SCAR=0.0
5 6 ▶use DBI;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 6 ▶use DBD::SQLite;
Subroutine BEGIN: called CC=1 SCAR=0.0
7 6 ▶use DBD::SQLite::Constants qw(:database_connection_configuration_options :dbd_sqlite_string_mode);
Subroutine BEGIN: called CC=1 SCAR=0.0
8 6 ▶use File::Spec::Functions 'catfile';
Subroutine BEGIN: called CC=1 SCAR=0.0
9 6 ▶use File::Temp;
Subroutine BEGIN: called CC=1 SCAR=0.0
10 6 ▶use Mojo::SQLite::Database;
Subroutine BEGIN: called CC=1 SCAR=0.0
11 6 ▶use Mojo::SQLite::Migrations;
Subroutine BEGIN: called CC=1 SCAR=0.0
12 6 ▶use Scalar::Util qw(blessed weaken);
Subroutine BEGIN: called CC=1 SCAR=0.0
13 6 ▶use SQL::Abstract::Pg;
Subroutine BEGIN: called CC=1 SCAR=0.0
14 6 ▶use URI;
Subroutine BEGIN: called CC=1 SCAR=0.0
15 6 ▶use URI::db;
Subroutine BEGIN: called CC=1 SCAR=0.0
16  
17 6 our $VERSION = 'v4.0.0';
18  
19 1 ▶has abstract => sub { SQL::Abstract::Pg->new(name_sep => '.', quote_char => '"') };
Subroutine __ANON__: called CC=1 SCAR=0.0
20 6 has 'auto_migrate';
21 6 has database_class => 'Mojo::SQLite::Database';
22 7 ▶has dsn => sub { _url_from_file(shift->_tempfile)->dbi_dsn };
Subroutine __ANON__: called CC=1 SCAR=0.0
23 6 has max_connections => 1;
24 5 ▶has migrations => sub { Mojo::SQLite::Migrations->new(sqlite => shift) };
Subroutine __ANON__: called CC=1 SCAR=0.0
25 19 ▶has options => sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
26 {
27 19 AutoCommit => 1,
28 AutoInactiveDestroy => 1,
29 PrintError => 0,
30 RaiseError => 1,
31 sqlite_string_mode => DBD_SQLITE_STRING_MODE_UNICODE_FALLBACK,
32 wal_mode => 0,
33 };
34 6 };
35 6 has 'parent';
36  
37 21 ▶sub new { @_ > 1 ? shift->SUPER::new->from_string(@_) : shift->SUPER::new }
Subroutine new: called CC=2 SCAR=6.9
Pod documented
Branch: 1 branch
BranchTrueFalseTotal
@_ > 1 ? : 9 12 21
38  
39 123 ▶sub db { $_[0]->database_class->new(dbh => $_[0]->_prepare, sqlite => $_[0]) }
Subroutine db: called CC=1 SCAR=0.0
Pod documented
40  
41 5 ▶sub from_filename { shift->from_string(_url_from_file(shift, shift)) }
Subroutine from_filename: called CC=1 SCAR=0.0
Pod documented
42  
43 14 ▶sub from_string {
Subroutine from_string: called CC=14 SCAR=26.9
Pod documented
44 14 my ($self, $str) = @_;
45 14 ▶ return $self unless $str;
Branch: 1 branch
BranchTrueFalseTotal
unless $str 0 14 14
46 14 ▶ return $self->parent($str) if blessed $str and $str->isa('Mojo::SQLite');
Branch: 1 branch
BranchTrueFalseTotal
if builtin::blessed($str) and $str->isa("Mojo::SQLite") 2 12 14
Condition100%3/3
builtin::blessed($str) and $str->isa("Mojo::SQLite")
!ll&&!rl&&r
662
MC/DC100%2/2
builtin::blessed($str) and $str->isa("Mojo::SQLite")
builtin::blessed($str) $str->isa("Mojo::SQLite")
Truth table100%3/3
A and B
A= builtin::blessed($str)B= $str->isa("Mojo::SQLite")
ABresult
0X0
100
111
47  
48 12 my $url = URI->new($str);
49  
50 # Options
51 12 my %options = $url->query_form;
52 12 $url->query(undef);
53 # don't set default string_mode if sqlite_unicode legacy option is set
54 12 ▶ delete $self->options->{sqlite_string_mode} if exists $options{sqlite_unicode};
Branch: 1 branch
BranchTrueFalseTotal
if exists $options{"sqlite_unicode"} 2 10 12
55 12 @{$self->options}{keys %options} = values %options;
56  
57 # Parse URL based on scheme
58 12 ▶ $url->scheme('file') unless $url->has_recognized_scheme;
Branch: 1 branch
BranchTrueFalseTotal
unless $url->has_recognized_scheme 4 8 12
59 12 ▶ if ($url->scheme eq 'file') {
Branch: 2 branches
BranchTrueFalseTotal
if ($url->scheme eq 'file') { } 5 7 12
elsif ($url->scheme ne 'db') { } 2 5 7
60 5 $url = _url_from_file($url->file);
61 } elsif ($url->scheme ne 'db') {
62 2 $url = URI::db->new($url);
63 }
64  
65 12 ▶ croak qq{Invalid SQLite connection string "$str"}
Branch: 1 branch
BranchTrueFalseTotal
unless $url->has_recognized_engine and $url->canonical_engine eq "sqlite" and ($url->host // "") eq "" || $url->host eq "localhost" 1 11 12
Condition54%6/11
$url->has_recognized_engine and $url->canonical_engine eq "sqlite" and ($url->host // "") eq "" || $url->host eq "localhost"
!ll&&!rl&&r
1011
$url->has_recognized_engine and $url->canonical_engine eq "sqlite"
!ll&&!rl&&r
1011
($url->host // "") eq "" or $url->host eq "localhost"
l!l&&r!l&&!r
1100
$url->host // ""
l!l
011
MC/DC0%0/4
$url->has_recognized_engine and $url->canonical_engine eq "sqlite" and ($url->host // "") eq "" || $url->host eq "localhost"
$url->has_recognized_engine $url->canonical_engine eq "sqlite" $url->host $url->host eq "localhost"
Truth table20%1/5
A and B and C or D
A= $url->has_recognized_engineB= $url->canonical_engine eq "sqlite"C= $url->hostD= $url->host eq "localhost"
ABCDresult
0XXX0
10XX0
11000
111X1
11011
66 unless $url->has_recognized_engine and $url->canonical_engine eq 'sqlite'
67 and (($url->host // '') eq '' or $url->host eq 'localhost');
68
69 # Temp database file
70 11 ▶ $url->dbname($self->_tempfile) if $url->dbname eq ':temp:';
Branch: 1 branch
BranchTrueFalseTotal
if $url->dbname eq ":temp:" 0 11 11
71
72 11 return $self->dsn($url->dbi_dsn);
73 }
74  
75 123 ▶sub _dequeue {
Subroutine _dequeue: called CC=9 SCAR=22.2
76 123 my $self = shift;
77  
78 # Fork-safety
79 123 ▶ delete @$self{qw(pid queue)} unless ($self->{pid} //= $$) eq $$;
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->{"pid"} //= $$) eq $$ 2 121 123
Condition66%2/3
$self->{"pid"} //= $$
l!l&&r!l&&!r
111120
MC/DC0%0/2
$self->{"pid"} //= $$
$self->{"pid"} $$
Truth table66%2/3
A //= B
A= $self->{"pid"}B= $$
ABresult
1X1
011
000
80  
81 123 ▶ while (my $dbh = shift @{$self->{queue} || []}) { return $dbh if $dbh->ping }
Branch: 2 branches
BranchTrueFalseTotal
if (my $dbh = shift @{$self->{"queue"} or [];}) 96 27 123
if $dbh->ping 96 0 96
Condition100%2/2
$self->{'queue'} || []
l!l
11013
MC/DC100%1/1
$self->{'queue'} || []
$self->{'queue'}
Truth table100%2/2
A
A= $self->{'queue'}
Aresult
11
00
82
83 27 ▶ my $dbh = DBI->connect($self->dsn, undef, undef, $self->options)
Condition50%1/2
"DBI"->connect($self->dsn, undef, undef, $self->options) // croak("DBI connection to @{[$self->dsn];} failed: $DBI::errstr")
l!l
270
MC/DC0%0/1
"DBI"->connect($self->dsn, undef, undef, $self->options) // croak("DBI connection to @{[$self->dsn];} failed: $DBI::errstr")
"DBI"->connect($self->dsn, undef, undef, $self->options)
Truth table50%1/2
A
A= "DBI"->connect($self->dsn, undef, undef, $self->options)
Aresult
11
00
84 0 // croak "DBI connection to @{[$self->dsn]} failed: $DBI::errstr"; # RaiseError disabled
85 27 $dbh->sqlite_db_config(SQLITE_DBCONFIG_DQS_DDL, 0);
86 27 $dbh->sqlite_db_config(SQLITE_DBCONFIG_DQS_DML, 0);
87 27 ▶ if ($self->options->{wal_mode} and !$self->options->{no_wal}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->options->{"wal_mode"} and not $self->options->{"no_wal"}) 1 26 27
Condition66%2/3
$self->options->{"wal_mode"} and not $self->options->{"no_wal"}
!ll&&!rl&&r
2601
MC/DC50%1/2
$self->options->{"wal_mode"} and not $self->options->{"no_wal"}
$self->options->{"wal_mode"} not $self->options->{"no_wal"}
Truth table66%2/3
A and not(B)
A= $self->options->{"wal_mode"}B= not $self->options->{"no_wal"}
ABresult
0X0
100
111
88 1 $dbh->do('pragma journal_mode=WAL');
89 1 $dbh->do('pragma synchronous=NORMAL');
90 }
91  
92 # Cache the last insert rowid on inserts
93 27 weaken(my $weakdbh = $dbh);
94 43 ▶ $dbh->sqlite_update_hook(sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
95 43 ▶ $weakdbh->{private_mojo_last_insert_id} = $_[3] if $_[0] == DBD::SQLite::INSERT;
Branch: 1 branch
BranchTrueFalseTotal
if $_[0] == &DBD::SQLite::INSERT() 20 23 43
96 27 });
97  
98 27 $self->emit(connection => $dbh);
99  
100 27 return $dbh;
101 }
102  
103 129 ▶sub _enqueue {
Subroutine _enqueue: called CC=5 SCAR=16.1
104 129 my ($self, $dbh) = @_;
105  
106 129 ▶ if (my $parent = $self->parent) { return $parent->_enqueue($dbh) }
Branch: 1 branch
BranchTrueFalseTotal
if (my $parent = $self->parent) 6 123 129
107  
108 123 ▶ my $queue = $self->{queue} ||= [];
Condition100%2/2
$self->{"queue"} ||= []
l!l
11112
MC/DC100%1/1
$self->{"queue"} ||= []
$self->{"queue"}
Truth table100%2/2
A
A= $self->{"queue"}
Aresult
11
00
109 123 ▶ push @$queue, $dbh if $dbh->{Active};
Branch: 1 branch
BranchTrueFalseTotal
if $dbh->{"Active"} 121 2 123
110 123 ▶ shift @$queue while @$queue > $self->max_connections;
Branch: 1 branch
BranchTrueFalseTotal
@$queue > $self->max_connections and do { shift @$queue } 13 123 136
111 }
112  
113 129 ▶sub _prepare {
Subroutine _prepare: called CC=5 SCAR=16.4
114 129 my $self = shift;
115  
116 # Automatic migrations
117 ++$self->{migrated} and $self->migrations->migrate
118 129 ▶ if !$self->{migrated} && $self->auto_migrate;
Branch: 1 branch
BranchTrueFalseTotal
if not $self->{"migrated"} and $self->auto_migrate 3 126 129
Condition66%6/9
!$self->{'migrated'} && $self->auto_migrate && (++$self->{'migrated'} && $self->migrations->migrate)
!ll&&!rl&&r
12630
not $self->{"migrated"} and $self->auto_migrate
!ll&&!rl&&r
131133
++$self->{"migrated"} and $self->migrations->migrate
!ll&&!rl&&r
030
MC/DC0%0/4
!$self->{'migrated'} && $self->auto_migrate && (++$self->{'migrated'} && $self->migrations->migrate)
not $self->{"migrated"} $self->auto_migrate ++$self->{"migrated"} $self->migrations->migrate
Truth table40%2/5
not(A) and B && C and D
A= not $self->{"migrated"}B= $self->auto_migrateC= ++$self->{"migrated"}D= $self->migrations->migrate
ABCDresult
0XXX0
10XX0
110X0
11100
11111
119  
120 129 my $parent = $self->parent;
121 129 ▶ return $parent ? $parent->_prepare : $self->_dequeue;
Branch: 1 branch
BranchTrueFalseTotal
$parent ? : 6 123 129
122 }
123  
124 7 ▶sub _tempfile { catfile(shift->{tempdir} = File::Temp->newdir, 'sqlite.db') }
Subroutine _tempfile: called CC=1 SCAR=0.0
125  
126 17 ▶sub _url_from_file {
Subroutine _url_from_file: called CC=2 SCAR=6.9
127 17 my $url = URI::db->new;
128 17 $url->engine('sqlite');
129 17 $url->dbname(shift);
130 17 ▶ if (my $options = shift) { $url->query_form($options) }
Branch: 1 branch
BranchTrueFalseTotal
if (my $options = shift()) 1 16 17
131 17 return $url;
132 }
133  
134 6 1;
135  
136 =head1 NAME
137  
138 Mojo::SQLite - A tiny Mojolicious wrapper for SQLite
139  
140 =head1 SYNOPSIS
141  
142 use Mojo::SQLite;
143  
144 # Select the library version
145 my $sql = Mojo::SQLite->new('sqlite:test.db');
146 say $sql->db->query('select sqlite_version() as version')->hash->{version};
147  
148 # Use migrations to create a table
149 $sql->migrations->name('my_names_app')->from_string(<<EOF)->migrate;
150 -- 1 up
151 create table names (id integer primary key autoincrement, name text);
152 -- 1 down
153 drop table names;
154 EOF
155  
156 # Use migrations to drop and recreate the table
157 $sql->migrations->migrate(0)->migrate;
158  
159 # Get a database handle from the cache for multiple queries
160 my $db = $sql->db;
161  
162 # Use SQL::Abstract to generate simple CRUD queries for you
163 $db->insert('names', {name => 'Isabel'});
164 my $id = $db->select('names', ['id'], {name => 'Isabel'})->hash->{id};
165 $db->update('names', {name => 'Bel'}, {id => $id});
166 $db->delete('names', {name => 'Bel'});
167  
168 # Insert a few rows in a transaction with SQL and placeholders
169 eval {
170 my $tx = $db->begin;
171 $db->query('insert into names (name) values (?)', 'Sara');
172 $db->query('insert into names (name) values (?)', 'Stefan');
173 $tx->commit;
174 };
175 say $@ if $@;
176  
177 # Insert another row with SQL::Abstract and return the generated id
178 say $db->insert('names', {name => 'Daniel'})->last_insert_id;
179
180 # JSON roundtrip
181 say $db->query('select ? as foo', {json => {bar => 'baz'}})
182 ->expand(json => 'foo')->hash->{foo}{bar};
183  
184 # Select one row at a time
185 my $results = $db->query('select * from names');
186 while (my $next = $results->hash) {
187 say $next->{name};
188 }
189  
190 # Select all rows with SQL::Abstract
191 say $_->{name} for $db->select('names')->hashes->each;
192  
193 =head1 DESCRIPTION
194  
195 L<Mojo::SQLite> is a tiny wrapper around L<DBD::SQLite> that makes
196 L<SQLite|https://www.sqlite.org/> a lot of fun to use with the
197 L<Mojolicious|https://mojolico.us> real-time web framework. Use all
198 L<SQL features|http://sqlite.org/lang.html> SQLite has to offer, generate CRUD
199 queries from data structures, and manage your database schema with migrations.
200  
201 =head1 BASICS
202  
203 Database and statement handles are cached automatically, so they can be reused
204 transparently to increase performance. And you can handle connection timeouts
205 gracefully by holding on to them only for short amounts of time.
206  
207 use Mojolicious::Lite;
208 use Mojo::SQLite;
209  
210 helper sqlite => sub { state $sql = Mojo::SQLite->new('sqlite:test.db') };
211  
212 get '/' => sub ($c) {
213 my $db = $c->sqlite->db;
214 $c->render(json => $db->query(q{select datetime('now','localtime') as now})->hash);
215 };
216  
217 app->start;
218  
219 In this example application, we create a C<sqlite> helper to store a
220 L<Mojo::SQLite> object. Our action calls that helper and uses the method
221 L<Mojo::SQLite/"db"> to dequeue a L<Mojo::SQLite::Database> object from the
222 connection pool. Then we use the method L<Mojo::SQLite::Database/"query"> to
223 execute an L<SQL|http://www.postgresql.org/docs/current/static/sql.html>
224 statement, which returns a L<Mojo::SQLite::Results> object. And finally we call
225 the method L<Mojo::SQLite::Results/"hash"> to retrieve the first row as a hash
226 reference.
227  
228 All I/O and queries are performed synchronously, and SQLite's default journal
229 mode only supports concurrent reads from multiple processes while the database
230 is not being written.
231  
232 The "Write-Ahead Log" journal mode allows multiple
233 processes to read and write concurrently to the same database file (but only
234 one can write at a time). WAL mode is enabled by the C<wal_mode> option,
235 and persists when opening that same database in the future.
236  
237 # Performed concurrently (concurrent with writing only with WAL journaling mode)
238 my $pid = fork || die $!;
239 say $sql->db->query(q{select datetime('now','localtime') as time})->hash->{time};
240 exit unless $pid;
241  
242 C<wal_mode> was enabled by default until L<Mojo::SQLite> version v4.0.0; the
243 C<no_wal> option (supported since version 2.002) can be specified to prevent it
244 when creating new databases, but to disable it in an existing database the
245 C<journal_mode> must be set manually back to the default of C<DELETE>. See
246 L<http://sqlite.org/wal.html> and L<DBD::SQLite/"journal_mode"> for more
247 information.
248  
249 # Disable WAL mode on a database where it was previously enabled
250 $sql->db->query('PRAGMA journal_mode=DELETE');
251  
252 The L<double-quoted string literal misfeature
253 |https://sqlite.org/quirks.html#double_quoted_string_literals_are_accepted> is
254 disabled for all connections since Mojo::SQLite 3.003; use single quotes for
255 string literals and double quotes for identifiers, as is normally recommended.
256  
257 All cached database handles will be reset automatically if a new process has
258 been forked, this allows multiple processes to share the same L<Mojo::SQLite>
259 object safely.
260  
261 Any database errors will throw an exception as C<RaiseError> is automatically
262 enabled, so use C<eval> or L<Try::Tiny> to catch them. This makes transactions
263 with L<Mojo::SQLite::Database/"begin"> easy.
264  
265 While passing a file path of C<:memory:> (or a custom L</"dsn"> with
266 C<mode=memory>) will create a temporary database, in-memory databases cannot be
267 shared between connections, so subsequent calls to L</"db"> may return
268 connections to completely different databases. For a temporary database that
269 can be shared between connections and processes, pass a file path of C<:temp:>
270 to store the database in a temporary directory (this is the default), or
271 consider constructing a temporary directory yourself with L<File::Temp> if you
272 need to reuse the filename. A temporary directory allows SQLite to create
273 L<additional temporary files|https://www.sqlite.org/tempfiles.html> safely.
274  
275 use File::Spec::Functions 'catfile';
276 use File::Temp;
277 use Mojo::SQLite;
278 my $tempdir = File::Temp->newdir; # Deleted when object goes out of scope
279 my $tempfile = catfile $tempdir, 'test.db';
280 my $sql = Mojo::SQLite->new->from_filename($tempfile);
281  
282 =head1 EXAMPLES
283  
284 This distribution also contains a well-structured example
285 L<blog application|https://github.com/Grinnz/Mojo-SQLite/tree/master/examples/blog>
286 you can use for inspiration. This application shows how to apply the MVC design
287 pattern in practice.
288  
289 =head1 EVENTS
290  
291 L<Mojo::SQLite> inherits all events from L<Mojo::EventEmitter> and can emit the
292 following new ones.
293  
294 =head2 connection
295  
296 $sql->on(connection => sub ($sql, $dbh) {
297 $dbh->do('pragma journal_size_limit=1000000');
298 });
299  
300 Emitted when a new database connection has been established.
301  
302 =head1 ATTRIBUTES
303  
304 L<Mojo::SQLite> implements the following attributes.
305  
306 =head2 abstract
307  
308 my $abstract = $sql->abstract;
309 $sql = $sql->abstract(SQL::Abstract->new);
310  
311 L<SQL::Abstract> object used to generate CRUD queries for
312 L<Mojo::SQLite::Database>, defaults to a L<SQL::Abstract::Pg> object with
313 C<name_sep> set to C<.> and C<quote_char> set to C<">.
314  
315 # Generate WHERE clause and bind values
316 my($stmt, @bind) = $sql->abstract->where({foo => 'bar', baz => 'yada'});
317  
318 L<SQL::Abstract::Pg> provides additional features to the L<SQL::Abstract>
319 query methods in L<Mojo::SQLite::Database> such as C<-json> and
320 C<limit>/C<offset>. The C<for> feature is not applicable to SQLite queries.
321  
322 $sql->db->select(['some_table', ['other_table', foo_id => 'id']],
323 ['foo', [bar => 'baz'], \q{datetime('now') as dt}],
324 {foo => 'value'},
325 {order_by => 'foo', limit => 10, offset => 5, group_by => ['foo'], having => {baz => 'value'}});
326  
327 # Upsert supported since SQLite 3.24.0
328 $sql->db->insert('some_table', {name => $name, value => $value},
329 {on_conflict => [name => {value => \'"excluded"."value"'}]});
330  
331 =head2 auto_migrate
332  
333 my $bool = $sql->auto_migrate;
334 $sql = $sql->auto_migrate($bool);
335  
336 Automatically migrate to the latest database schema with L</"migrations">, as
337 soon as L</"db"> has been called for the first time.
338  
339 =head2 database_class
340  
341 my $class = $sql->database_class;
342 $sql = $sql->database_class('MyApp::Database');
343  
344 Class to be used by L</"db">, defaults to L<Mojo::SQLite::Database>. Note that
345 this class needs to have already been loaded before L</"db"> is called.
346  
347 =head2 dsn
348  
349 my $dsn = $sql->dsn;
350 $sql = $sql->dsn('dbi:SQLite:uri=file:foo.db');
351  
352 Data source name, defaults to C<dbi:SQLite:dbname=> followed by a path to a
353 temporary file.
354  
355 =head2 max_connections
356  
357 my $max = $sql->max_connections;
358 $sql = $sql->max_connections(3);
359  
360 Maximum number of idle database handles to cache for future use, defaults to
361 C<1>.
362  
363 =head2 migrations
364  
365 my $migrations = $sql->migrations;
366 $sql = $sql->migrations(Mojo::SQLite::Migrations->new);
367  
368 L<Mojo::SQLite::Migrations> object you can use to change your database schema
369 more easily.
370  
371 # Load migrations from file and migrate to latest version
372 $sql->migrations->from_file('/home/dbook/migrations.sql')->migrate;
373  
374 =head2 options
375  
376 my $options = $sql->options;
377 $sql = $sql->options({AutoCommit => 1, RaiseError => 1});
378  
379 Options for database handles, defaults to setting C<sqlite_string_mode> to
380 C<DBD_SQLITE_STRING_MODE_UNICODE_FALLBACK>, setting C<AutoCommit>,
381 C<AutoInactiveDestroy> and C<RaiseError>, and deactivating C<PrintError>.
382 Note that C<AutoCommit> and C<RaiseError> are considered mandatory, so
383 deactivating them would be very dangerous. See
384 L<DBI/"ATTRIBUTES COMMON TO ALL HANDLES"> and
385 L<DBD::SQLite/"DRIVER PRIVATE ATTRIBUTES"> for more information on available
386 options.
387  
388 =head2 parent
389  
390 my $parent = $sql->parent;
391 $sql = $sql->parent(Mojo::SQLite->new);
392  
393 Another L<Mojo::SQLite> object to use for connection management, instead of
394 establishing and caching our own database connections.
395  
396 =head1 METHODS
397  
398 L<Mojo::SQLite> inherits all methods from L<Mojo::EventEmitter> and implements
399 the following new ones.
400  
401 =head2 new
402  
403 my $sql = Mojo::SQLite->new;
404 my $sql = Mojo::SQLite->new('file:test.db);
405 my $sql = Mojo::SQLite->new('sqlite:test.db');
406 my $sql = Mojo::SQLite->new(Mojo::SQLite->new);
407  
408 Construct a new L<Mojo::SQLite> object and parse connection string with
409 L</"from_string"> if necessary.
410  
411 # Customize configuration further
412 my $sql = Mojo::SQLite->new->dsn('dbi:SQLite:dbname=test.db');
413 my $sql = Mojo::SQLite->new->dsn('dbi:SQLite:uri=file:test.db?mode=memory');
414  
415 # Pass filename directly
416 my $sql = Mojo::SQLite->new->from_filename($filename);
417  
418 =head2 db
419  
420 my $db = $sql->db;
421  
422 Get a database object based on L</"database_class"> (which is usually
423 L<Mojo::SQLite::Database>) for a cached or newly established database
424 connection. The L<DBD::SQLite> database handle will be automatically cached
425 again when that object is destroyed, so you can handle problems like connection
426 timeouts gracefully by holding on to it only for short amounts of time.
427  
428 # Add up all the money
429 say $sql->db->select('accounts')
430 ->hashes->reduce(sub { $a->{money} + $b->{money} });
431  
432 =head2 from_filename
433  
434 $sql = $sql->from_filename('C:\\Documents and Settings\\foo & bar.db', $options);
435  
436 Parse database filename directly. Unlike L</"from_string">, the filename is
437 parsed as a local filename and not a URL. A hashref of L</"options"> may be
438 passed as the second argument.
439  
440 # Absolute filename
441 $sql->from_filename('/home/fred/data.db');
442  
443 # Relative to current directory
444 $sql->from_filename('data.db');
445  
446 # Temporary file database (default)
447 $sql->from_filename(':temp:');
448  
449 # In-memory temporary database (single connection only)
450 my $db = $sql->from_filename(':memory:')->db;
451  
452 # Additional options
453 $sql->from_filename($filename, { PrintError => 1 });
454
455 # Readonly connection
456 $sql->from_filename($filename, { ReadOnly => 1 });
457
458 # Strict unicode strings and WAL mode
459 use DBD::SQLite::Constants ':dbd_sqlite_string_mode';
460 $sql->from_filename($filename, { sqlite_string_mode => DBD_SQLITE_STRING_MODE_UNICODE_STRICT, wal_mode => 1 });
461  
462 =head2 from_string
463  
464 $sql = $sql->from_string('test.db');
465 $sql = $sql->from_string('file:test.db');
466 $sql = $sql->from_string('file:///C:/foo/bar.db');
467 $sql = $sql->from_string('sqlite:C:%5Cfoo%5Cbar.db');
468 $sql = $sql->from_string(Mojo::SQLite->new);
469  
470 Parse configuration from connection string or use another L<Mojo::SQLite>
471 object as L</"parent">. Connection strings are parsed as URLs, so you should
472 construct them using a module like L<Mojo::URL>, L<URI::file>, or L<URI::db>.
473 For portability on non-Unix-like systems, either construct the URL with the
474 C<sqlite> scheme, or use L<URI::file/"new"> to construct a URL with the C<file>
475 scheme. A URL with no scheme will be parsed as a C<file> URL, and C<file> URLs
476 are parsed according to the current operating system. If specified, the
477 hostname must be C<localhost>. If the URL has a query string, it will be parsed
478 and applied to L</"options">.
479  
480 # Absolute filename
481 $sql->from_string('sqlite:////home/fred/data.db');
482 $sql->from_string('sqlite://localhost//home/fred/data.db');
483 $sql->from_string('sqlite:/home/fred/data.db');
484 $sql->from_string('file:///home/fred/data.db');
485 $sql->from_string('file://localhost/home/fred/data.db');
486 $sql->from_string('file:/home/fred/data.db');
487 $sql->from_string('///home/fred/data.db');
488 $sql->from_string('//localhost/home/fred/data.db');
489 $sql->from_string('/home/fred/data.db');
490  
491 # Relative to current directory
492 $sql->from_string('sqlite:data.db');
493 $sql->from_string('file:data.db');
494 $sql->from_string('data.db');
495  
496 # Connection string must be a valid URL
497 $sql->from_string(Mojo::URL->new->scheme('sqlite')->path($filename));
498 $sql->from_string(URI::db->new->Mojo::Base::tap(engine => 'sqlite')->Mojo::Base::tap(dbname => $filename));
499 $sql->from_string(URI::file->new($filename));
500  
501 # Temporary file database (default)
502 $sql->from_string(':temp:');
503  
504 # In-memory temporary database (single connection only)
505 my $db = $sql->from_string(':memory:')->db;
506  
507 # Additional options
508 $sql->from_string('data.db?PrintError=1&sqlite_allow_multiple_statements=1');
509 $sql->from_string(Mojo::URL->new->scheme('sqlite')->path($filename)->query(sqlite_see_if_its_a_number => 1));
510 $sql->from_string(URI::file->new($filename)->Mojo::Base::tap(query_form => {PrintError => 1}));
511  
512 # Readonly connection with WAL mode
513 $sql->from_string('data.db?ReadOnly=1&wal_mode=1');
514  
515 # String unicode strings and WAL mode
516 use DBD::SQLite::Constants ':dbd_sqlite_string_mode';
517 $sql->from_string(Mojo::URL->new->scheme('sqlite')->path('data.db')
518 ->query(sqlite_string_mode => DBD_SQLITE_STRING_MODE_UNICODE_STRICT, wal_mode => 1));
519  
520 =head1 DEBUGGING
521  
522 You can set the C<DBI_TRACE> environment variable to get some advanced
523 diagnostics information printed by L<DBI>.
524  
525 DBI_TRACE=1
526 DBI_TRACE=15
527 DBI_TRACE=SQL
528  
529 =head1 REFERENCE
530  
531 This is the class hierarchy of the L<Mojo::SQLite> distribution.
532  
533 =over 2
534  
535 =item * L<Mojo::SQLite>
536  
537 =item * L<Mojo::SQLite::Database>
538  
539 =item * L<Mojo::SQLite::Migrations>
540  
541 =item * L<Mojo::SQLite::Results>
542  
543 =item * L<Mojo::SQLite::Transaction>
544  
545 =back
546  
547 =head1 BUGS
548  
549 Report any issues on the public bugtracker.
550  
551 =head1 AUTHOR
552  
553 Dan Book, C<dbook@cpan.org>
554  
555 =head1 CREDITS
556  
557 Sebastian Riedel, author of L<Mojo::Pg>, which this distribution is based on.
558  
559 =head1 COPYRIGHT AND LICENSE
560  
561 Copyright 2015, Dan Book.
562  
563 This library is free software; you may redistribute it and/or modify it under
564 the terms of the Artistic License version 2.0.
565  
566 =head1 SEE ALSO
567  
568 L<Mojolicious>, L<Mojo::Pg>, L<DBD::SQLite>
↑ Summary SQLite/Migrations.pm »