1 package DBIx::Class::Storage::DBI::SQLite;
6 use base qw/DBIx::Class::Storage::DBI/;
9 use SQL::Abstract 'is_plain_value';
10 use DBIx::Class::_Util qw(modver_gt_or_eq sigwarn_silencer dbic_internal_try);
11 use DBIx::Class::Carp;
15 __PACKAGE__->sql_maker_class('DBIx::Class::SQLMaker::SQLite');
16 __PACKAGE__->sql_limit_dialect ('LimitOffset');
17 __PACKAGE__->sql_quote_char ('"');
18 __PACKAGE__->datetime_parser_type ('DateTime::Format::SQLite');
22 DBIx::Class::Storage::DBI::SQLite - Automatic primary key class for SQLite
26 # In your table classes
27 use base 'DBIx::Class::Core';
28 __PACKAGE__->set_primary_key('id');
32 This class implements autoincrements for SQLite.
40 NOTE - This section applies to you only if ALL of these are true:
42 * You are or were using DBD::SQLite with a version lesser than 1.38_01
44 * You are or were using DBIx::Class versions between 0.08191 and 0.08209
45 (inclusive) or between 0.08240-TRIAL and 0.08242-TRIAL (also inclusive)
47 * You use objects with overloaded stringification and are feeding them
48 to DBIC CRUD methods directly
50 An unfortunate chain of events led to DBIx::Class silently hitting the problem
51 described in L<RT#79576|https://rt.cpan.org/Public/Bug/Display.html?id=79576>.
53 In order to trigger the bug condition one needs to supply B<more than one>
54 bind value that is an object with overloaded stringification (numification
55 is not relevant, only stringification is). When this is the case the internal
56 DBIx::Class call to C<< $sth->bind_param >> would be executed in a way that
57 triggers the above-mentioned DBD::SQLite bug. As a result all the logs and
58 tracers will contain the expected values, however SQLite will receive B<all>
59 these bind positions being set to the value of the B<last> supplied
62 Even if you upgrade DBIx::Class (which works around the bug starting from
63 version 0.08210) you may still have corrupted/incorrect data in your database.
64 DBIx::Class warned about this condition for several years, hoping to give
65 anyone affected sufficient notice of the potential issues. The warning was
66 removed in version 0.082900.
80 my ($self, $dir) = @_;
83 ## Where is the db file?
84 my $dsn = $self->_dbi_connect_info()->[0];
86 my $dbname = $1 if($dsn =~ /dbname=([^;]+)/);
89 $dbname = $1 if($dsn =~ /^dbi:SQLite:(.+)$/i);
91 $self->throw_exception("Cannot determine name of SQLite db file")
92 if(!$dbname || !-f $dbname);
94 # print "Found database: $dbname\n";
95 # my $dbfile = file($dbname);
96 my ($vol, $dbdir, $file) = File::Spec->splitpath($dbname);
97 # my $file = $dbfile->basename();
98 $file = POSIX::strftime("%Y-%m-%d-%H_%M_%S", localtime()) . $file;
99 $file = "B$file" while(-f $file);
101 mkdir($dir) unless -f $dir;
102 my $backupfile = File::Spec->catfile($dir, $file);
104 my $res = File::Copy::copy($dbname, $backupfile);
105 $self->throw_exception("Backup failed! ($!)") if(!$res);
110 sub _exec_svp_begin {
111 my ($self, $name) = @_;
113 $self->_dbh->do("SAVEPOINT $name");
116 sub _exec_svp_release {
117 my ($self, $name) = @_;
119 $self->_dbh->do("RELEASE SAVEPOINT $name");
122 sub _exec_svp_rollback {
123 my ($self, $name) = @_;
125 $self->_dbh->do("ROLLBACK TO SAVEPOINT $name");
127 # resync state for older DBD::SQLite (RT#67843)
128 # https://github.com/DBD-SQLite/DBD-SQLite/commit/9b3cdbf
130 ! modver_gt_or_eq('DBD::SQLite', '1.33')
132 $self->_dbh->FETCH('AutoCommit')
134 $self->_dbh->STORE('AutoCommit', 0);
135 $self->_dbh->STORE('BegunWork', 1);
142 # Be extremely careful what we do here. SQLite is notoriously bad at
143 # synchronizing its internal transaction state with {AutoCommit}
144 # https://metacpan.org/source/ADAMK/DBD-SQLite-1.37/lib/DBD/SQLite.pm#L921
145 # There is a function http://www.sqlite.org/c3ref/get_autocommit.html
146 # but DBD::SQLite does not expose it (nor does it seem to properly use it)
148 # Therefore only execute a "ping" when we have no other choice *AND*
149 # scrutinize the thrown exceptions to make sure we are where we think we are
150 my $dbh = $self->_dbh or return undef;
151 return undef unless $dbh->FETCH('Active');
152 return undef unless $dbh->ping;
156 # older DBD::SQLite does not properly synchronize commit state between
157 # the libsqlite and the $dbh
158 unless (defined $DBD::SQLite::__DBIC_TXN_SYNC_SANE__) {
159 $DBD::SQLite::__DBIC_TXN_SYNC_SANE__ = modver_gt_or_eq('DBD::SQLite', '1.38_02');
162 # fallback to travesty
163 unless ($DBD::SQLite::__DBIC_TXN_SYNC_SANE__) {
164 # since we do not have access to sqlite3_get_autocommit(), do a trick
165 # to attempt to *safely* determine what state are we *actually* in.
167 my $really_not_in_txn;
169 # not assigning RV directly to env above, because this causes a bizarre
170 # leak of the catch{} cref on older perls... wtf
173 # older versions of DBD::SQLite do not properly detect multiline BEGIN/COMMIT
174 # statements to adjust their {AutoCommit} state. Hence use such a statement
175 # pair here as well, in order to escape from poking {AutoCommit} needlessly
176 # https://rt.cpan.org/Public/Bug/Display.html?id=80087
178 # will fail instantly if already in a txn
179 $dbh->do("-- multiline\nBEGIN");
180 $dbh->do("-- multiline\nCOMMIT");
182 $really_not_in_txn = 1;
185 $really_not_in_txn = ( $_[0] =~ qr/transaction within a transaction/
191 # if we were unable to determine this - we may very well be dead
192 if (not defined $really_not_in_txn) {
195 # check the AC sync-state
196 elsif ($really_not_in_txn xor $dbh->{AutoCommit}) {
198 'Internal transaction state of handle %s (apparently %s a transaction) does not seem to '
199 . 'match its AutoCommit attribute setting of %s - this is an indication of a '
200 . 'potentially serious bug in your transaction handling logic',
202 $really_not_in_txn ? 'NOT in' : 'in',
203 $dbh->{AutoCommit} ? 'TRUE' : 'FALSE',
206 # it is too dangerous to execute anything else in this state
207 # assume everything works (safer - worst case scenario next statement throws)
212 # do the actual test and return on no failure
213 ( $ping_fail ||= ! dbic_internal_try { $dbh->do('SELECT * FROM sqlite_master LIMIT 1'); 1 } )
214 or return 1; # the actual RV of _ping()
216 # ping failed (or so it seems) - need to do some cleanup
217 # it is possible to have a proper "connection", and have "ping" return
218 # false anyway (e.g. corrupted file). In such cases DBD::SQLite still
219 # keeps the actual file handle open. We don't really want this to happen,
220 # so force-close the handle via DBI itself
222 dbic_internal_try { $dbh->disconnect }; # if it fails - it fails
223 undef; # the actual RV of _ping()
226 sub deployment_statements {
228 my ($schema, $type, $version, $dir, $sqltargs, @rest) = @_;
233 ! exists $sqltargs->{producer_args}{sqlite_version}
235 my $dver = $self->_server_info->{normalized_dbms_version}
237 $sqltargs->{producer_args}{sqlite_version} = $dver;
240 $self->next::method($schema, $type, $version, $dir, $sqltargs, @rest);
243 sub bind_attribute_by_data_type {
245 # According to http://www.sqlite.org/datatype3.html#storageclasses
246 # all numeric types are dynamically allocated up to 8 bytes per
248 # Thus it should be safe and non-wasteful to bind everything as
249 # SQL_BIGINT and have SQLite deal with storage/comparisons however
251 $_[1] =~ /^ (?: int(?:[1248]|eger)? | (?:tiny|small|medium|big)int ) $/ix
257 # FIXME - what the flying fuck... work around RT#76395
258 # DBD::SQLite warns on binding >32 bit values with 32 bit IVs
262 DBIx::Class::_ENV_::IV_SIZE < 8
264 DBIx::Class::_ENV_::OS_NAME eq 'MSWin32'
267 ! defined $DBD::SQLite::__DBIC_CHECK_dbd_mishandles_bound_BIGINT
269 $DBD::SQLite::__DBIC_CHECK_dbd_mishandles_bound_BIGINT = (
270 modver_gt_or_eq('DBD::SQLite', '1.37')
274 local $SIG{__WARN__} = sigwarn_silencer( qr/
275 \Qdatatype mismatch: bind\E \s (?:
276 param \s+ \( \d+ \) \s+ [-+]? \d+ (?: \. 0*)? \Q as integer\E
278 \d+ \s type \s @{[ DBI::SQL_BIGINT() ]} \s as \s [-+]? \d+ (?: \. 0*)?
282 DBIx::Class::_ENV_::IV_SIZE < 8
284 DBIx::Class::_ENV_::OS_NAME eq 'MSWin32'
287 $DBD::SQLite::__DBIC_CHECK_dbd_mishandles_bound_BIGINT
290 shift->next::method(@_);
293 # DBD::SQLite (at least up to version 1.31 has a bug where it will
294 # non-fatally numify a string value bound as an integer, resulting
295 # in insertions of '0' into supposed-to-be-numeric fields
296 # Since this can result in severe data inconsistency, remove the
297 # bind attr if such a situation is detected
299 # FIXME - when a DBD::SQLite version is released that eventually fixes
300 # this situation (somehow) - no-op this override once a proper DBD
301 # version is detected
302 sub _dbi_attrs_for_bind {
303 my ($self, $ident, $bind) = @_;
305 my $bindattrs = $self->next::method($ident, $bind);
307 if (! defined $DBD::SQLite::__DBIC_CHECK_dbd_can_bind_bigint_values) {
308 $DBD::SQLite::__DBIC_CHECK_dbd_can_bind_bigint_values
309 = modver_gt_or_eq('DBD::SQLite', '1.37') ? 1 : 0;
312 for my $i (0.. $#$bindattrs) {
314 defined $bindattrs->[$i]
316 defined $bind->[$i][1]
318 grep { $bindattrs->[$i] eq $_ } (
319 DBI::SQL_INTEGER(), DBI::SQL_TINYINT(), DBI::SQL_SMALLINT(), DBI::SQL_BIGINT()
322 if ( $bind->[$i][1] !~ /^ [\+\-]? [0-9]+ (?: \. 0* )? $/x ) {
323 carp_unique( sprintf (
324 "Non-integer value supplied for column '%s' despite the integer datatype",
325 $bind->[$i][0]{dbic_colname} || "# $i"
327 undef $bindattrs->[$i];
330 ! $DBD::SQLite::__DBIC_CHECK_dbd_can_bind_bigint_values
332 # unsigned 32 bit ints have a range of −2,147,483,648 to 2,147,483,647
333 # alternatively expressed as the hexadecimal numbers below
334 # the comparison math will come out right regardless of ivsize, since
335 # we are operating within 31 bits
336 # P.S. 31 because one bit is lost for the sign
337 if ($bind->[$i][1] > 0x7fff_ffff or $bind->[$i][1] < -0x8000_0000) {
338 carp_unique( sprintf (
339 "An integer value occupying more than 32 bits was supplied for column '%s' "
340 . 'which your version of DBD::SQLite (%s) can not bind properly so DBIC '
341 . 'will treat it as a string instead, consider upgrading to at least '
342 . 'DBD::SQLite version 1.37',
343 $bind->[$i][0]{dbic_colname} || "# $i",
344 DBD::SQLite->VERSION,
346 undef $bindattrs->[$i];
349 $bindattrs->[$i] = DBI::SQL_INTEGER()
358 =head2 connect_call_use_foreign_keys
362 on_connect_call => 'use_foreign_keys'
364 In L<connect_info|DBIx::Class::Storage::DBI/connect_info> to turn on foreign key
365 (including cascading) support for recent versions of SQLite and L<DBD::SQLite>.
369 PRAGMA foreign_keys = ON
371 See L<http://www.sqlite.org/foreignkeys.html> for more information.
375 sub connect_call_use_foreign_keys {
379 'PRAGMA foreign_keys = ON'
383 =head1 FURTHER QUESTIONS?
385 Check the list of L<additional DBIC resources|DBIx::Class/GETTING HELP/SUPPORT>.
387 =head1 COPYRIGHT AND LICENSE
389 This module is free software L<copyright|DBIx::Class/COPYRIGHT AND LICENSE>
390 by the L<DBIx::Class (DBIC) authors|DBIx::Class/AUTHORS>. You can
391 redistribute it and/or modify it under the same terms as the
392 L<DBIx::Class library|DBIx::Class/COPYRIGHT AND LICENSE>.