File Coverage

blib/lib/DBD/SQLite.pm
Criterion Covered Total %
statement 352 372 94.6
branch 164 228 71.9
condition 92 147 62.5
subroutine 27 29 93.1
pod 0 1 0.0
total 635 777 81.7


line stmt bran cond sub pod time code
1             package DBD::SQLite;
2              
3 116     116   14487159 use 5.006;
  116         1788  
4 116     116   666 use strict;
  116         254  
  116         2965  
5 116     116   701 use DBI 1.57 ();
  116         2430  
  116         2042  
6 116     116   605 use XSLoader ();
  116         226  
  116         10561  
7              
8             our $VERSION = '1.74';
9              
10             # sqlite_version cache (set in the XS bootstrap)
11             our ($sqlite_version, $sqlite_version_number);
12              
13             # not sure if we still need these...
14             our ($err, $errstr);
15              
16             XSLoader::load('DBD::SQLite', $VERSION);
17              
18             # New or old API?
19 116     116   962 use constant NEWAPI => ($DBI::VERSION >= 1.608);
  116         347  
  116         21674  
20              
21             # global registry of collation functions, initialized with 2 builtins
22             our %COLLATION;
23             tie %COLLATION, 'DBD::SQLite::_WriteOnceHash';
24             $COLLATION{perl} = sub { $_[0] cmp $_[1] };
25 116     116   56843 $COLLATION{perllocale} = sub { use locale; $_[0] cmp $_[1] };
  116         71854  
  116         715  
26              
27             our $drh;
28             my $methods_are_installed = 0;
29              
30             sub driver {
31 110 50   110 0 489514 return $drh if $drh;
32              
33 110 50 50     1028 if (!$methods_are_installed && DBD::SQLite::NEWAPI ) {
34 110         522 DBI->setup_driver('DBD::SQLite');
35              
36 110         4614 DBD::SQLite::db->install_method('sqlite_last_insert_rowid');
37 110         7595 DBD::SQLite::db->install_method('sqlite_busy_timeout');
38 110         4306 DBD::SQLite::db->install_method('sqlite_create_function');
39 110         4020 DBD::SQLite::db->install_method('sqlite_create_aggregate');
40 110         4138 DBD::SQLite::db->install_method('sqlite_create_collation');
41 110         4178 DBD::SQLite::db->install_method('sqlite_collation_needed');
42 110         4142 DBD::SQLite::db->install_method('sqlite_progress_handler');
43 110         3990 DBD::SQLite::db->install_method('sqlite_commit_hook');
44 110         4656 DBD::SQLite::db->install_method('sqlite_rollback_hook');
45 110         4119 DBD::SQLite::db->install_method('sqlite_update_hook');
46 110         3852 DBD::SQLite::db->install_method('sqlite_set_authorizer');
47 110         3925 DBD::SQLite::db->install_method('sqlite_backup_from_file');
48 110         3949 DBD::SQLite::db->install_method('sqlite_backup_to_file');
49 110         4236 DBD::SQLite::db->install_method('sqlite_backup_from_dbh');
50 110         4101 DBD::SQLite::db->install_method('sqlite_backup_to_dbh');
51 110         3895 DBD::SQLite::db->install_method('sqlite_enable_load_extension');
52 110         4345 DBD::SQLite::db->install_method('sqlite_load_extension');
53 110         4310 DBD::SQLite::db->install_method('sqlite_register_fts3_perl_tokenizer');
54 110         4338 DBD::SQLite::db->install_method('sqlite_trace', { O => 0x0004 });
55 110         4566 DBD::SQLite::db->install_method('sqlite_profile', { O => 0x0004 });
56 110         4452 DBD::SQLite::db->install_method('sqlite_table_column_metadata', { O => 0x0004 });
57 110         4775 DBD::SQLite::db->install_method('sqlite_db_filename', { O => 0x0004 });
58 110         4404 DBD::SQLite::db->install_method('sqlite_db_status', { O => 0x0004 });
59 110         4757 DBD::SQLite::st->install_method('sqlite_st_status', { O => 0x0004 });
60 110         4511 DBD::SQLite::db->install_method('sqlite_create_module');
61 110         4042 DBD::SQLite::db->install_method('sqlite_limit');
62 110         4084 DBD::SQLite::db->install_method('sqlite_db_config');
63 110         4085 DBD::SQLite::db->install_method('sqlite_get_autocommit');
64 110         3969 DBD::SQLite::db->install_method('sqlite_txn_state');
65 110         4899 DBD::SQLite::db->install_method('sqlite_error_offset');
66              
67 110         3814 $methods_are_installed++;
68             }
69              
70 110         1526 $drh = DBI::_new_drh( "$_[0]::dr", {
71             Name => 'SQLite',
72             Version => $VERSION,
73             Attribution => 'DBD::SQLite by Matt Sergeant et al',
74             } );
75              
76 110         5564 return $drh;
77             }
78              
79             sub CLONE {
80 0     0   0 undef $drh;
81             }
82              
83              
84             package # hide from PAUSE
85             DBD::SQLite::dr;
86              
87             sub connect {
88 313     313   3713728 my ($drh, $dbname, $user, $auth, $attr) = @_;
89              
90             # Default PrintWarn to the value of $^W
91             # unless ( defined $attr->{PrintWarn} ) {
92             # $attr->{PrintWarn} = $^W ? 1 : 0;
93             # }
94              
95 313         1604 my $dbh = DBI::_new_dbh( $drh, {
96             Name => $dbname,
97             } );
98              
99 313         12842 my $real = $dbname;
100 313 100       2001 if ( $dbname =~ /=/ ) {
101 296         1372 foreach my $attrib ( split(/;/, $dbname) ) {
102 298         1131 my ($key, $value) = split(/=/, $attrib, 2);
103 298 100       2240 if ( $key =~ /^(?:db(?:name)?|database)$/ ) {
    100          
104 285         935 $real = $value;
105             } elsif ( $key eq 'uri' ) {
106 6         11 $real = $value;
107 6         23 $attr->{sqlite_open_flags} |= DBD::SQLite::OPEN_URI();
108             } else {
109 7         23 $attr->{$key} = $value;
110             }
111             }
112             }
113              
114 313 100       1389 if (my $flags = $attr->{sqlite_open_flags}) {
115 19 100       90 unless ($flags & (DBD::SQLite::OPEN_READONLY() | DBD::SQLite::OPEN_READWRITE())) {
116 13         35 $attr->{sqlite_open_flags} |= DBD::SQLite::OPEN_READWRITE() | DBD::SQLite::OPEN_CREATE();
117             }
118             }
119              
120             # To avoid unicode and long file name problems on Windows,
121             # convert to the shortname if the file (or parent directory) exists.
122 313 0 33     1863 if ( $^O =~ /MSWin32/ and $real ne ':memory:' and $real ne '' and $real !~ /^file:/ and !-f $real ) {
      33        
      0        
      0        
123 0         0 require File::Basename;
124 0         0 my ($file, $dir, $suffix) = File::Basename::fileparse($real);
125             # We are creating a new file.
126             # Does the directory it's in at least exist?
127 0 0       0 if ( -d $dir ) {
128 0         0 require Win32;
129 0         0 $real = join '', grep { defined } Win32::GetShortPathName($dir), $file, $suffix;
  0         0  
130             } else {
131             # SQLite can't do mkpath anyway.
132             # So let it go through as it and fail.
133             }
134             }
135              
136             # Hand off to the actual login function
137 313 100       109482 DBD::SQLite::db::_login($dbh, $real, $user, $auth, $attr) or return undef;
138              
139             # Register the on-demand collation installer, REGEXP function and
140             # perl tokenizer
141 307         1122 if ( DBD::SQLite::NEWAPI ) {
142 307         4579 $dbh->sqlite_collation_needed( \&install_collation );
143 307         4362 $dbh->sqlite_create_function( "REGEXP", 2, \&regexp );
144 307         43077 $dbh->sqlite_register_fts3_perl_tokenizer();
145             } else {
146             $dbh->func( \&install_collation, "collation_needed" );
147             $dbh->func( "REGEXP", 2, \&regexp, "create_function" );
148             $dbh->func( "register_fts3_perl_tokenizer" );
149             }
150              
151             # HACK: Since PrintWarn = 0 doesn't seem to actually prevent warnings
152             # in DBD::SQLite we set Warn to false if PrintWarn is false.
153              
154             # NOTE: According to the explanation by timbunce,
155             # "Warn is meant to report on bad practices or problems with
156             # the DBI itself (hence always on by default), while PrintWarn
157             # is meant to report warnings coming from the database."
158             # That is, if you want to disable an ineffective rollback warning
159             # etc (due to bad practices), you should turn off Warn,
160             # and to silence other warnings, turn off PrintWarn.
161             # Warn and PrintWarn are independent, and turning off PrintWarn
162             # does not silence those warnings that should be controlled by
163             # Warn.
164              
165             # unless ( $attr->{PrintWarn} ) {
166             # $attr->{Warn} = 0;
167             # }
168              
169 307         2368 return $dbh;
170             }
171              
172             sub install_collation {
173 12     12   31 my $dbh = shift;
174 12         20 my $name = shift;
175 12         68 my $collation = $DBD::SQLite::COLLATION{$name};
176 12 50       81 unless ($collation) {
177 0 0       0 warn "Can't install unknown collation: $name" if $dbh->{PrintWarn};
178 0         0 return;
179             }
180 12         17 if ( DBD::SQLite::NEWAPI ) {
181 12         65 $dbh->sqlite_create_collation( $name => $collation );
182             } else {
183             $dbh->func( $name => $collation, "create_collation" );
184             }
185             }
186              
187             # default implementation for sqlite 'REGEXP' infix operator.
188             # Note : args are reversed, i.e. "a REGEXP b" calls REGEXP(b, a)
189             # (see https://www.sqlite.org/vtab.html#xfindfunction)
190             sub regexp {
191 116     116   118234 use locale;
  116         294  
  116         588  
192 392 100 66 392   2836 return if !defined $_[0] || !defined $_[1];
193 264         1546 return scalar($_[1] =~ $_[0]);
194             }
195              
196             package # hide from PAUSE
197             DBD::SQLite::db;
198              
199 116     116   11263 use DBI qw/:sql_types/;
  116         330  
  116         596125  
200              
201             sub prepare {
202 1380     1380   3178692 my $dbh = shift;
203 1380         2357 my $sql = shift;
204 1380 50       3844 $sql = '' unless defined $sql;
205              
206 1380         5436 my $sth = DBI::_new_sth( $dbh, {
207             Statement => $sql,
208             } );
209              
210 1380 100       115367 DBD::SQLite::st::_prepare($sth, $sql, @_) or return undef;
211              
212 1359         19605 return $sth;
213             }
214              
215             sub do {
216 2978     2978   3121729 my ($dbh, $statement, $attr, @bind_values) = @_;
217              
218             # shortcut
219 2978         11288 my $allow_multiple_statements = $dbh->FETCH('sqlite_allow_multiple_statements');
220 2978 100 100     15869 if (defined $statement && !defined $attr && !@bind_values) {
      100        
221             # _do() (i.e. sqlite3_exec()) runs semicolon-separate SQL
222             # statements, which is handy but insecure sometimes.
223             # Use this only when it's safe or explicitly allowed.
224 2870 100 66     8613 if (index($statement, ';') == -1 or $allow_multiple_statements) {
225 2847         8369162 return DBD::SQLite::db::_do($dbh, $statement);
226             }
227             }
228              
229 131         247 my @copy = @{[@bind_values]};
  131         399  
230 131         273 my $rows = 0;
231              
232 131         311 while ($statement) {
233 136 100       501 my $sth = $dbh->prepare($statement, $attr) or return undef;
234 123 100       10729 $sth->execute(splice @copy, 0, $sth->{NUM_OF_PARAMS}) or return undef;
235 119         1080 $rows += $sth->rows;
236             # XXX: not sure why but $dbh->{sqlite...} wouldn't work here
237 119 100       1718 last unless $allow_multiple_statements;
238 8         127 $statement = $sth->{sqlite_unprepared_statements};
239             }
240              
241             # always return true if no error
242 114 100       815 return ($rows == 0) ? "0E0" : $rows;
243             }
244              
245             sub ping {
246 1     1   890 my $dbh = shift;
247              
248             # $file may be undef (ie. in-memory/temporary database)
249 1         24 my $file = DBD::SQLite::NEWAPI ? $dbh->sqlite_db_filename
250             : $dbh->func("db_filename");
251              
252 1 50 33     6 return 0 if $file && !-f $file;
253 1 50       13 return $dbh->FETCH('Active') ? 1 : 0;
254             }
255              
256             sub quote {
257 8     8   3501 my ($self, $value, $data_type) = @_;
258 8 100       29 return "NULL" unless defined $value;
259 7 50 66     68 if (defined $data_type and (
      66        
260             $data_type == DBI::SQL_BIT ||
261             $data_type == DBI::SQL_BLOB ||
262             $data_type == DBI::SQL_BINARY ||
263             $data_type == DBI::SQL_VARBINARY ||
264             $data_type == DBI::SQL_LONGVARBINARY)) {
265 6         1067 return q(X') . unpack('H*', $value) . q(');
266             }
267 1         3 $value =~ s/'/''/g;
268 1         4 return "'$value'";
269             }
270              
271             sub get_info {
272 79     79   12878 my ($dbh, $info_type) = @_;
273              
274 79         7873 require DBD::SQLite::GetInfo;
275 79         229 my $v = $DBD::SQLite::GetInfo::info{int($info_type)};
276 79 100       194 $v = $v->($dbh) if ref $v eq 'CODE';
277 79         237 return $v;
278             }
279              
280             sub _attached_database_list {
281 21     21   40 my $dbh = shift;
282 21         32 my @attached;
283              
284 21 50       73 my $sth_databases = $dbh->prepare( 'PRAGMA database_list' ) or return;
285 21 50       234 $sth_databases->execute or return;
286 21         466 while ( my $db_info = $sth_databases->fetchrow_hashref ) {
287 47 100       775 push @attached, $db_info->{name} if $db_info->{seq} >= 2;
288             }
289 21         316 return @attached;
290             }
291              
292             # SQL/CLI (ISO/IEC JTC 1/SC 32 N 0595), 6.63 Tables
293             # Based on DBD::Oracle's
294             # See also http://www.ch-werner.de/sqliteodbc/html/sqlite3odbc_8c.html#a213
295             sub table_info {
296 16     16   13115 my ($dbh, $cat_val, $sch_val, $tbl_val, $typ_val, $attr) = @_;
297              
298 16         35 my @where = ();
299 16         27 my $sql;
300 16 100 100     190 if ( defined($cat_val) && $cat_val eq '%'
    100 66        
    100 66        
      33        
      33        
      66        
      66        
      66        
      66        
      66        
      66        
      66        
      33        
      33        
      33        
      33        
      33        
301             && defined($sch_val) && $sch_val eq ''
302             && defined($tbl_val) && $tbl_val eq '') { # Rule 19a
303 1         4 $sql = <<'END_SQL';
304             SELECT NULL TABLE_CAT
305             , NULL TABLE_SCHEM
306             , NULL TABLE_NAME
307             , NULL TABLE_TYPE
308             , NULL REMARKS
309             END_SQL
310             }
311             elsif ( defined($cat_val) && $cat_val eq ''
312             && defined($sch_val) && $sch_val eq '%'
313             && defined($tbl_val) && $tbl_val eq '') { # Rule 19b
314 1         4 $sql = <<'END_SQL';
315             SELECT NULL TABLE_CAT
316             , t.tn TABLE_SCHEM
317             , NULL TABLE_NAME
318             , NULL TABLE_TYPE
319             , NULL REMARKS
320             FROM (
321             SELECT 'main' tn
322             UNION SELECT 'temp' tn
323             END_SQL
324 1         6 for my $db_name (_attached_database_list($dbh)) {
325 0         0 $sql .= " UNION SELECT '$db_name' tn\n";
326             }
327 1         5 $sql .= ") t\n";
328             }
329             elsif ( defined($cat_val) && $cat_val eq ''
330             && defined($sch_val) && $sch_val eq ''
331             && defined($tbl_val) && $tbl_val eq ''
332             && defined($typ_val) && $typ_val eq '%') { # Rule 19c
333 1         2 $sql = <<'END_SQL';
334             SELECT NULL TABLE_CAT
335             , NULL TABLE_SCHEM
336             , NULL TABLE_NAME
337             , t.tt TABLE_TYPE
338             , NULL REMARKS
339             FROM (
340             SELECT 'TABLE' tt UNION
341             SELECT 'VIEW' tt UNION
342             SELECT 'LOCAL TEMPORARY' tt UNION
343             SELECT 'SYSTEM TABLE' tt
344             ) t
345             ORDER BY TABLE_TYPE
346             END_SQL
347             }
348             else {
349 13         30 $sql = <<'END_SQL';
350             SELECT *
351             FROM
352             (
353             SELECT NULL TABLE_CAT
354             , TABLE_SCHEM
355             , tbl_name TABLE_NAME
356             , TABLE_TYPE
357             , NULL REMARKS
358             , sql sqlite_sql
359             FROM (
360             SELECT 'main' TABLE_SCHEM, tbl_name, upper(type) TABLE_TYPE, sql
361             FROM sqlite_master
362             UNION ALL
363             SELECT 'temp' TABLE_SCHEM, tbl_name, 'LOCAL TEMPORARY' TABLE_TYPE, sql
364             FROM sqlite_temp_master
365             END_SQL
366              
367 13         37 for my $db_name (_attached_database_list($dbh)) {
368 9         54 $sql .= <<"END_SQL";
369             UNION ALL
370             SELECT '$db_name' TABLE_SCHEM, tbl_name, upper(type) TABLE_TYPE, sql
371             FROM "$db_name".sqlite_master
372             END_SQL
373             }
374              
375 13         32 $sql .= <<'END_SQL';
376             UNION ALL
377             SELECT 'main' TABLE_SCHEM, 'sqlite_master' tbl_name, 'SYSTEM TABLE' TABLE_TYPE, NULL sql
378             UNION ALL
379             SELECT 'temp' TABLE_SCHEM, 'sqlite_temp_master' tbl_name, 'SYSTEM TABLE' TABLE_TYPE, NULL sql
380             )
381             )
382             END_SQL
383 13 50       46 $attr = {} unless ref $attr eq 'HASH';
384 13 50       44 my $escape = defined $attr->{Escape} ? " ESCAPE '$attr->{Escape}'" : '';
385 13 100       32 if ( defined $sch_val ) {
386 3         12 push @where, "TABLE_SCHEM LIKE '$sch_val'$escape";
387             }
388 13 100       31 if ( defined $tbl_val ) {
389 11         30 push @where, "TABLE_NAME LIKE '$tbl_val'$escape";
390             }
391 13 100       31 if ( defined $typ_val ) {
392 1         2 my $table_type_list;
393 1         6 $typ_val =~ s/^\s+//;
394 1         6 $typ_val =~ s/\s+$//;
395 1         5 my @ttype_list = split (/\s*,\s*/, $typ_val);
396 1         4 foreach my $table_type (@ttype_list) {
397 1 50       6 if ($table_type !~ /^'.*'$/) {
398 1         5 $table_type = "'" . $table_type . "'";
399             }
400             }
401 1         4 $table_type_list = join(', ', @ttype_list);
402 1 50       7 push @where, "TABLE_TYPE IN (\U$table_type_list)" if $table_type_list;
403             }
404 13 100       55 $sql .= ' WHERE ' . join("\n AND ", @where ) . "\n" if @where;
405 13         29 $sql .= " ORDER BY TABLE_TYPE, TABLE_SCHEM, TABLE_NAME\n";
406             }
407 16 50       67 my $sth = $dbh->prepare($sql) or return undef;
408 16 50       956 $sth->execute or return undef;
409 16         427 $sth;
410             }
411              
412             sub primary_key_info {
413 33     33   24593 my ($dbh, $catalog, $schema, $table, $attr) = @_;
414              
415 33         340 my $databases = $dbh->selectall_arrayref("PRAGMA database_list", {Slice => {}});
416              
417 33         4142 my @pk_info;
418 33         90 for my $database (@$databases) {
419 49         116 my $dbname = $database->{name};
420 49 100 66     169 next if defined $schema && $schema ne '%' && $schema ne $dbname;
      100        
421              
422 43         185 my $quoted_dbname = $dbh->quote_identifier($dbname);
423              
424 43 100       1775 my $master_table =
    100          
425             ($dbname eq 'main') ? 'sqlite_master' :
426             ($dbname eq 'temp') ? 'sqlite_temp_master' :
427             $quoted_dbname.'.sqlite_master';
428              
429 43 50       214 my $sth = $dbh->prepare("SELECT name, sql FROM $master_table WHERE type = ?") or return;
430 43 50       1238 $sth->execute("table") or return;
431 43         1234 while(my $row = $sth->fetchrow_hashref) {
432 55         186 my $tbname = $row->{name};
433 55 100 66     849 next if defined $table && $table ne '%' && $table ne $tbname;
      100        
434              
435 33         156 my $quoted_tbname = $dbh->quote_identifier($tbname);
436 33 50       1140 my $t_sth = $dbh->prepare("PRAGMA $quoted_dbname.table_info($quoted_tbname)") or return;
437 33 50       594 $t_sth->execute or return;
438 33         88 my @pk;
439 33         794 while(my $col = $t_sth->fetchrow_hashref) {
440 52 100       968 push @pk, $col->{name} if $col->{pk};
441             }
442              
443             # If there're multiple primary key columns, we need to
444             # find their order from one of the auto-generated unique
445             # indices (note that single column integer primary key
446             # doesn't create an index).
447 33 100 66     212 if (@pk > 1 and $row->{sql} =~ /\bPRIMARY\s+KEY\s*\(\s*
448             (
449             (?:
450             (
451             [a-z_][a-z0-9_]*
452             | (["'`])(?:\3\3|(?!\3).)+?\3(?!\3)
453             | \[[^\]]+\]
454             )
455             \s*,\s*
456             )+
457             (
458             [a-z_][a-z0-9_]*
459             | (["'`])(?:\5\5|(?!\5).)+?\5(?!\5)
460             | \[[^\]]+\]
461             )
462             )
463             \s*\)/six) {
464 4         16 my $pk_sql = $1;
465 4         54 @pk = ();
466 4         49 while($pk_sql =~ /
467             (
468             [a-z_][a-z0-9_]*
469             | (["'`])(?:\2\2|(?!\2).)+?\2(?!\2)
470             | \[([^\]]+)\]
471             )
472             (?:\s*,\s*|$)
473             /sixg) {
474 9         37 my($col, $quote, $brack) = ($1, $2, $3);
475 9 100       31 if ( defined $quote ) {
    100          
476             # Dequote "'`
477 2         6 $col = substr $col, 1, -1;
478 2         26 $col =~ s/$quote$quote/$quote/g;
479             } elsif ( defined $brack ) {
480             # Dequote []
481 1         2 $col = $brack;
482             }
483 9         49 push @pk, $col;
484             }
485             }
486              
487 33 100       196 my $key_name = $row->{sql} =~ /\bCONSTRAINT\s+(\S+|"[^"]+")\s+PRIMARY\s+KEY\s*\(/i ? $1 : 'PRIMARY KEY';
488 33         53 my $key_seq = 0;
489 33         67 foreach my $pk_field (@pk) {
490 38         1163 push @pk_info, {
491             TABLE_SCHEM => $dbname,
492             TABLE_NAME => $tbname,
493             COLUMN_NAME => $pk_field,
494             KEY_SEQ => ++$key_seq,
495             PK_NAME => $key_name,
496             };
497             }
498             }
499             }
500              
501 33 50       184 my $sponge = DBI->connect("DBI:Sponge:", '','')
502             or return $dbh->DBI::set_err($DBI::err, "DBI::Sponge: $DBI::errstr");
503 33         19664 my @names = qw(TABLE_CAT TABLE_SCHEM TABLE_NAME COLUMN_NAME KEY_SEQ PK_NAME);
504             my $sth = $sponge->prepare( "primary_key_info", {
505 33 50       125 rows => [ map { [ @{$_}{@names} ] } @pk_info ],
  38         76  
  38         357  
506             NUM_OF_FIELDS => scalar @names,
507             NAME => \@names,
508             }) or return $dbh->DBI::set_err(
509             $sponge->err,
510             $sponge->errstr,
511             );
512 33         3022 return $sth;
513             }
514              
515              
516             our %DBI_code_for_rule = ( # from DBI doc; curiously, they are not exported
517             # by the DBI module.
518             # codes for update/delete constraints
519             'CASCADE' => 0,
520             'RESTRICT' => 1,
521             'SET NULL' => 2,
522             'NO ACTION' => 3,
523             'SET DEFAULT' => 4,
524              
525             # codes for deferrability
526             'INITIALLY DEFERRED' => 5,
527             'INITIALLY IMMEDIATE' => 6,
528             'NOT DEFERRABLE' => 7,
529             );
530              
531              
532             my @FOREIGN_KEY_INFO_ODBC = (
533             'PKTABLE_CAT', # The primary (unique) key table catalog identifier.
534             'PKTABLE_SCHEM', # The primary (unique) key table schema identifier.
535             'PKTABLE_NAME', # The primary (unique) key table identifier.
536             'PKCOLUMN_NAME', # The primary (unique) key column identifier.
537             'FKTABLE_CAT', # The foreign key table catalog identifier.
538             'FKTABLE_SCHEM', # The foreign key table schema identifier.
539             'FKTABLE_NAME', # The foreign key table identifier.
540             'FKCOLUMN_NAME', # The foreign key column identifier.
541             'KEY_SEQ', # The column sequence number (starting with 1).
542             'UPDATE_RULE', # The referential action for the UPDATE rule.
543             'DELETE_RULE', # The referential action for the DELETE rule.
544             'FK_NAME', # The foreign key name.
545             'PK_NAME', # The primary (unique) key name.
546             'DEFERRABILITY', # The deferrability of the foreign key constraint.
547             'UNIQUE_OR_PRIMARY', # qualifies the key referenced by the foreign key
548             );
549              
550             # Column names below are not used, but listed just for completeness's sake.
551             # Maybe we could add an option so that the user can choose which field
552             # names will be returned; the DBI spec is not very clear about ODBC vs. CLI.
553             my @FOREIGN_KEY_INFO_SQL_CLI = qw(
554             UK_TABLE_CAT
555             UK_TABLE_SCHEM
556             UK_TABLE_NAME
557             UK_COLUMN_NAME
558             FK_TABLE_CAT
559             FK_TABLE_SCHEM
560             FK_TABLE_NAME
561             FK_COLUMN_NAME
562             ORDINAL_POSITION
563             UPDATE_RULE
564             DELETE_RULE
565             FK_NAME
566             UK_NAME
567             DEFERABILITY
568             UNIQUE_OR_PRIMARY
569             );
570              
571             my $DEFERRABLE_RE = qr/
572             (?:(?:
573             on \s+ (?:delete|update) \s+ (?:set \s+ null|set \s+ default|cascade|restrict|no \s+ action)
574             |
575             match \s* (?:\S+|".+?(?<!")")
576             ) \s*)*
577             ((?:not)? \s* deferrable (?: \s* initially \s* (?: immediate | deferred))?)?
578             /sxi;
579              
580             sub foreign_key_info {
581 10     10   15642 my ($dbh, $pk_catalog, $pk_schema, $pk_table, $fk_catalog, $fk_schema, $fk_table) = @_;
582              
583 10 50       91 my $databases = $dbh->selectall_arrayref("PRAGMA database_list", {Slice => {}}) or return;
584              
585 10         1175 my @fk_info;
586             my %table_info;
587 10         27 for my $database (@$databases) {
588 20         45 my $dbname = $database->{name};
589 20 100 66     71 next if defined $fk_schema && $fk_schema ne '%' && $fk_schema ne $dbname;
      100        
590              
591 19         86 my $quoted_dbname = $dbh->quote_identifier($dbname);
592 19 100       572 my $master_table =
    100          
593             ($dbname eq 'main') ? 'sqlite_master' :
594             ($dbname eq 'temp') ? 'sqlite_temp_master' :
595             $quoted_dbname.'.sqlite_master';
596              
597 19 50       130 my $tables = $dbh->selectall_arrayref("SELECT name, sql FROM $master_table WHERE type = ?", undef, "table") or return;
598 19         279 for my $table (@$tables) {
599 34         124 my $tbname = $table->[0];
600 34         47 my $ddl = $table->[1];
601 34         54 my (@rels, %relid2rels);
602 34 100 66     175 next if defined $fk_table && $fk_table ne '%' && $fk_table ne $tbname;
      100        
603              
604 14         89 my $quoted_tbname = $dbh->quote_identifier($tbname);
605 14 50       452 my $sth = $dbh->prepare("PRAGMA $quoted_dbname.foreign_key_list($quoted_tbname)") or return;
606 14 50       155 $sth->execute or return;
607 14         379 while(my $row = $sth->fetchrow_hashref) {
608 18 100 66     149 next if defined $pk_table && $pk_table ne '%' && $pk_table ne $row->{table};
      100        
609              
610 15 100       41 unless ($table_info{$row->{table}}) {
611 13         57 my $quoted_tb = $dbh->quote_identifier($row->{table});
612 13         369 for my $db (@$databases) {
613 15         51 my $quoted_db = $dbh->quote_identifier($db->{name});
614 15 50       387 my $t_sth = $dbh->prepare("PRAGMA $quoted_db.table_info($quoted_tb)") or return;
615 15 50       222 $t_sth->execute or return;
616 15         56 my $cols = {};
617 15         311 while(my $r = $t_sth->fetchrow_hashref) {
618 30         567 $cols->{$r->{name}} = $r->{pk};
619             }
620 15 100       85 if (keys %$cols) {
621             $table_info{$row->{table}} = {
622             schema => $db->{name},
623 13         63 columns => $cols,
624             };
625 13         146 last;
626             }
627             }
628             }
629              
630 15 100 66     112 next if defined $pk_schema && $pk_schema ne '%' && $pk_schema ne $table_info{$row->{table}}{schema};
      100        
631              
632             # cribbed from DBIx::Class::Schema::Loader::DBI::SQLite
633             my $rel = $rels[ $row->{id} ] ||= {
634             local_columns => [],
635             remote_columns => undef,
636             remote_table => $row->{table},
637 13   100     89 };
638 13         22 push @{ $rel->{local_columns} }, $row->{from};
  13         34  
639 13         30 push @{ $rel->{remote_columns} }, $row->{to}
640 13 50       32 if defined $row->{to};
641              
642             my $fk_row = {
643             PKTABLE_CAT => undef,
644             PKTABLE_SCHEM => $table_info{$row->{table}}{schema},
645             PKTABLE_NAME => $row->{table},
646             PKCOLUMN_NAME => $row->{to},
647             FKTABLE_CAT => undef,
648             FKTABLE_SCHEM => $dbname,
649             FKTABLE_NAME => $tbname,
650             FKCOLUMN_NAME => $row->{from},
651             KEY_SEQ => $row->{seq} + 1,
652             UPDATE_RULE => $DBI_code_for_rule{$row->{on_update}},
653             DELETE_RULE => $DBI_code_for_rule{$row->{on_delete}},
654             FK_NAME => undef,
655             PK_NAME => undef,
656             DEFERRABILITY => undef,
657 13 100       159 UNIQUE_OR_PRIMARY => $table_info{$row->{table}}{columns}{$row->{to}} ? 'PRIMARY' : 'UNIQUE',
658             };
659 13         23 push @fk_info, $fk_row;
660 13         17 push @{ $relid2rels{$row->{id}} }, $fk_row; # keep so can fixup
  13         251  
661             }
662              
663             # cribbed from DBIx::Class::Schema::Loader::DBI::SQLite
664             # but with additional parsing of which kind of deferrable
665 14         104 REL: for my $relid (keys %relid2rels) {
666 11         24 my $rel = $rels[$relid];
667 11         16 my $deferrable = $DBI_code_for_rule{'NOT DEFERRABLE'};
668 11         19 my $local_cols = '"?' . (join '"? \s* , \s* "?', map quotemeta, @{ $rel->{local_columns} }) . '"?';
  11         59  
669 11 50       22 my $remote_cols = '"?' . (join '"? \s* , \s* "?', map quotemeta, @{ $rel->{remote_columns} || [] }) . '"?';
  11         50  
670 11     1   1093 my ($deferrable_clause) = $ddl =~ /
  1         757  
  1         16  
  1         16  
671             foreign \s+ key \s* \( \s* $local_cols \s* \) \s* references \s* (?:\S+|".+?(?<!")") \s*
672             (?:\( \s* $remote_cols \s* \) \s*)?
673             $DEFERRABLE_RE
674             /sxi;
675 11 50       29065 if (!$deferrable_clause) {
676             # check for inline constraint if 1 local column
677 11 100       18 if (@{ $rel->{local_columns} } == 1) {
  11         33  
678 9         14 my ($local_col) = @{ $rel->{local_columns} };
  9         21  
679 9 50       15 my ($remote_col) = @{ $rel->{remote_columns} || [] };
  9         24  
680 9   50     859 $remote_col ||= '';
681 9         7708 ($deferrable_clause) = $ddl =~ /
682             "?\Q$local_col\E"? \s* (?:\w+\s*)* (?: \( \s* \d\+ (?:\s*,\s*\d+)* \s* \) )? \s*
683             references \s+ (?:\S+|".+?(?<!")") (?:\s* \( \s* "?\Q$remote_col\E"? \s* \))? \s*
684             $DEFERRABLE_RE
685             /sxi;
686             }
687             }
688 11 100       45 if ($deferrable_clause) {
689             # default is already NOT
690 3 50       12 if ($deferrable_clause !~ /not/i) {
691             $deferrable = $deferrable_clause =~ /deferred/i
692             ? $DBI_code_for_rule{'INITIALLY DEFERRED'}
693 3 50       10 : $DBI_code_for_rule{'INITIALLY IMMEDIATE'};
694             }
695             }
696 11         16 $_->{DEFERRABILITY} = $deferrable for @{ $relid2rels{$relid} };
  11         229  
697             }
698             }
699             }
700              
701 10 50       60 my $sponge_dbh = DBI->connect("DBI:Sponge:", "", "")
702             or return $dbh->DBI::set_err($DBI::err, "DBI::Sponge: $DBI::errstr");
703             my $sponge_sth = $sponge_dbh->prepare("foreign_key_info", {
704             NAME => \@FOREIGN_KEY_INFO_ODBC,
705 10 50       4434 rows => [ map { [@{$_}{@FOREIGN_KEY_INFO_ODBC} ] } @fk_info ],
  13         23  
  13         161  
706             NUM_OF_FIELDS => scalar(@FOREIGN_KEY_INFO_ODBC),
707             }) or return $dbh->DBI::set_err(
708             $sponge_dbh->err,
709             $sponge_dbh->errstr,
710             );
711 10         1168 return $sponge_sth;
712             }
713              
714             my @STATISTICS_INFO_ODBC = (
715             'TABLE_CAT', # The catalog identifier.
716             'TABLE_SCHEM', # The schema identifier.
717             'TABLE_NAME', # The table identifier.
718             'NON_UNIQUE', # Unique index indicator.
719             'INDEX_QUALIFIER', # Index qualifier identifier.
720             'INDEX_NAME', # The index identifier.
721             'TYPE', # The type of information being returned.
722             'ORDINAL_POSITION', # Column sequence number (starting with 1).
723             'COLUMN_NAME', # The column identifier.
724             'ASC_OR_DESC', # Column sort sequence.
725             'CARDINALITY', # Cardinality of the table or index.
726             'PAGES', # Number of storage pages used by this table or index.
727             'FILTER_CONDITION', # The index filter condition as a string.
728             );
729              
730             sub statistics_info {
731 4     4   51820 my ($dbh, $catalog, $schema, $table, $unique_only, $quick) = @_;
732              
733 4 50       44 my $databases = $dbh->selectall_arrayref("PRAGMA database_list", {Slice => {}}) or return;
734              
735 4         488 my @statistics_info;
736 4         17 for my $database (@$databases) {
737 8         22 my $dbname = $database->{name};
738 8 0 33     25 next if defined $schema && $schema ne '%' && $schema ne $dbname;
      33        
739              
740 8         34 my $quoted_dbname = $dbh->quote_identifier($dbname);
741 8 50       240 my $master_table =
    100          
742             ($dbname eq 'main') ? 'sqlite_master' :
743             ($dbname eq 'temp') ? 'sqlite_temp_master' :
744             $quoted_dbname.'.sqlite_master';
745              
746 8 50       52 my $tables = $dbh->selectall_arrayref("SELECT name FROM $master_table WHERE type = ?", undef, "table") or return;
747 8         118 for my $table_ref (@$tables) {
748 8         23 my $tbname = $table_ref->[0];
749 8 100 33     65 next if defined $table && $table ne '%' && uc($table) ne uc($tbname);
      66        
750              
751 4         19 my $quoted_tbname = $dbh->quote_identifier($tbname);
752 4 50       137 my $sth = $dbh->prepare("PRAGMA $quoted_dbname.index_list($quoted_tbname)") or return;
753 4 50       50 $sth->execute or return;
754 4         95 while(my $row = $sth->fetchrow_hashref) {
755              
756 16 100 100     132 next if $unique_only && !$row->{unique};
757 12         46 my $quoted_idx = $dbh->quote_identifier($row->{name});
758 12         332 for my $db (@$databases) {
759 24         86 my $quoted_db = $dbh->quote_identifier($db->{name});
760 24 50       625 my $i_sth = $dbh->prepare("PRAGMA $quoted_db.index_info($quoted_idx)") or return;
761 24 50       191 $i_sth->execute or return;
762 24         62 my $cols = {};
763 24         669 while(my $info = $i_sth->fetchrow_hashref) {
764             push @statistics_info, {
765             TABLE_CAT => undef,
766             TABLE_SCHEM => $db->{name},
767             TABLE_NAME => $tbname,
768             NON_UNIQUE => $row->{unique} ? 0 : 1,
769             INDEX_QUALIFIER => undef,
770             INDEX_NAME => $row->{name},
771             TYPE => 'btree', # see https://www.sqlite.org/version3.html esp. "Traditional B-trees are still used for indices"
772             ORDINAL_POSITION => $info->{seqno} + 1,
773             COLUMN_NAME => $info->{name},
774 16 100       560 ASC_OR_DESC => undef,
775             CARDINALITY => undef,
776             PAGES => undef,
777             FILTER_CONDITION => undef,
778             };
779             }
780             }
781             }
782             }
783             }
784              
785 4 50       21 my $sponge_dbh = DBI->connect("DBI:Sponge:", "", "")
786             or return $dbh->DBI::set_err($DBI::err, "DBI::Sponge: $DBI::errstr");
787             my $sponge_sth = $sponge_dbh->prepare("statistics_info", {
788             NAME => \@STATISTICS_INFO_ODBC,
789 4 50       3023 rows => [ map { [@{$_}{@STATISTICS_INFO_ODBC} ] } @statistics_info ],
  16         25  
  16         159  
790             NUM_OF_FIELDS => scalar(@STATISTICS_INFO_ODBC),
791             }) or return $dbh->DBI::set_err(
792             $sponge_dbh->err,
793             $sponge_dbh->errstr,
794             );
795 4         572 return $sponge_sth;
796             }
797              
798             my @TypeInfoKeys = qw/
799             TYPE_NAME
800             DATA_TYPE
801             COLUMN_SIZE
802             LITERAL_PREFIX
803             LITERAL_SUFFIX
804             CREATE_PARAMS
805             NULLABLE
806             CASE_SENSITIVE
807             SEARCHABLE
808             UNSIGNED_ATTRIBUTE
809             FIXED_PREC_SCALE
810             AUTO_UNIQUE_VALUE
811             LOCAL_TYPE_NAME
812             MINIMUM_SCALE
813             MAXIMUM_SCALE
814             SQL_DATA_TYPE
815             SQL_DATETIME_SUB
816             NUM_PREC_RADIX
817             INTERVAL_PRECISION
818             /;
819              
820             my %TypeInfo = (
821             SQL_INTEGER ,=> {
822             TYPE_NAME => 'INTEGER',
823             DATA_TYPE => SQL_INTEGER,
824             NULLABLE => 2, # no for integer primary key, otherwise yes
825             SEARCHABLE => 3,
826             },
827             SQL_DOUBLE ,=> {
828             TYPE_NAME => 'REAL',
829             DATA_TYPE => SQL_DOUBLE,
830             NULLABLE => 1,
831             SEARCHABLE => 3,
832             },
833             SQL_VARCHAR ,=> {
834             TYPE_NAME => 'TEXT',
835             DATA_TYPE => SQL_VARCHAR,
836             LITERAL_PREFIX => "'",
837             LITERAL_SUFFIX => "'",
838             NULLABLE => 1,
839             SEARCHABLE => 3,
840             },
841             SQL_BLOB ,=> {
842             TYPE_NAME => 'BLOB',
843             DATA_TYPE => SQL_BLOB,
844             NULLABLE => 1,
845             SEARCHABLE => 3,
846             },
847             SQL_UNKNOWN_TYPE ,=> {
848             DATA_TYPE => SQL_UNKNOWN_TYPE,
849             },
850             );
851              
852             sub type_info_all {
853 0     0   0 my $idx = 0;
854              
855 0         0 my @info = ({map {$_ => $idx++} @TypeInfoKeys});
  0         0  
856 0         0 for my $id (sort {$a <=> $b} keys %TypeInfo) {
  0         0  
857 0         0 push @info, [map {$TypeInfo{$id}{$_}} @TypeInfoKeys];
  0         0  
858             }
859 0         0 return \@info;
860             }
861              
862             my @COLUMN_INFO = qw(
863             TABLE_CAT
864             TABLE_SCHEM
865             TABLE_NAME
866             COLUMN_NAME
867             DATA_TYPE
868             TYPE_NAME
869             COLUMN_SIZE
870             BUFFER_LENGTH
871             DECIMAL_DIGITS
872             NUM_PREC_RADIX
873             NULLABLE
874             REMARKS
875             COLUMN_DEF
876             SQL_DATA_TYPE
877             SQL_DATETIME_SUB
878             CHAR_OCTET_LENGTH
879             ORDINAL_POSITION
880             IS_NULLABLE
881             );
882              
883             sub column_info {
884 7     7   5936 my ($dbh, $cat_val, $sch_val, $tbl_val, $col_val) = @_;
885              
886 7 100 100     67 if ( defined $col_val and $col_val eq '%' ) {
887 1         3 $col_val = undef;
888             }
889              
890             # Get a list of all tables ordered by TABLE_SCHEM, TABLE_NAME
891 7         40 my $sql = <<'END_SQL';
892             SELECT TABLE_SCHEM, tbl_name TABLE_NAME
893             FROM (
894             SELECT 'main' TABLE_SCHEM, tbl_name
895             FROM sqlite_master
896             WHERE type IN ('table','view')
897             UNION ALL
898             SELECT 'temp' TABLE_SCHEM, tbl_name
899             FROM sqlite_temp_master
900             WHERE type IN ('table','view')
901             END_SQL
902              
903 7         27 for my $db_name (_attached_database_list($dbh)) {
904 2         11 $sql .= <<"END_SQL";
905             UNION ALL
906             SELECT '$db_name' TABLE_SCHEM, tbl_name
907             FROM "$db_name".sqlite_master
908             WHERE type IN ('table','view')
909             END_SQL
910             }
911              
912 7         32 $sql .= <<'END_SQL';
913             UNION ALL
914             SELECT 'main' TABLE_SCHEM, 'sqlite_master' tbl_name
915             UNION ALL
916             SELECT 'temp' TABLE_SCHEM, 'sqlite_temp_master' tbl_name
917             )
918             END_SQL
919              
920 7         14 my @where;
921 7 50       18 if ( defined $sch_val ) {
922 0         0 push @where, "TABLE_SCHEM LIKE '$sch_val'";
923             }
924 7 50       17 if ( defined $tbl_val ) {
925 7         33 push @where, "TABLE_NAME LIKE '$tbl_val'";
926             }
927 7 50       35 $sql .= ' WHERE ' . join("\n AND ", @where ) . "\n" if @where;
928 7         26 $sql .= " ORDER BY TABLE_SCHEM, TABLE_NAME\n";
929 7 50       30 my $sth_tables = $dbh->prepare($sql) or return undef;
930 7 50       558 $sth_tables->execute or return undef;
931              
932             # Taken from Fey::Loader::SQLite
933 7         32 my @cols;
934 7         137 while ( my ($schema, $table) = $sth_tables->fetchrow_array ) {
935 9 50       61 my $sth_columns = $dbh->prepare(qq{PRAGMA "$schema".table_info("$table")}) or return;
936 9 50       99 $sth_columns->execute or return;
937              
938 9         228 for ( my $position = 1; my $col_info = $sth_columns->fetchrow_hashref; $position++ ) {
939 20 100       56 if ( defined $col_val ) {
940             # This must do a LIKE comparison
941 14 50       82 my $sth = $dbh->prepare("SELECT '$col_info->{name}' LIKE '$col_val'") or return undef;
942 14 50       163 $sth->execute or return undef;
943             # Skip columns that don't match $col_val
944 14 100       420 next unless ($sth->fetchrow_array)[0];
945             }
946              
947             my %col = (
948             TABLE_SCHEM => $schema,
949             TABLE_NAME => $table,
950             COLUMN_NAME => $col_info->{name},
951 13         83 ORDINAL_POSITION => $position,
952             );
953              
954 13         27 my $type = $col_info->{type};
955 13 100       89 if ( $type =~ s/(\w+)\s*\(\s*(\d+)(?:\s*,\s*(\d+))?\s*\)/$1/ ) {
956 7         30 $col{COLUMN_SIZE} = $2;
957 7         17 $col{DECIMAL_DIGITS} = $3;
958             }
959              
960 13         28 $col{TYPE_NAME} = $type;
961              
962 13 50       31 if ( defined $col_info->{dflt_value} ) {
963             $col{COLUMN_DEF} = $col_info->{dflt_value}
964 0         0 }
965              
966 13 100       39 if ( $col_info->{notnull} ) {
967 2         6 $col{NULLABLE} = 0;
968 2         4 $col{IS_NULLABLE} = 'NO';
969             } else {
970 11         29 $col{NULLABLE} = 1;
971 11         21 $col{IS_NULLABLE} = 'YES';
972             }
973              
974 13         251 push @cols, \%col;
975             }
976 9         176 $sth_columns->finish;
977             }
978 7         63 $sth_tables->finish;
979              
980 7 50       38 my $sponge = DBI->connect("DBI:Sponge:", '','')
981             or return $dbh->DBI::set_err($DBI::err, "DBI::Sponge: $DBI::errstr");
982             $sponge->prepare( "column_info", {
983 7 50       8409 rows => [ map { [ @{$_}{@COLUMN_INFO} ] } @cols ],
  13         28  
  13         157  
984             NUM_OF_FIELDS => scalar @COLUMN_INFO,
985             NAME => [ @COLUMN_INFO ],
986             } ) or return $dbh->DBI::set_err(
987             $sponge->err,
988             $sponge->errstr,
989             );
990             }
991              
992             #======================================================================
993             # An internal tied hash package used for %DBD::SQLite::COLLATION, to
994             # prevent people from unintentionally overriding globally registered collations.
995              
996             package # hide from PAUSE
997             DBD::SQLite::_WriteOnceHash;
998              
999             require Tie::Hash;
1000              
1001             our @ISA = qw(Tie::StdHash);
1002              
1003             sub TIEHASH {
1004 116     116   493 bless {}, $_[0];
1005             }
1006              
1007             sub STORE {
1008 237 100   237   2517 ! exists $_[0]->{$_[1]} or die "entry $_[1] already registered";
1009 235         916 $_[0]->{$_[1]} = $_[2];
1010             }
1011              
1012             sub DELETE {
1013 1     1   550 die "deletion of entry $_[1] is forbidden";
1014             }
1015              
1016             1;
1017              
1018             __END__
1019              
1020             =pod
1021              
1022             =encoding utf-8
1023              
1024             =head1 NAME
1025              
1026             DBD::SQLite - Self-contained RDBMS in a DBI Driver
1027              
1028             =head1 SYNOPSIS
1029              
1030             use DBI;
1031             my $dbh = DBI->connect("dbi:SQLite:dbname=$dbfile","","");
1032              
1033             =head1 DESCRIPTION
1034              
1035             SQLite is a public domain file-based relational database engine that
1036             you can find at L<https://www.sqlite.org/>.
1037              
1038             B<DBD::SQLite> is a Perl DBI driver for SQLite, that includes
1039             the entire thing in the distribution.
1040             So in order to get a fast transaction capable RDBMS working for your
1041             perl project you simply have to install this module, and B<nothing>
1042             else.
1043              
1044             SQLite supports the following features:
1045              
1046             =over 4
1047              
1048             =item Implements a large subset of SQL92
1049              
1050             See L<https://www.sqlite.org/lang.html> for details.
1051              
1052             =item A complete DB in a single disk file
1053              
1054             Everything for your database is stored in a single disk file, making it
1055             easier to move things around than with L<DBD::CSV>.
1056              
1057             =item Atomic commit and rollback
1058              
1059             Yes, B<DBD::SQLite> is small and light, but it supports full transactions!
1060              
1061             =item Extensible
1062              
1063             User-defined aggregate or regular functions can be registered with the
1064             SQL parser.
1065              
1066             =back
1067              
1068             There's lots more to it, so please refer to the docs on the SQLite web
1069             page, listed above, for SQL details. Also refer to L<DBI> for details
1070             on how to use DBI itself. The API works like every DBI module does.
1071             However, currently many statement attributes are not implemented or
1072             are limited by the typeless nature of the SQLite database.
1073              
1074             =head1 SQLITE VERSION
1075              
1076             DBD::SQLite is usually compiled with a bundled SQLite library
1077             (SQLite version S<3.42.0> as of this release) for consistency.
1078             However, a different version of SQLite may sometimes be used for
1079             some reasons like security, or some new experimental features.
1080              
1081             You can look at C<$DBD::SQLite::sqlite_version> (C<3.x.y> format) or
1082             C<$DBD::SQLite::sqlite_version_number> (C<3xxxyyy> format)
1083             to find which version of SQLite is actually used. You can also
1084             check C<DBD::SQLite::Constants::SQLITE_VERSION_NUMBER()>.
1085              
1086             You can also find how the library is compiled by calling
1087             C<DBD::SQLite::compile_options()> (see below).
1088              
1089             =head1 NOTABLE DIFFERENCES FROM OTHER DRIVERS
1090              
1091             =head2 Database Name Is A File Name
1092              
1093             SQLite creates a file per a database. You should pass the C<path> of
1094             the database file (with or without a parent directory) in the DBI
1095             connection string (as a database C<name>):
1096              
1097             my $dbh = DBI->connect("dbi:SQLite:dbname=$dbfile","","");
1098              
1099             The file is opened in read/write mode, and will be created if
1100             it does not exist yet.
1101              
1102             Although the database is stored in a single file, the directory
1103             containing the database file must be writable by SQLite because the
1104             library will create several temporary files there.
1105              
1106             If the filename C<$dbfile> is ":memory:", then a private, temporary
1107             in-memory database is created for the connection. This in-memory
1108             database will vanish when the database connection is closed.
1109             It is handy for your library tests.
1110              
1111             Note that future versions of SQLite might make use of additional
1112             special filenames that begin with the ":" character. It is recommended
1113             that when a database filename actually does begin with a ":" character
1114             you should prefix the filename with a pathname such as "./" to avoid
1115             ambiguity.
1116              
1117             If the filename C<$dbfile> is an empty string, then a private,
1118             temporary on-disk database will be created. This private database will
1119             be automatically deleted as soon as the database connection is closed.
1120              
1121             As of 1.41_01, you can pass URI filename (see L<https://www.sqlite.org/uri.html>)
1122             as well for finer control:
1123              
1124             my $dbh = DBI->connect("dbi:SQLite:uri=file:$path_to_dbfile?mode=rwc");
1125              
1126             Note that this is not for remote SQLite database connection. You can
1127             only connect to a local database.
1128              
1129             =head2 Read-Only Database
1130              
1131             You can set sqlite_open_flags (only) when you connect to a database:
1132              
1133             use DBD::SQLite::Constants qw/:file_open/;
1134             my $dbh = DBI->connect("dbi:SQLite:$dbfile", undef, undef, {
1135             sqlite_open_flags => SQLITE_OPEN_READONLY,
1136             });
1137              
1138             See L<https://www.sqlite.org/c3ref/open.html> for details.
1139              
1140             As of 1.49_05, you can also make a database read-only by setting
1141             C<ReadOnly> attribute to true (only) when you connect to a database.
1142             Actually you can set it after you connect, but in that case, it
1143             can't make the database read-only, and you'll see a warning (which
1144             you can hide by turning C<PrintWarn> off).
1145              
1146             =head2 DBD::SQLite And File::Temp
1147              
1148             When you use L<File::Temp> to create a temporary file/directory for
1149             SQLite databases, you need to remember:
1150              
1151             =over 4
1152              
1153             =item tempfile may be locked exclusively
1154              
1155             You may want to use C<tempfile()> to create a temporary database
1156             filename for DBD::SQLite, but as noted in L<File::Temp>'s POD,
1157             this file may have an exclusive lock under some operating systems
1158             (notably Mac OSX), and result in a "database is locked" error.
1159             To avoid this, set EXLOCK option to false when you call tempfile().
1160              
1161             ($fh, $filename) = tempfile($template, EXLOCK => 0);
1162              
1163             =item CLEANUP may not work unless a database is disconnected
1164              
1165             When you set CLEANUP option to true when you create a temporary
1166             directory with C<tempdir()> or C<newdir()>, you may have to
1167             disconnect databases explicitly before the temporary directory
1168             is gone (notably under MS Windows).
1169              
1170             =back
1171              
1172             (The above is quoted from the pod of File::Temp.)
1173              
1174             If you don't need to keep or share a temporary database,
1175             use ":memory:" database instead. It's much handier and cleaner
1176             for ordinary testing.
1177              
1178             =head2 DBD::SQLite and fork()
1179              
1180             Follow the advice in the SQLite FAQ (L<https://sqlite.org/faq.html>).
1181              
1182             =over 4
1183              
1184             Under Unix, you should not carry an open SQLite database across
1185             a fork() system call into the child process. Problems will result
1186             if you do.
1187              
1188             =back
1189              
1190             You shouldn't (re)use a database handle you created (probably to
1191             set up a database schema etc) before you fork(). Otherwise, you
1192             might see a database corruption in the worst case.
1193              
1194             If you need to fork(), (re)open a database after you fork().
1195             You might also want to tweak C<sqlite_busy_timeout> and
1196             C<sqlite_use_immediate_transaction> (see below), depending
1197             on your needs.
1198              
1199             If you need a higher level of concurrency than SQLite supports,
1200             consider using other client/server database engines.
1201              
1202             =head2 Accessing A Database With Other Tools
1203              
1204             To access the database from the command line, try using C<dbish>
1205             which comes with the L<DBI::Shell> module. Just type:
1206              
1207             dbish dbi:SQLite:foo.db
1208              
1209             On the command line to access the file F<foo.db>.
1210              
1211             Alternatively you can install SQLite from the link above without
1212             conflicting with B<DBD::SQLite> and use the supplied C<sqlite3>
1213             command line tool.
1214              
1215             =head2 Blobs
1216              
1217             As of version 1.11, blobs should "just work" in SQLite as text columns.
1218             However this will cause the data to be treated as a string, so SQL
1219             statements such as length(x) will return the length of the column as a NUL
1220             terminated string, rather than the size of the blob in bytes. In order to
1221             store natively as a BLOB use the following code:
1222              
1223             use DBI qw(:sql_types);
1224             my $dbh = DBI->connect("dbi:SQLite:dbfile","","");
1225            
1226             my $blob = `cat foo.jpg`;
1227             my $sth = $dbh->prepare("INSERT INTO mytable VALUES (1, ?)");
1228             $sth->bind_param(1, $blob, SQL_BLOB);
1229             $sth->execute();
1230              
1231             And then retrieval just works:
1232              
1233             $sth = $dbh->prepare("SELECT * FROM mytable WHERE id = 1");
1234             $sth->execute();
1235             my $row = $sth->fetch;
1236             my $blobo = $row->[1];
1237            
1238             # now $blobo == $blob
1239              
1240             =head2 Functions And Bind Parameters
1241              
1242             As of this writing, a SQL that compares a return value of a function
1243             with a numeric bind value like this doesn't work as you might expect.
1244              
1245             my $sth = $dbh->prepare(q{
1246             SELECT bar FROM foo GROUP BY bar HAVING count(*) > ?;
1247             });
1248             $sth->execute(5);
1249              
1250             This is because DBD::SQLite assumes that all the bind values are text
1251             (and should be quoted) by default. Thus the above statement becomes
1252             like this while executing:
1253              
1254             SELECT bar FROM foo GROUP BY bar HAVING count(*) > "5";
1255              
1256             There are four workarounds for this.
1257              
1258             =over 4
1259              
1260             =item Use bind_param() explicitly
1261              
1262             As shown above in the C<BLOB> section, you can always use
1263             C<bind_param()> to tell the type of a bind value.
1264              
1265             use DBI qw(:sql_types); # Don't forget this
1266            
1267             my $sth = $dbh->prepare(q{
1268             SELECT bar FROM foo GROUP BY bar HAVING count(*) > ?;
1269             });
1270             $sth->bind_param(1, 5, SQL_INTEGER);
1271             $sth->execute();
1272              
1273             =item Add zero to make it a number
1274              
1275             This is somewhat weird, but works anyway.
1276              
1277             my $sth = $dbh->prepare(q{
1278             SELECT bar FROM foo GROUP BY bar HAVING count(*) > (? + 0);
1279             });
1280             $sth->execute(5);
1281              
1282             =item Use SQL cast() function
1283              
1284             This is more explicit way to do the above.
1285              
1286             my $sth = $dbh->prepare(q{
1287             SELECT bar FROM foo GROUP BY bar HAVING count(*) > cast(? as integer);
1288             });
1289             $sth->execute(5);
1290              
1291             =item Set C<sqlite_see_if_its_a_number> database handle attribute
1292              
1293             As of version 1.32_02, you can use C<sqlite_see_if_its_a_number>
1294             to let DBD::SQLite to see if the bind values are numbers or not.
1295              
1296             $dbh->{sqlite_see_if_its_a_number} = 1;
1297             my $sth = $dbh->prepare(q{
1298             SELECT bar FROM foo GROUP BY bar HAVING count(*) > ?;
1299             });
1300             $sth->execute(5);
1301              
1302             You can set it to true when you connect to a database.
1303              
1304             my $dbh = DBI->connect('dbi:SQLite:foo', undef, undef, {
1305             AutoCommit => 1,
1306             RaiseError => 1,
1307             sqlite_see_if_its_a_number => 1,
1308             });
1309              
1310             This is the most straightforward solution, but as noted above,
1311             existing data in your databases created by DBD::SQLite have not
1312             always been stored as numbers, so this *might* cause other obscure
1313             problems. Use this sparingly when you handle existing databases.
1314             If you handle databases created by other tools like native C<sqlite3>
1315             command line tool, this attribute would help you.
1316              
1317             As of 1.41_04, C<sqlite_see_if_its_a_number> works only for
1318             bind values with no explicit type.
1319              
1320             my $dbh = DBI->connect('dbi:SQLite:foo', undef, undef, {
1321             AutoCommit => 1,
1322             RaiseError => 1,
1323             sqlite_see_if_its_a_number => 1,
1324             });
1325             my $sth = $dbh->prepare('INSERT INTO foo VALUES(?)');
1326             # '1.230' will be inserted as a text, instead of 1.23 as a number,
1327             # even though sqlite_see_if_its_a_number is set.
1328             $sth->bind_param(1, '1.230', SQL_VARCHAR);
1329             $sth->execute;
1330              
1331             =back
1332              
1333             =head2 Placeholders
1334              
1335             SQLite supports several placeholder expressions, including C<?>
1336             and C<:AAAA>. Consult the L<DBI> and SQLite documentation for
1337             details.
1338              
1339             L<https://www.sqlite.org/lang_expr.html#varparam>
1340              
1341             Note that a question mark actually means a next unused (numbered)
1342             placeholder. You're advised not to use it with other (numbered or
1343             named) placeholders to avoid confusion.
1344              
1345             my $sth = $dbh->prepare(
1346             'update TABLE set a=?1 where b=?2 and a IS NOT ?1'
1347             );
1348             $sth->execute(1, 2);
1349              
1350             =head2 Pragma
1351              
1352             SQLite has a set of "Pragma"s to modify its operation or to query
1353             for its internal data. These are specific to SQLite and are not
1354             likely to work with other DBD libraries, but you may find some of
1355             these are quite useful, including:
1356              
1357             =over 4
1358              
1359             =item journal_mode
1360              
1361             You can use this pragma to change the journal mode for SQLite
1362             databases, maybe for better performance, or for compatibility.
1363              
1364             Its default mode is C<DELETE>, which means SQLite uses a rollback
1365             journal to implement transactions, and the journal is deleted
1366             at the conclusion of each transaction. If you use C<TRUNCATE>
1367             instead of C<DELETE>, the journal will be truncated, which is
1368             usually much faster.
1369              
1370             A C<WAL> (write-ahead log) mode is introduced as of SQLite 3.7.0.
1371             This mode is persistent, and it stays in effect even after
1372             closing and reopening the database. In other words, once the C<WAL>
1373             mode is set in an application or in a test script, the database
1374             becomes inaccessible by older clients. This tends to be an issue
1375             when you use a system C<sqlite3> executable under a conservative
1376             operating system.
1377              
1378             To fix this, You need to issue C<PRAGMA journal_mode = DELETE>
1379             (or C<TRUNCATE>) beforehand, or install a newer version of
1380             C<sqlite3>.
1381              
1382             =item legacy_file_format
1383              
1384             If you happen to need to create a SQLite database that will also
1385             be accessed by a very old SQLite client (prior to 3.3.0 released
1386             in Jan. 2006), you need to set this pragma to ON before you create
1387             a database.
1388              
1389             =item reverse_unordered_selects
1390              
1391             You can set this pragma to ON to reverse the order of results of
1392             SELECT statements without an ORDER BY clause so that you can see
1393             if applications are making invalid assumptions about the result
1394             order.
1395              
1396             Note that SQLite 3.7.15 (bundled with DBD::SQLite 1.38_02) enhanced
1397             its query optimizer and the order of results of a SELECT statement
1398             without an ORDER BY clause may be different from the one of the
1399             previous versions.
1400              
1401             =item synchronous
1402              
1403             You can set set this pragma to OFF to make some of the operations
1404             in SQLite faster with a possible risk of database corruption
1405             in the worst case. See also L</"Performance"> section below.
1406              
1407             =back
1408              
1409             See L<https://www.sqlite.org/pragma.html> for more details.
1410              
1411             =head2 Foreign Keys
1412              
1413             SQLite has started supporting foreign key constraints since 3.6.19
1414             (released on Oct 14, 2009; bundled in DBD::SQLite 1.26_05).
1415             To be exact, SQLite has long been able to parse a schema with foreign
1416             keys, but the constraints has not been enforced. Now you can issue
1417             a C<foreign_keys> pragma to enable this feature and enforce the
1418             constraints, preferably as soon as you connect to a database and
1419             you're not in a transaction:
1420              
1421             $dbh->do("PRAGMA foreign_keys = ON");
1422              
1423             And you can explicitly disable the feature whenever you like by
1424             turning the pragma off:
1425              
1426             $dbh->do("PRAGMA foreign_keys = OFF");
1427              
1428             As of this writing, this feature is disabled by default by the
1429             SQLite team, and by us, to secure backward compatibility, as
1430             this feature may break your applications, and actually broke
1431             some for us. If you have used a schema with foreign key constraints
1432             but haven't cared them much and supposed they're always ignored for
1433             SQLite, be prepared, and please do extensive testing to ensure
1434             that your applications will continue to work when the foreign keys
1435             support is enabled by default.
1436              
1437             See L<https://www.sqlite.org/foreignkeys.html> for details.
1438              
1439             =head2 Transactions
1440              
1441             DBI/DBD::SQLite's transactions may be a bit confusing. They behave
1442             differently according to the status of the C<AutoCommit> flag:
1443              
1444             =over 4
1445              
1446             =item When the AutoCommit flag is on
1447              
1448             You're supposed to always use the auto-commit mode, except you
1449             explicitly begin a transaction, and when the transaction ended,
1450             you're supposed to go back to the auto-commit mode. To begin a
1451             transaction, call C<begin_work> method, or issue a C<BEGIN>
1452             statement. To end it, call C<commit/rollback> methods, or issue
1453             the corresponding statements.
1454              
1455             $dbh->{AutoCommit} = 1;
1456            
1457             $dbh->begin_work; # or $dbh->do('BEGIN TRANSACTION');
1458            
1459             # $dbh->{AutoCommit} is turned off temporarily during a transaction;
1460            
1461             $dbh->commit; # or $dbh->do('COMMIT');
1462            
1463             # $dbh->{AutoCommit} is turned on again;
1464              
1465             =item When the AutoCommit flag is off
1466              
1467             You're supposed to always use the transactional mode, until you
1468             explicitly turn on the AutoCommit flag. You can explicitly issue
1469             a C<BEGIN> statement (only when an actual transaction has not
1470             begun yet) but you're not allowed to call C<begin_work> method
1471             (if you don't issue a C<BEGIN>, it will be issued internally).
1472             You can commit or roll it back freely. Another transaction will
1473             automatically begin if you execute another statement.
1474              
1475             $dbh->{AutoCommit} = 0;
1476            
1477             # $dbh->do('BEGIN TRANSACTION') is not necessary, but possible
1478            
1479             ...
1480            
1481             $dbh->commit; # or $dbh->do('COMMIT');
1482            
1483             # $dbh->{AutoCommit} stays intact;
1484            
1485             $dbh->{AutoCommit} = 1; # ends the transactional mode
1486              
1487             =back
1488              
1489             This C<AutoCommit> mode is independent from the autocommit mode
1490             of the internal SQLite library, which always begins by a C<BEGIN>
1491             statement, and ends by a C<COMMIT> or a C<ROLLBACK>.
1492              
1493             =head2 Transaction and Database Locking
1494              
1495             The default transaction behavior of SQLite is C<deferred>, that
1496             means, locks are not acquired until the first read or write
1497             operation, and thus it is possible that another thread or process
1498             could create a separate transaction and write to the database after
1499             the C<BEGIN> on the current thread has executed, and eventually
1500             cause a "deadlock". To avoid this, DBD::SQLite internally issues
1501             a C<BEGIN IMMEDIATE> if you begin a transaction by calling
1502             C<begin_work> or by turning off C<AutoCommit> (since 1.38_01).
1503              
1504             If you really need to turn off this feature for some reasons,
1505             set C<sqlite_use_immediate_transaction> database handle attribute
1506             to false, and the default C<deferred> transaction will be used.
1507              
1508             my $dbh = DBI->connect("dbi:SQLite::memory:", "", "", {
1509             sqlite_use_immediate_transaction => 0,
1510             });
1511              
1512             Or, issue a C<BEGIN> statement explicitly each time you begin
1513             a transaction.
1514              
1515             See L<http://sqlite.org/lockingv3.html> for locking details.
1516              
1517             =head2 C<< $sth->finish >> and Transaction Rollback
1518              
1519             As the L<DBI> doc says, you almost certainly do B<not> need to
1520             call L<DBI/finish> method if you fetch all rows (probably in a loop).
1521             However, there are several exceptions to this rule, and rolling-back
1522             of an unfinished C<SELECT> statement is one of such exceptional
1523             cases.
1524              
1525             SQLite prohibits C<ROLLBACK> of unfinished C<SELECT> statements in
1526             a transaction (See L<http://sqlite.org/lang_transaction.html> for
1527             details). So you need to call C<finish> before you issue a rollback.
1528              
1529             $sth = $dbh->prepare("SELECT * FROM t");
1530             $dbh->begin_work;
1531             eval {
1532             $sth->execute;
1533             $row = $sth->fetch;
1534             ...
1535             die "For some reason";
1536             ...
1537             };
1538             if($@) {
1539             $sth->finish; # You need this for SQLite
1540             $dbh->rollback;
1541             } else {
1542             $dbh->commit;
1543             }
1544              
1545             =head2 Processing Multiple Statements At A Time
1546              
1547             L<DBI>'s statement handle is not supposed to process multiple
1548             statements at a time. So if you pass a string that contains multiple
1549             statements (a C<dump>) to a statement handle (via C<prepare> or C<do>),
1550             L<DBD::SQLite> only processes the first statement, and discards the
1551             rest.
1552              
1553             If you need to process multiple statements at a time, set
1554             a C<sqlite_allow_multiple_statements> attribute of a database handle
1555             to true when you connect to a database, and C<do> method takes care
1556             of the rest (since 1.30_01, and without creating DBI's statement
1557             handles internally since 1.47_01). If you do need to use C<prepare>
1558             or C<prepare_cached> (which I don't recommend in this case, because
1559             typically there's no placeholder nor reusable part in a dump),
1560             you can look at C<< $sth->{sqlite_unprepared_statements} >> to retrieve
1561             what's left, though it usually contains nothing but white spaces.
1562              
1563             =head2 TYPE statement attribute
1564              
1565             Because of historical reasons, DBD::SQLite's C<TYPE> statement
1566             handle attribute returns an array ref of string values, contrary to
1567             the DBI specification. This value is also less useful for SQLite
1568             users because SQLite uses dynamic type system (that means,
1569             the datatype of a value is associated with the value itself, not
1570             with its container).
1571              
1572             As of version 1.61_02, if you set C<sqlite_prefer_numeric_type>
1573             database handle attribute to true, C<TYPE> statement handle
1574             attribute returns an array of integer, as an experiment.
1575              
1576             =head2 Performance
1577              
1578             SQLite is fast, very fast. Matt processed his 72MB log file with it,
1579             inserting the data (400,000+ rows) by using transactions and only
1580             committing every 1000 rows (otherwise the insertion is quite slow),
1581             and then performing queries on the data.
1582              
1583             Queries like count(*) and avg(bytes) took fractions of a second to
1584             return, but what surprised him most of all was:
1585              
1586             SELECT url, count(*) as count
1587             FROM access_log
1588             GROUP BY url
1589             ORDER BY count desc
1590             LIMIT 20
1591              
1592             To discover the top 20 hit URLs on the site (L<http://axkit.org>),
1593             and it returned within 2 seconds. He was seriously considering
1594             switching his log analysis code to use this little speed demon!
1595              
1596             Oh yeah, and that was with no indexes on the table, on a 400MHz PIII.
1597              
1598             For best performance be sure to tune your hdparm settings if you
1599             are using linux. Also you might want to set:
1600              
1601             PRAGMA synchronous = OFF
1602              
1603             Which will prevent SQLite from doing fsync's when writing (which
1604             slows down non-transactional writes significantly) at the expense
1605             of some peace of mind. Also try playing with the cache_size pragma.
1606              
1607             The memory usage of SQLite can also be tuned using the cache_size
1608             pragma.
1609              
1610             $dbh->do("PRAGMA cache_size = 800000");
1611              
1612             The above will allocate 800M for DB cache; the default is 2M.
1613             Your sweet spot probably lies somewhere in between.
1614              
1615             =head1 DRIVER PRIVATE ATTRIBUTES
1616              
1617             =head2 Database Handle Attributes
1618              
1619             =over 4
1620              
1621             =item sqlite_version
1622              
1623             Returns the version of the SQLite library which B<DBD::SQLite> is using,
1624             e.g., "3.26.0". Can only be read.
1625              
1626             =item sqlite_string_mode
1627              
1628             SQLite strings are simple arrays of bytes, but Perl strings can store any
1629             arbitrary Unicode code point. Thus, DBD::SQLite has to adopt some method
1630             of translating between those two models. This parameter defines that
1631             translation.
1632              
1633             Accepted values are the following constants:
1634              
1635             =over
1636              
1637             =item * DBD_SQLITE_STRING_MODE_BYTES: All strings are assumed to
1638             represent bytes. A Perl string that contains any code point above 255
1639             will trigger an exception. This is appropriate for Latin-1 strings,
1640             binary data, pre-encoded UTF-8 strings, etc.
1641              
1642             =item * DBD_SQLITE_STRING_MODE_UNICODE_FALLBACK: All Perl strings are encoded
1643             to UTF-8 before being given to SQLite. Perl will B<try> to decode SQLite
1644             strings as UTF-8 when giving them to Perl. Should any such string not be
1645             valid UTF-8, a warning is thrown, and the string is left undecoded.
1646              
1647             This is appropriate for strings that are decoded to characters via,
1648             e.g., L<Encode/decode>.
1649              
1650             Also note that, due to some bizarreness in SQLite's type system (see
1651             L<https://www.sqlite.org/datatype3.html>), if you want to retain
1652             blob-style behavior for B<some> columns under DBD_SQLITE_STRING_MODE_UNICODE_FALLBACK
1653             (say, to store images in the database), you have to state so
1654             explicitly using the 3-argument form of L<DBI/bind_param> when doing
1655             updates:
1656              
1657             use DBI qw(:sql_types);
1658             use DBD::SQLite::Constants ':dbd_sqlite_string_mode';
1659             $dbh->{sqlite_string_mode} = DBD_SQLITE_STRING_MODE_UNICODE_FALLBACK;
1660             my $sth = $dbh->prepare("INSERT INTO mytable (blobcolumn) VALUES (?)");
1661              
1662             # Binary_data will be stored as is.
1663             $sth->bind_param(1, $binary_data, SQL_BLOB);
1664              
1665             Defining the column type as C<BLOB> in the DDL is B<not> sufficient.
1666              
1667             =item * DBD_SQLITE_STRING_MODE_UNICODE_STRICT: Like
1668             DBD_SQLITE_STRING_MODE_UNICODE_FALLBACK but usually throws an exception
1669             rather than a warning if SQLite sends invalid UTF-8. (In Perl callbacks
1670             from SQLite we still warn instead.)
1671              
1672             =item * DBD_SQLITE_STRING_MODE_UNICODE_NAIVE: Like
1673             DBD_SQLITE_STRING_MODE_UNICODE_FALLBACK but uses a "naïve" UTF-8 decoding
1674             method that forgoes validation. This is marginally faster than a validated
1675             decode, but it can also B<corrupt> B<Perl> B<itself!>
1676              
1677             =item * DBD_SQLITE_STRING_MODE_PV (default, but B<DO> B<NOT> B<USE>): Like
1678             DBD_SQLITE_STRING_MODE_BYTES, but when translating Perl strings to SQLite
1679             the Perl string's internal byte buffer is given to SQLite. B<This> B<is>
1680             B<bad>, but it's been the default for many years, and changing that would
1681             break existing applications.
1682              
1683             =back
1684              
1685             =item C<sqlite_unicode> or C<unicode> (deprecated)
1686              
1687             If truthy, equivalent to setting C<sqlite_string_mode> to
1688             DBD_SQLITE_STRING_MODE_UNICODE_NAIVE; if falsy, equivalent to
1689             DBD_SQLITE_STRING_MODE_PV.
1690              
1691             Prefer C<sqlite_string_mode> in all new code.
1692              
1693             =item sqlite_allow_multiple_statements
1694              
1695             If you set this to true, C<do> method will process multiple
1696             statements at one go. This may be handy, but with performance
1697             penalty. See above for details.
1698              
1699             =item sqlite_use_immediate_transaction
1700              
1701             If you set this to true, DBD::SQLite tries to issue a C<begin
1702             immediate transaction> (instead of C<begin transaction>) when
1703             necessary. See above for details.
1704              
1705             As of version 1.38_01, this attribute is set to true by default.
1706             If you really need to use C<deferred> transactions for some reasons,
1707             set this to false explicitly.
1708              
1709             =item sqlite_see_if_its_a_number
1710              
1711             If you set this to true, DBD::SQLite tries to see if the bind values
1712             are number or not, and does not quote if they are numbers. See above
1713             for details.
1714              
1715             =item sqlite_extended_result_codes
1716              
1717             If set to true, DBD::SQLite uses extended result codes where appropriate
1718             (see L<https://www.sqlite.org/rescode.html>).
1719              
1720             =item sqlite_defensive
1721              
1722             If set to true, language features that allow ordinary SQL to deliberately
1723             corrupt the database file are prohibited.
1724              
1725             =back
1726              
1727             =head2 Statement Handle Attributes
1728              
1729             =over 4
1730              
1731             =item sqlite_unprepared_statements
1732              
1733             Returns an unprepared part of the statement you pass to C<prepare>.
1734             Typically this contains nothing but white spaces after a semicolon.
1735             See above for details.
1736              
1737             =back
1738              
1739             =head1 METHODS
1740              
1741             See also to the L<DBI> documentation for the details of other common
1742             methods.
1743              
1744             =head2 table_info
1745              
1746             $sth = $dbh->table_info(undef, $schema, $table, $type, \%attr);
1747              
1748             Returns all tables and schemas (databases) as specified in L<DBI/table_info>.
1749             The schema and table arguments will do a C<LIKE> search. You can specify an
1750             ESCAPE character by including an 'Escape' attribute in \%attr. The C<$type>
1751             argument accepts a comma separated list of the following types 'TABLE',
1752             'INDEX', 'VIEW', 'TRIGGER', 'LOCAL TEMPORARY' and 'SYSTEM TABLE'
1753             (by default all are returned).
1754             Note that a statement handle is returned, and not a direct list of tables.
1755              
1756             The following fields are returned:
1757              
1758             B<TABLE_CAT>: Always NULL, as SQLite does not have the concept of catalogs.
1759              
1760             B<TABLE_SCHEM>: The name of the schema (database) that the table or view is
1761             in. The default schema is 'main', temporary tables are in 'temp' and other
1762             databases will be in the name given when the database was attached.
1763              
1764             B<TABLE_NAME>: The name of the table or view.
1765              
1766             B<TABLE_TYPE>: The type of object returned. Will be one of 'TABLE', 'INDEX',
1767             'VIEW', 'TRIGGER', 'LOCAL TEMPORARY' or 'SYSTEM TABLE'.
1768              
1769             =head2 primary_key, primary_key_info
1770              
1771             @names = $dbh->primary_key(undef, $schema, $table);
1772             $sth = $dbh->primary_key_info(undef, $schema, $table, \%attr);
1773              
1774             You can retrieve primary key names or more detailed information.
1775             As noted above, SQLite does not have the concept of catalogs, so the
1776             first argument of the methods is usually C<undef>, and you'll usually
1777             set C<undef> for the second one (unless you want to know the primary
1778             keys of temporary tables).
1779              
1780              
1781             =head2 foreign_key_info
1782              
1783             $sth = $dbh->foreign_key_info(undef, $pk_schema, $pk_table,
1784             undef, $fk_schema, $fk_table);
1785              
1786             Returns information about foreign key constraints, as specified in
1787             L<DBI/foreign_key_info>, but with some limitations :
1788              
1789             =over
1790              
1791             =item *
1792              
1793             information in rows returned by the C<$sth> is incomplete with
1794             respect to the L<DBI/foreign_key_info> specification. All requested fields
1795             are present, but the content is C<undef> for some of them.
1796              
1797             =back
1798              
1799             The following nonempty fields are returned :
1800              
1801             B<PKTABLE_NAME>:
1802             The primary (unique) key table identifier.
1803              
1804             B<PKCOLUMN_NAME>:
1805             The primary (unique) key column identifier.
1806              
1807             B<FKTABLE_NAME>:
1808             The foreign key table identifier.
1809              
1810             B<FKCOLUMN_NAME>:
1811             The foreign key column identifier.
1812              
1813             B<KEY_SEQ>:
1814             The column sequence number (starting with 1), when
1815             several columns belong to a same constraint.
1816              
1817             B<UPDATE_RULE>:
1818             The referential action for the UPDATE rule.
1819             The following codes are defined:
1820              
1821             CASCADE 0
1822             RESTRICT 1
1823             SET NULL 2
1824             NO ACTION 3
1825             SET DEFAULT 4
1826              
1827             Default is 3 ('NO ACTION').
1828              
1829             B<DELETE_RULE>:
1830             The referential action for the DELETE rule.
1831             The codes are the same as for UPDATE_RULE.
1832              
1833             B<DEFERRABILITY>:
1834             The following codes are defined:
1835              
1836             INITIALLY DEFERRED 5
1837             INITIALLY IMMEDIATE 6
1838             NOT DEFERRABLE 7
1839              
1840             B<UNIQUE_OR_PRIMARY>:
1841             Whether the column is primary or unique.
1842              
1843             B<Note>: foreign key support in SQLite must be explicitly turned on through
1844             a C<PRAGMA> command; see L</"Foreign keys"> earlier in this manual.
1845              
1846             =head2 statistics_info
1847              
1848             $sth = $dbh->statistics_info(undef, $schema, $table,
1849             $unique_only, $quick);
1850              
1851             Returns information about a table and it's indexes, as specified in
1852             L<DBI/statistics_info>, but with some limitations :
1853              
1854             =over
1855              
1856             =item *
1857              
1858             information in rows returned by the C<$sth> is incomplete with
1859             respect to the L<DBI/statistics_info> specification. All requested fields
1860             are present, but the content is C<undef> for some of them.
1861              
1862             =back
1863              
1864             The following nonempty fields are returned :
1865              
1866             B<TABLE_SCHEM>:
1867             The name of the schema (database) that the table is in. The default schema is 'main', temporary tables are in 'temp' and other databases will be in the name given when the database was attached.
1868              
1869             B<TABLE_NAME>:
1870             The name of the table
1871              
1872             B<NON_UNIQUE>:
1873             Contains 0 for unique indexes, 1 for non-unique indexes
1874              
1875             B<INDEX_NAME>:
1876             The name of the index
1877              
1878             B<TYPE>:
1879             SQLite uses 'btree' for all it's indexes
1880              
1881             B<ORDINAL_POSITION>:
1882             Column sequence number (starting with 1).
1883              
1884             B<COLUMN_NAME>:
1885             The name of the column
1886              
1887             =head2 ping
1888              
1889             my $bool = $dbh->ping;
1890              
1891             returns true if the database file exists (or the database is in-memory), and the database connection is active.
1892              
1893             =head1 DRIVER PRIVATE METHODS
1894              
1895             The following methods can be called via the func() method with a little
1896             tweak, but the use of func() method is now discouraged by the L<DBI> author
1897             for various reasons (see DBI's document
1898             L<https://metacpan.org/pod/DBI::DBD#Using-install_method()-to-expose-driver-private-methods>
1899             for details). So, if you're using L<DBI> >= 1.608, use these C<sqlite_>
1900             methods. If you need to use an older L<DBI>, you can call these like this:
1901              
1902             $dbh->func( ..., "(method name without sqlite_ prefix)" );
1903              
1904             Exception: C<sqlite_trace> should always be called as is, even with C<func()>
1905             method (to avoid conflict with DBI's trace() method).
1906              
1907             $dbh->func( ..., "sqlite_trace");
1908              
1909             =head2 $dbh->sqlite_last_insert_rowid()
1910              
1911             This method returns the last inserted rowid. If you specify an INTEGER PRIMARY
1912             KEY as the first column in your table, that is the column that is returned.
1913             Otherwise, it is the hidden ROWID column. See the SQLite docs for details.
1914              
1915             Generally you should not be using this method. Use the L<DBI> last_insert_id
1916             method instead. The usage of this is:
1917              
1918             $h->last_insert_id($catalog, $schema, $table_name, $field_name [, \%attr ])
1919              
1920             Running C<$h-E<gt>last_insert_id("","","","")> is the equivalent of running
1921             C<$dbh-E<gt>sqlite_last_insert_rowid()> directly.
1922              
1923             =head2 $dbh->sqlite_db_filename()
1924              
1925             Retrieve the current (main) database filename. If the database is in-memory
1926             or temporary, this returns an empty string, or C<undef>.
1927              
1928             =head2 $dbh->sqlite_busy_timeout()
1929              
1930             Retrieve the current busy timeout.
1931              
1932             =head2 $dbh->sqlite_busy_timeout( $ms )
1933              
1934             Set the current busy timeout. The timeout is in milliseconds.
1935              
1936             =head2 $dbh->sqlite_create_function( $name, $argc, $code_ref, $flags )
1937              
1938             This method will register a new function which will be usable in an SQL
1939             query. The method's parameters are:
1940              
1941             =over
1942              
1943             =item $name
1944              
1945             The name of the function. This is the name of the function as it will
1946             be used from SQL.
1947              
1948             =item $argc
1949              
1950             The number of arguments taken by the function. If this number is -1,
1951             the function can take any number of arguments.
1952              
1953             =item $code_ref
1954              
1955             This should be a reference to the function's implementation.
1956              
1957             =item $flags
1958              
1959             You can optionally pass an extra flag bit to create_function, which then would be ORed with SQLITE_UTF8 (default). As of 1.47_02 (SQLite 3.8.9), only meaning bit is SQLITE_DETERMINISTIC (introduced at SQLite 3.8.3), which can make the function perform better. See C API documentation at L<http://sqlite.org/c3ref/create_function.html> for details.
1960              
1961             =back
1962              
1963             For example, here is how to define a now() function which returns the
1964             current number of seconds since the epoch:
1965              
1966             $dbh->sqlite_create_function( 'now', 0, sub { return time } );
1967              
1968             After this, it could be used from SQL as:
1969              
1970             INSERT INTO mytable ( now() );
1971              
1972             The function should return a scalar value, and the value is treated as a text
1973             (or a number if appropriate) by default. If you do need to specify a type
1974             of the return value (like BLOB), you can return a reference to an array that
1975             contains the value and the type, as of 1.65_01.
1976              
1977             $dbh->sqlite_create_function( 'md5', 1, sub { return [md5($_[0]), SQL_BLOB] } );
1978              
1979             =head3 REGEXP function
1980              
1981             SQLite includes syntactic support for an infix operator 'REGEXP', but
1982             without any implementation. The C<DBD::SQLite> driver
1983             automatically registers an implementation that performs standard
1984             perl regular expression matching, using current locale. So for example
1985             you can search for words starting with an 'A' with a query like
1986              
1987             SELECT * from table WHERE column REGEXP '\bA\w+'
1988              
1989             If you want case-insensitive searching, use perl regex flags, like this :
1990              
1991             SELECT * from table WHERE column REGEXP '(?i:\bA\w+)'
1992              
1993             The default REGEXP implementation can be overridden through the
1994             C<create_function> API described above.
1995              
1996             Note that regexp matching will B<not> use SQLite indices, but will iterate
1997             over all rows, so it could be quite costly in terms of performance.
1998              
1999             =head2 $dbh->sqlite_create_collation( $name, $code_ref )
2000              
2001             This method manually registers a new function which will be usable in an SQL
2002             query as a COLLATE option for sorting. Such functions can also be registered
2003             automatically on demand: see section L</"COLLATION FUNCTIONS"> below.
2004              
2005             The method's parameters are:
2006              
2007             =over
2008              
2009             =item $name
2010              
2011             The name of the function exposed to SQL.
2012              
2013             =item $code_ref
2014              
2015             Reference to the function's implementation.
2016             The driver will check that this is a proper sorting function.
2017              
2018             =back
2019              
2020             =head2 $dbh->sqlite_collation_needed( $code_ref )
2021              
2022             This method manually registers a callback function that will
2023             be invoked whenever an undefined collation sequence is required
2024             from an SQL statement. The callback is invoked as
2025              
2026             $code_ref->($dbh, $collation_name)
2027              
2028             and should register the desired collation using
2029             L</"sqlite_create_collation">.
2030              
2031             An initial callback is already registered by C<DBD::SQLite>,
2032             so for most common cases it will be simpler to just
2033             add your collation sequences in the C<%DBD::SQLite::COLLATION>
2034             hash (see section L</"COLLATION FUNCTIONS"> below).
2035              
2036             =head2 $dbh->sqlite_create_aggregate( $name, $argc, $pkg, $flags )
2037              
2038             This method will register a new aggregate function which can then be used
2039             from SQL. The method's parameters are:
2040              
2041             =over
2042              
2043             =item $name
2044              
2045             The name of the aggregate function, this is the name under which the
2046             function will be available from SQL.
2047              
2048             =item $argc
2049              
2050             This is an integer which tells the SQL parser how many arguments the
2051             function takes. If that number is -1, the function can take any number
2052             of arguments.
2053              
2054             =item $pkg
2055              
2056             This is the package which implements the aggregator interface.
2057              
2058             =item $flags
2059              
2060             You can optionally pass an extra flag bit to create_aggregate, which then would be ORed with SQLITE_UTF8 (default). As of 1.47_02 (SQLite 3.8.9), only meaning bit is SQLITE_DETERMINISTIC (introduced at SQLite 3.8.3), which can make the function perform better. See C API documentation at L<http://sqlite.org/c3ref/create_function.html> for details.
2061              
2062             =back
2063              
2064             The aggregator interface consists of defining three methods:
2065              
2066             =over
2067              
2068             =item new()
2069              
2070             This method will be called once to create an object which should
2071             be used to aggregate the rows in a particular group. The step() and
2072             finalize() methods will be called upon the reference return by
2073             the method.
2074              
2075             =item step(@_)
2076              
2077             This method will be called once for each row in the aggregate.
2078              
2079             =item finalize()
2080              
2081             This method will be called once all rows in the aggregate were
2082             processed and it should return the aggregate function's result. When
2083             there is no rows in the aggregate, finalize() will be called right
2084             after new().
2085              
2086             =back
2087              
2088             Here is a simple aggregate function which returns the variance
2089             (example adapted from pysqlite):
2090              
2091             package variance;
2092            
2093             sub new { bless [], shift; }
2094            
2095             sub step {
2096             my ( $self, $value ) = @_;
2097            
2098             push @$self, $value;
2099             }
2100            
2101             sub finalize {
2102             my $self = $_[0];
2103            
2104             my $n = @$self;
2105            
2106             # Variance is NULL unless there is more than one row
2107             return undef unless $n || $n == 1;
2108            
2109             my $mu = 0;
2110             foreach my $v ( @$self ) {
2111             $mu += $v;
2112             }
2113             $mu /= $n;
2114            
2115             my $sigma = 0;
2116             foreach my $v ( @$self ) {
2117             $sigma += ($v - $mu)**2;
2118             }
2119             $sigma = $sigma / ($n - 1);
2120            
2121             return $sigma;
2122             }
2123            
2124             $dbh->sqlite_create_aggregate( "variance", 1, 'variance' );
2125              
2126             The aggregate function can then be used as:
2127              
2128             SELECT group_name, variance(score)
2129             FROM results
2130             GROUP BY group_name;
2131              
2132             For more examples, see the L<DBD::SQLite::Cookbook>.
2133              
2134             =head2 $dbh->sqlite_progress_handler( $n_opcodes, $code_ref )
2135              
2136             This method registers a handler to be invoked periodically during long
2137             running calls to SQLite.
2138              
2139             An example use for this interface is to keep a GUI updated during a
2140             large query. The parameters are:
2141              
2142             =over
2143              
2144             =item $n_opcodes
2145              
2146             The progress handler is invoked once for every C<$n_opcodes>
2147             virtual machine opcodes in SQLite.
2148              
2149             =item $code_ref
2150              
2151             Reference to the handler subroutine. If the progress handler returns
2152             non-zero, the SQLite operation is interrupted. This feature can be used to
2153             implement a "Cancel" button on a GUI dialog box.
2154              
2155             Set this argument to C<undef> if you want to unregister a previous
2156             progress handler.
2157              
2158             =back
2159              
2160             =head2 $dbh->sqlite_commit_hook( $code_ref )
2161              
2162             This method registers a callback function to be invoked whenever a
2163             transaction is committed. Any callback set by a previous call to
2164             C<sqlite_commit_hook> is overridden. A reference to the previous
2165             callback (if any) is returned. Registering an C<undef> disables the
2166             callback.
2167              
2168             When the commit hook callback returns zero, the commit operation is
2169             allowed to continue normally. If the callback returns non-zero, then
2170             the commit is converted into a rollback (in that case, any attempt to
2171             I<explicitly> call C<< $dbh->rollback() >> afterwards would yield an
2172             error).
2173              
2174             =head2 $dbh->sqlite_rollback_hook( $code_ref )
2175              
2176             This method registers a callback function to be invoked whenever a
2177             transaction is rolled back. Any callback set by a previous call to
2178             C<sqlite_rollback_hook> is overridden. A reference to the previous
2179             callback (if any) is returned. Registering an C<undef> disables the
2180             callback.
2181              
2182             =head2 $dbh->sqlite_update_hook( $code_ref )
2183              
2184             This method registers a callback function to be invoked whenever a row
2185             is updated, inserted or deleted. Any callback set by a previous call to
2186             C<sqlite_update_hook> is overridden. A reference to the previous
2187             callback (if any) is returned. Registering an C<undef> disables the
2188             callback.
2189              
2190             The callback will be called as
2191              
2192             $code_ref->($action_code, $database, $table, $rowid)
2193              
2194             where
2195              
2196             =over
2197              
2198             =item $action_code
2199              
2200             is an integer equal to either C<DBD::SQLite::INSERT>,
2201             C<DBD::SQLite::DELETE> or C<DBD::SQLite::UPDATE>
2202             (see L</"Action Codes">);
2203              
2204             =item $database
2205              
2206             is the name of the database containing the affected row;
2207              
2208             =item $table
2209              
2210             is the name of the table containing the affected row;
2211              
2212             =item $rowid
2213              
2214             is the unique 64-bit signed integer key of the affected row within
2215             that table.
2216              
2217             =back
2218              
2219             =head2 $dbh->sqlite_set_authorizer( $code_ref )
2220              
2221             This method registers an authorizer callback to be invoked whenever
2222             SQL statements are being compiled by the L<DBI/prepare> method. The
2223             authorizer callback should return C<DBD::SQLite::OK> to allow the
2224             action, C<DBD::SQLite::IGNORE> to disallow the specific action but
2225             allow the SQL statement to continue to be compiled, or
2226             C<DBD::SQLite::DENY> to cause the entire SQL statement to be rejected
2227             with an error. If the authorizer callback returns any other value,
2228             then C<prepare> call that triggered the authorizer will fail with
2229             an error message.
2230              
2231             An authorizer is used when preparing SQL statements from an untrusted
2232             source, to ensure that the SQL statements do not try to access data
2233             they are not allowed to see, or that they do not try to execute
2234             malicious statements that damage the database. For example, an
2235             application may allow a user to enter arbitrary SQL queries for
2236             evaluation by a database. But the application does not want the user
2237             to be able to make arbitrary changes to the database. An authorizer
2238             could then be put in place while the user-entered SQL is being
2239             prepared that disallows everything except SELECT statements.
2240              
2241             The callback will be called as
2242              
2243             $code_ref->($action_code, $string1, $string2, $database, $trigger_or_view)
2244              
2245             where
2246              
2247             =over
2248              
2249             =item $action_code
2250              
2251             is an integer that specifies what action is being authorized
2252             (see L</"Action Codes">).
2253              
2254             =item $string1, $string2
2255              
2256             are strings that depend on the action code
2257             (see L</"Action Codes">).
2258              
2259             =item $database
2260              
2261             is the name of the database (C<main>, C<temp>, etc.) if applicable.
2262              
2263             =item $trigger_or_view
2264              
2265             is the name of the inner-most trigger or view that is responsible for
2266             the access attempt, or C<undef> if this access attempt is directly from
2267             top-level SQL code.
2268              
2269             =back
2270              
2271             =head2 $dbh->sqlite_backup_from_file( $filename )
2272              
2273             This method accesses the SQLite Online Backup API, and will take a backup of
2274             the named database file, copying it to, and overwriting, your current database
2275             connection. This can be particularly handy if your current connection is to the
2276             special :memory: database, and you wish to populate it from an existing DB.
2277              
2278             =head2 $dbh->sqlite_backup_to_file( $filename )
2279              
2280             This method accesses the SQLite Online Backup API, and will take a backup of
2281             the currently connected database, and write it out to the named file.
2282              
2283             =head2 $dbh->sqlite_backup_from_dbh( $another_dbh )
2284              
2285             This method accesses the SQLite Online Backup API, and will take a backup of
2286             the database for the passed handle, copying it to, and overwriting, your current database
2287             connection. This can be particularly handy if your current connection is to the
2288             special :memory: database, and you wish to populate it from an existing DB.
2289             You can use this to backup from an in-memory database to another in-memory database.
2290              
2291             =head2 $dbh->sqlite_backup_to_dbh( $another_dbh )
2292              
2293             This method accesses the SQLite Online Backup API, and will take a backup of
2294             the currently connected database, and write it out to the passed database handle.
2295              
2296             =head2 $dbh->sqlite_enable_load_extension( $bool )
2297              
2298             Calling this method with a true value enables loading (external)
2299             SQLite3 extensions. After the call, you can load extensions like this:
2300              
2301             $dbh->sqlite_enable_load_extension(1);
2302             $sth = $dbh->prepare("select load_extension('libmemvfs.so')")
2303             or die "Cannot prepare: " . $dbh->errstr();
2304              
2305             =head2 $dbh->sqlite_load_extension( $file, $proc )
2306              
2307             Loading an extension by a select statement (with the "load_extension" SQLite3 function like above) has some limitations. If the extension you want to use creates other functions that are not native to SQLite, use this method instead. $file (a path to the extension) is mandatory, and $proc (an entry point name) is optional. You need to call C<sqlite_enable_load_extension> before calling C<sqlite_load_extension>:
2308              
2309             $dbh->sqlite_enable_load_extension(1);
2310             $dbh->sqlite_load_extension('libsqlitefunctions.so')
2311             or die "Cannot load extension: " . $dbh->errstr();
2312              
2313             If the extension uses SQLite mutex functions like C<sqlite3_mutex_enter>, then
2314             the extension should be compiled with the same C<SQLITE_THREADSAFE> compile-time
2315             setting as this module, see C<DBD::SQLite::compile_options()>.
2316              
2317             =head2 $dbh->sqlite_trace( $code_ref )
2318              
2319             This method registers a trace callback to be invoked whenever
2320             SQL statements are being run.
2321              
2322             The callback will be called as
2323              
2324             $code_ref->($statement)
2325              
2326             where
2327              
2328             =over
2329              
2330             =item $statement
2331              
2332             is a UTF-8 rendering of the SQL statement text as the statement
2333             first begins executing.
2334              
2335             =back
2336              
2337             Additional callbacks might occur as each triggered subprogram is
2338             entered. The callbacks for triggers contain a UTF-8 SQL comment
2339             that identifies the trigger.
2340              
2341             See also L<DBI/TRACING> for better tracing options.
2342              
2343             =head2 $dbh->sqlite_profile( $code_ref )
2344              
2345             This method registers a profile callback to be invoked whenever
2346             a SQL statement finishes.
2347              
2348             The callback will be called as
2349              
2350             $code_ref->($statement, $elapsed_time)
2351              
2352             where
2353              
2354             =over
2355              
2356             =item $statement
2357              
2358             is the original statement text (without bind parameters).
2359              
2360             =item $elapsed_time
2361              
2362             is an estimate of wall-clock time of how long that statement took to run (in milliseconds).
2363              
2364             =back
2365              
2366             This method is considered experimental and is subject to change in future versions of SQLite.
2367              
2368             See also L<DBI::Profile> for better profiling options.
2369              
2370             =head2 $dbh->sqlite_table_column_metadata( $dbname, $tablename, $columnname )
2371              
2372             is for internal use only.
2373              
2374             =head2 $dbh->sqlite_db_status()
2375              
2376             Returns a hash reference that holds a set of status information of database connection such as cache usage. See L<https://www.sqlite.org/c3ref/c_dbstatus_options.html> for details. You may also pass 0 as an argument to reset the status.
2377              
2378             =head2 $sth->sqlite_st_status()
2379              
2380             Returns a hash reference that holds a set of status information of SQLite statement handle such as full table scan count. See L<https://www.sqlite.org/c3ref/c_stmtstatus_counter.html> for details. Statement status only holds the current value.
2381              
2382             my $status = $sth->sqlite_st_status();
2383             my $cur = $status->{fullscan_step};
2384              
2385             You may also pass 0 as an argument to reset the status.
2386              
2387             =head2 $dbh->sqlite_db_config( $id, $new_integer_value )
2388              
2389             You can change how the connected database should behave like this:
2390              
2391             use DBD::SQLite::Constants qw/:database_connection_configuration_options/;
2392            
2393             my $dbh = DBI->connect('dbi:SQLite::memory:');
2394              
2395             # This disables language features that allow ordinary SQL
2396             # to deliberately corrupt the database file
2397             $dbh->sqlite_db_config( SQLITE_DBCONFIG_DEFENSIVE, 1 );
2398            
2399             # This disables two-arg version of fts3_tokenizer.
2400             $dbh->sqlite_db_config( SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER, 0 );
2401              
2402             C<sqlite_db_config> returns the new value after the call. If you just want to know the current value without changing anything, pass a negative integer value.
2403              
2404             my $current_value = $dbh->sqlite_db_config( SQLITE_DBCONFIG_DEFENSIVE, -1 );
2405              
2406             As of this writing, C<sqlite_db_config> only supports options that set an integer value. C<SQLITE_DBCONFIG_LOOKASIDE> and C<SQLITE_DBCONFIG_MAINDBNAME> are not supported. See also C<https://www.sqlite.org/capi3ref.html#sqlite3_db_config> for details.
2407              
2408             =head2 $dbh->sqlite_create_module()
2409              
2410             Registers a name for a I<virtual table module>. Module names must be
2411             registered before creating a new virtual table using the module and
2412             before using a preexisting virtual table for the module.
2413             Virtual tables are explained in L<DBD::SQLite::VirtualTable>.
2414              
2415             =head2 $dbh->sqlite_limit( $category_id, $new_value )
2416              
2417             Sets a new run-time limit for the category, and returns the current limit.
2418             If the new value is a negative number (or omitted), the limit is unchanged
2419             and just returns the current limit. Category ids (SQLITE_LIMIT_LENGTH,
2420             SQLITE_LIMIT_VARIABLE_NUMBER, etc) can be imported from DBD::SQLite::Constants.
2421              
2422             =head2 $dbh->sqlite_get_autocommit()
2423              
2424             Returns true if the internal SQLite connection is in an autocommit mode.
2425             This does not always return the same value as C<< $dbh->{AutoCommit} >>.
2426             This returns false if you explicitly issue a C<<BEGIN>> statement.
2427              
2428             =head2 $dbh->sqlite_txn_state()
2429              
2430             Returns the internal transaction status of SQLite (not of DBI).
2431             Return values (SQLITE_TXN_NONE, SQLITE_TXN_READ, SQLITE_TXN_WRITE)
2432             can be imported from DBD::SQLite::Constants. You may pass an optional
2433             schema name (usually "main"). If SQLite does not support this function,
2434             or if you pass a wrong schema name, -1 is returned.
2435              
2436             =head2 $dbh->sqlite_error_offset()
2437              
2438             Returns the byte offset of the start of a problematic input SQL token
2439             or -1 if the most recent error does not reference a specific token in
2440             the input SQL (or DBD::SQLite is built with an older version of SQLite).
2441              
2442             =head1 DRIVER FUNCTIONS
2443              
2444             =head2 DBD::SQLite::compile_options()
2445              
2446             Returns an array of compile options (available since SQLite 3.6.23,
2447             bundled in DBD::SQLite 1.30_01), or an empty array if the bundled
2448             library is old or compiled with SQLITE_OMIT_COMPILEOPTION_DIAGS.
2449              
2450             =head2 DBD::SQLite::sqlite_status()
2451              
2452             Returns a hash reference that holds a set of status information of SQLite runtime such as memory usage or page cache usage (see L<https://www.sqlite.org/c3ref/c_status_malloc_count.html> for details). Each of the entry contains the current value and the highwater value.
2453              
2454             my $status = DBD::SQLite::sqlite_status();
2455             my $cur = $status->{memory_used}{current};
2456             my $high = $status->{memory_used}{highwater};
2457              
2458             You may also pass 0 as an argument to reset the status.
2459              
2460             =head2 DBD::SQLite::strlike($pattern, $string, $escape_char), DBD::SQLite::strglob($pattern, $string)
2461              
2462             As of 1.49_05 (SQLite 3.10.0), you can use these two functions to
2463             see if a string matches a pattern. These may be useful when you
2464             create a virtual table or a custom function.
2465             See L<http://sqlite.org/c3ref/strlike.html> and
2466             L<http://sqlite.org/c3ref/strglob.html> for details.
2467              
2468             =head1 DRIVER CONSTANTS
2469              
2470             A subset of SQLite C constants are made available to Perl,
2471             because they may be needed when writing
2472             hooks or authorizer callbacks. For accessing such constants,
2473             the C<DBD::SQLite> module must be explicitly C<use>d at compile
2474             time. For example, an authorizer that forbids any
2475             DELETE operation would be written as follows :
2476              
2477             use DBD::SQLite;
2478             $dbh->sqlite_set_authorizer(sub {
2479             my $action_code = shift;
2480             return $action_code == DBD::SQLite::DELETE ? DBD::SQLite::DENY
2481             : DBD::SQLite::OK;
2482             });
2483              
2484             The list of constants implemented in C<DBD::SQLite> is given
2485             below; more information can be found ad
2486             at L<https://www.sqlite.org/c3ref/constlist.html>.
2487              
2488             =head2 Authorizer Return Codes
2489              
2490             OK
2491             DENY
2492             IGNORE
2493              
2494             =head2 Action Codes
2495              
2496             The L</set_authorizer> method registers a callback function that is
2497             invoked to authorize certain SQL statement actions. The first
2498             parameter to the callback is an integer code that specifies what
2499             action is being authorized. The second and third parameters to the
2500             callback are strings, the meaning of which varies according to the
2501             action code. Below is the list of action codes, together with their
2502             associated strings.
2503              
2504             # constant string1 string2
2505             # ======== ======= =======
2506             CREATE_INDEX Index Name Table Name
2507             CREATE_TABLE Table Name undef
2508             CREATE_TEMP_INDEX Index Name Table Name
2509             CREATE_TEMP_TABLE Table Name undef
2510             CREATE_TEMP_TRIGGER Trigger Name Table Name
2511             CREATE_TEMP_VIEW View Name undef
2512             CREATE_TRIGGER Trigger Name Table Name
2513             CREATE_VIEW View Name undef
2514             DELETE Table Name undef
2515             DROP_INDEX Index Name Table Name
2516             DROP_TABLE Table Name undef
2517             DROP_TEMP_INDEX Index Name Table Name
2518             DROP_TEMP_TABLE Table Name undef
2519             DROP_TEMP_TRIGGER Trigger Name Table Name
2520             DROP_TEMP_VIEW View Name undef
2521             DROP_TRIGGER Trigger Name Table Name
2522             DROP_VIEW View Name undef
2523             INSERT Table Name undef
2524             PRAGMA Pragma Name 1st arg or undef
2525             READ Table Name Column Name
2526             SELECT undef undef
2527             TRANSACTION Operation undef
2528             UPDATE Table Name Column Name
2529             ATTACH Filename undef
2530             DETACH Database Name undef
2531             ALTER_TABLE Database Name Table Name
2532             REINDEX Index Name undef
2533             ANALYZE Table Name undef
2534             CREATE_VTABLE Table Name Module Name
2535             DROP_VTABLE Table Name Module Name
2536             FUNCTION undef Function Name
2537             SAVEPOINT Operation Savepoint Name
2538              
2539             =head1 COLLATION FUNCTIONS
2540              
2541             =head2 Definition
2542              
2543             SQLite v3 provides the ability for users to supply arbitrary
2544             comparison functions, known as user-defined "collation sequences" or
2545             "collating functions", to be used for comparing two text values.
2546             L<https://www.sqlite.org/datatype3.html#collation>
2547             explains how collations are used in various SQL expressions.
2548              
2549             =head2 Builtin collation sequences
2550              
2551             The following collation sequences are builtin within SQLite :
2552              
2553             =over
2554              
2555             =item B<BINARY>
2556              
2557             Compares string data using memcmp(), regardless of text encoding.
2558              
2559             =item B<NOCASE>
2560              
2561             The same as binary, except the 26 upper case characters of ASCII are
2562             folded to their lower case equivalents before the comparison is
2563             performed. Note that only ASCII characters are case folded. SQLite
2564             does not attempt to do full UTF case folding due to the size of the
2565             tables required.
2566              
2567             =item B<RTRIM>
2568              
2569             The same as binary, except that trailing space characters are ignored.
2570              
2571             =back
2572              
2573             In addition, C<DBD::SQLite> automatically installs the
2574             following collation sequences :
2575              
2576             =over
2577              
2578             =item B<perl>
2579              
2580             corresponds to the Perl C<cmp> operator
2581              
2582             =item B<perllocale>
2583              
2584             Perl C<cmp> operator, in a context where C<use locale> is activated.
2585              
2586             =back
2587              
2588             =head2 Usage
2589              
2590             You can write for example
2591              
2592             CREATE TABLE foo(
2593             txt1 COLLATE perl,
2594             txt2 COLLATE perllocale,
2595             txt3 COLLATE nocase
2596             )
2597              
2598             or
2599              
2600             SELECT * FROM foo ORDER BY name COLLATE perllocale
2601              
2602             =head2 Unicode handling
2603              
2604             Depending on the C<< $dbh->{sqlite_string_mode} >> value, strings coming
2605             from the database and passed to the collation function may be decoded as
2606             UTF-8. This only works, though, if the C<sqlite_string_mode> attribute is
2607             set B<before> the first call to a perl collation sequence. The recommended
2608             way to activate unicode is to set C<sqlite_string_mode> at connection time:
2609              
2610             my $dbh = DBI->connect(
2611             "dbi:SQLite:dbname=foo", "", "",
2612             {
2613             RaiseError => 1,
2614             sqlite_string_mode => DBD_SQLITE_STRING_MODE_UNICODE_STRICT,
2615             }
2616             );
2617              
2618             =head2 Adding user-defined collations
2619              
2620             The native SQLite API for adding user-defined collations is
2621             exposed through methods L</"sqlite_create_collation"> and
2622             L</"sqlite_collation_needed">.
2623              
2624             To avoid calling these functions every time a C<$dbh> handle is
2625             created, C<DBD::SQLite> offers a simpler interface through the
2626             C<%DBD::SQLite::COLLATION> hash : just insert your own
2627             collation functions in that hash, and whenever an unknown
2628             collation name is encountered in SQL, the appropriate collation
2629             function will be loaded on demand from the hash. For example,
2630             here is a way to sort text values regardless of their accented
2631             characters :
2632              
2633             use DBD::SQLite;
2634             $DBD::SQLite::COLLATION{no_accents} = sub {
2635             my ( $a, $b ) = map lc, @_;
2636             tr[àâáäåãçðèêéëìîíïñòôóöõøùûúüý]
2637             [aaaaaacdeeeeiiiinoooooouuuuy] for $a, $b;
2638             $a cmp $b;
2639             };
2640             my $dbh = DBI->connect("dbi:SQLite:dbname=dbfile");
2641             my $sql = "SELECT ... FROM ... ORDER BY ... COLLATE no_accents");
2642             my $rows = $dbh->selectall_arrayref($sql);
2643              
2644             The builtin C<perl> or C<perllocale> collations are predefined
2645             in that same hash.
2646              
2647             The COLLATION hash is a global registry within the current process;
2648             hence there is a risk of undesired side-effects. Therefore, to
2649             prevent action at distance, the hash is implemented as a "write-only"
2650             hash, that will happily accept new entries, but will raise an
2651             exception if any attempt is made to override or delete a existing
2652             entry (including the builtin C<perl> and C<perllocale>).
2653              
2654             If you really, really need to change or delete an entry, you can
2655             always grab the tied object underneath C<%DBD::SQLite::COLLATION> ---
2656             but don't do that unless you really know what you are doing. Also
2657             observe that changes in the global hash will not modify existing
2658             collations in existing database handles: it will only affect new
2659             I<requests> for collations. In other words, if you want to change
2660             the behaviour of a collation within an existing C<$dbh>, you
2661             need to call the L</create_collation> method directly.
2662              
2663             =head1 FULLTEXT SEARCH
2664              
2665             SQLite is bundled with an extension module for full-text
2666             indexing. Tables with this feature enabled can be efficiently queried
2667             to find rows that contain one or more instances of some specified
2668             words, in any column, even if the table contains many large documents.
2669              
2670             Explanations for using this feature are provided in a separate document:
2671             see L<DBD::SQLite::Fulltext_search>.
2672              
2673              
2674             =head1 R* TREE SUPPORT
2675              
2676             The RTREE extension module within SQLite adds support for creating
2677             a R-Tree, a special index for range and multidimensional queries. This
2678             allows users to create tables that can be loaded with (as an example)
2679             geospatial data such as latitude/longitude coordinates for buildings within
2680             a city :
2681              
2682             CREATE VIRTUAL TABLE city_buildings USING rtree(
2683             id, -- Integer primary key
2684             minLong, maxLong, -- Minimum and maximum longitude
2685             minLat, maxLat -- Minimum and maximum latitude
2686             );
2687              
2688             then query which buildings overlap or are contained within a specified region:
2689              
2690             # IDs that are contained within query coordinates
2691             my $contained_sql = <<"";
2692             SELECT id FROM city_buildings
2693             WHERE minLong >= ? AND maxLong <= ?
2694             AND minLat >= ? AND maxLat <= ?
2695            
2696             # ... and those that overlap query coordinates
2697             my $overlap_sql = <<"";
2698             SELECT id FROM city_buildings
2699             WHERE maxLong >= ? AND minLong <= ?
2700             AND maxLat >= ? AND minLat <= ?
2701            
2702             my $contained = $dbh->selectcol_arrayref($contained_sql,undef,
2703             $minLong, $maxLong, $minLat, $maxLat);
2704            
2705             my $overlapping = $dbh->selectcol_arrayref($overlap_sql,undef,
2706             $minLong, $maxLong, $minLat, $maxLat);
2707              
2708             For more detail, please see the SQLite R-Tree page
2709             (L<https://www.sqlite.org/rtree.html>). Note that custom R-Tree
2710             queries using callbacks, as mentioned in the prior link, have not been
2711             implemented yet.
2712              
2713             =head1 VIRTUAL TABLES IMPLEMENTED IN PERL
2714              
2715             SQLite has a concept of "virtual tables" which look like regular
2716             tables but are implemented internally through specific functions.
2717             The fulltext or R* tree features described in the previous chapters
2718             are examples of such virtual tables, implemented in C code.
2719              
2720             C<DBD::SQLite> also supports virtual tables implemented in I<Perl code>:
2721             see L<DBD::SQLite::VirtualTable> for using or implementing such
2722             virtual tables. These can have many interesting uses
2723             for joining regular DBMS data with some other kind of data within your
2724             Perl programs. Bundled with the present distribution are :
2725              
2726             =over
2727              
2728             =item *
2729              
2730             L<DBD::SQLite::VirtualTable::FileContent> : implements a virtual
2731             column that exposes file contents. This is especially useful
2732             in conjunction with a fulltext index; see L<DBD::SQLite::Fulltext_search>.
2733              
2734             =item *
2735              
2736             L<DBD::SQLite::VirtualTable::PerlData> : binds to a Perl array
2737             within the Perl program. This can be used for simple import/export
2738             operations, for debugging purposes, for joining data from different
2739             sources, etc.
2740              
2741             =back
2742              
2743             Other Perl virtual tables may also be published separately on CPAN.
2744              
2745             =head1 FOR DBD::SQLITE EXTENSION AUTHORS
2746              
2747             Since 1.30_01, you can retrieve the bundled SQLite C source and/or
2748             header like this:
2749              
2750             use File::ShareDir 'dist_dir';
2751             use File::Spec::Functions 'catfile';
2752            
2753             # the whole sqlite3.h header
2754             my $sqlite3_h = catfile(dist_dir('DBD-SQLite'), 'sqlite3.h');
2755            
2756             # or only a particular header, amalgamated in sqlite3.c
2757             my $what_i_want = 'parse.h';
2758             my $sqlite3_c = catfile(dist_dir('DBD-SQLite'), 'sqlite3.c');
2759             open my $fh, '<', $sqlite3_c or die $!;
2760             my $code = do { local $/; <$fh> };
2761             my ($parse_h) = $code =~ m{(
2762             /\*+[ ]Begin[ ]file[ ]$what_i_want[ ]\*+
2763             .+?
2764             /\*+[ ]End[ ]of[ ]$what_i_want[ ]\*+/
2765             )}sx;
2766             open my $out, '>', $what_i_want or die $!;
2767             print $out $parse_h;
2768             close $out;
2769              
2770             You usually want to use this in your extension's C<Makefile.PL>,
2771             and you may want to add DBD::SQLite to your extension's C<CONFIGURE_REQUIRES>
2772             to ensure your extension users use the same C source/header they use
2773             to build DBD::SQLite itself (instead of the ones installed in their
2774             system).
2775              
2776             =head1 TO DO
2777              
2778             The following items remain to be done.
2779              
2780             =head2 Leak Detection
2781              
2782             Implement one or more leak detection tests that only run during
2783             AUTOMATED_TESTING and RELEASE_TESTING and validate that none of the C
2784             code we work with leaks.
2785              
2786             =head2 Stream API for Blobs
2787              
2788             Reading/writing into blobs using C<sqlite2_blob_open> / C<sqlite2_blob_close>.
2789              
2790             =head2 Support for custom callbacks for R-Tree queries
2791              
2792             Custom queries of a R-Tree index using a callback are possible with
2793             the SQLite C API (L<https://www.sqlite.org/rtree.html>), so one could
2794             potentially use a callback that narrowed the result set down based
2795             on a specific need, such as querying for overlapping circles.
2796              
2797             =head1 SUPPORT
2798              
2799             Bugs should be reported to GitHub issues:
2800              
2801             L<https://github.com/DBD-SQLite/DBD-SQLite/issues>
2802              
2803             or via RT if you prefer:
2804              
2805             L<http://rt.cpan.org/NoAuth/ReportBug.html?Queue=DBD-SQLite>
2806              
2807             Note that bugs of bundled SQLite library (i.e. bugs in C<sqlite3.[ch]>)
2808             should be reported to the SQLite developers at sqlite.org via their bug
2809             tracker or via their mailing list.
2810              
2811             The master repository is on GitHub:
2812              
2813             L<https://github.com/DBD-SQLite/DBD-SQLite>.
2814              
2815             We also have a mailing list:
2816              
2817             L<http://lists.scsys.co.uk/cgi-bin/mailman/listinfo/dbd-sqlite>
2818              
2819             =head1 AUTHORS
2820              
2821             Matt Sergeant E<lt>matt@sergeant.orgE<gt>
2822              
2823             Francis J. Lacoste E<lt>flacoste@logreport.orgE<gt>
2824              
2825             Wolfgang Sourdeau E<lt>wolfgang@logreport.orgE<gt>
2826              
2827             Adam Kennedy E<lt>adamk@cpan.orgE<gt>
2828              
2829             Max Maischein E<lt>corion@cpan.orgE<gt>
2830              
2831             Laurent Dami E<lt>dami@cpan.orgE<gt>
2832              
2833             Kenichi Ishigaki E<lt>ishigaki@cpan.orgE<gt>
2834              
2835             =head1 COPYRIGHT
2836              
2837             The bundled SQLite code in this distribution is Public Domain.
2838              
2839             DBD::SQLite is copyright 2002 - 2007 Matt Sergeant.
2840              
2841             Some parts copyright 2008 Francis J. Lacoste.
2842              
2843             Some parts copyright 2008 Wolfgang Sourdeau.
2844              
2845             Some parts copyright 2008 - 2013 Adam Kennedy.
2846              
2847             Some parts copyright 2009 - 2013 Kenichi Ishigaki.
2848              
2849             Some parts derived from L<DBD::SQLite::Amalgamation>
2850             copyright 2008 Audrey Tang.
2851              
2852             This program is free software; you can redistribute
2853             it and/or modify it under the same terms as Perl itself.
2854              
2855             The full text of the license can be found in the
2856             LICENSE file included with this module.
2857              
2858             =cut