1 package DBIx::Class::Storage::DBI::SQLite;
6 use base qw/DBIx::Class::Storage::DBI/;
9 use DBIx::Class::_Util qw(modver_gt_or_eq sigwarn_silencer);
10 use DBIx::Class::Carp;
14 __PACKAGE__->sql_maker_class('DBIx::Class::SQLMaker::SQLite');
15 __PACKAGE__->sql_limit_dialect ('LimitOffset');
16 __PACKAGE__->sql_quote_char ('"');
17 __PACKAGE__->datetime_parser_type ('DateTime::Format::SQLite');
21 DBIx::Class::Storage::DBI::SQLite - Automatic primary key class for SQLite
25 # In your table classes
26 use base 'DBIx::Class::Core';
27 __PACKAGE__->set_primary_key('id');
31 This class implements autoincrements for SQLite.
39 NOTE - This section applies to you only if ALL of these are true:
41 * You are or were using DBD::SQLite with a version lesser than 1.38_01
43 * You are or were using DBIx::Class versions between 0.08191 and 0.08209
44 (inclusive) or between 0.08240-TRIAL and 0.08242-TRIAL (also inclusive)
46 * You use objects with overloaded stringification and are feeding them
47 to DBIC CRUD methods directly
49 An unfortunate chain of events led to DBIx::Class silently hitting the problem
50 described in L<RT#79576|https://rt.cpan.org/Public/Bug/Display.html?id=79576>.
52 In order to trigger the bug condition one needs to supply B<more than one>
53 bind value that is an object with overloaded stringification (numification
54 is not relevant, only stringification is). When this is the case the internal
55 DBIx::Class call to C<< $sth->bind_param >> would be executed in a way that
56 triggers the above-mentioned DBD::SQLite bug. As a result all the logs and
57 tracers will contain the expected values, however SQLite will receive B<all>
58 these bind positions being set to the value of the B<last> supplied
61 Even if you upgrade DBIx::Class (which works around the bug starting from
62 version 0.08210) you may still have corrupted/incorrect data in your database.
63 DBIx::Class warned about this condition for several years, hoping to give
64 anyone affected sufficient notice of the potential issues. The warning was
79 my ($self, $dir) = @_;
82 ## Where is the db file?
83 my $dsn = $self->_dbi_connect_info()->[0];
85 my $dbname = $1 if($dsn =~ /dbname=([^;]+)/);
88 $dbname = $1 if($dsn =~ /^dbi:SQLite:(.+)$/i);
90 $self->throw_exception("Cannot determine name of SQLite db file")
91 if(!$dbname || !-f $dbname);
93 # print "Found database: $dbname\n";
94 # my $dbfile = file($dbname);
95 my ($vol, $dbdir, $file) = File::Spec->splitpath($dbname);
96 # my $file = $dbfile->basename();
97 $file = POSIX::strftime("%Y-%m-%d-%H_%M_%S", localtime()) . $file;
98 $file = "B$file" while(-f $file);
100 mkdir($dir) unless -f $dir;
101 my $backupfile = File::Spec->catfile($dir, $file);
103 my $res = File::Copy::copy($dbname, $backupfile);
104 $self->throw_exception("Backup failed! ($!)") if(!$res);
109 sub _exec_svp_begin {
110 my ($self, $name) = @_;
112 $self->_dbh->do("SAVEPOINT $name");
115 sub _exec_svp_release {
116 my ($self, $name) = @_;
118 $self->_dbh->do("RELEASE SAVEPOINT $name");
121 sub _exec_svp_rollback {
122 my ($self, $name) = @_;
124 # For some reason this statement changes the value of $dbh->{AutoCommit}, so
125 # we localize it here to preserve the original value.
126 local $self->_dbh->{AutoCommit} = $self->_dbh->{AutoCommit};
128 $self->_dbh->do("ROLLBACK TRANSACTION TO SAVEPOINT $name");
134 # Be extremely careful what we do here. SQLite is notoriously bad at
135 # synchronizing its internal transaction state with {AutoCommit}
136 # https://metacpan.org/source/ADAMK/DBD-SQLite-1.37/lib/DBD/SQLite.pm#L921
137 # There is a function http://www.sqlite.org/c3ref/get_autocommit.html
138 # but DBD::SQLite does not expose it (nor does it seem to properly use it)
140 # Therefore only execute a "ping" when we have no other choice *AND*
141 # scrutinize the thrown exceptions to make sure we are where we think we are
142 my $dbh = $self->_dbh or return undef;
143 return undef unless $dbh->FETCH('Active');
144 return undef unless $dbh->ping;
148 # older DBD::SQLite does not properly synchronize commit state between
149 # the libsqlite and the $dbh
150 unless (defined $DBD::SQLite::__DBIC_TXN_SYNC_SANE__) {
151 $DBD::SQLite::__DBIC_TXN_SYNC_SANE__ = modver_gt_or_eq('DBD::SQLite', '1.38_02');
154 # fallback to travesty
155 unless ($DBD::SQLite::__DBIC_TXN_SYNC_SANE__) {
156 # since we do not have access to sqlite3_get_autocommit(), do a trick
157 # to attempt to *safely* determine what state are we *actually* in.
159 # also using T::T here leads to bizarre leaks - will figure it out later
160 my $really_not_in_txn = do {
163 # older versions of DBD::SQLite do not properly detect multiline BEGIN/COMMIT
164 # statements to adjust their {AutoCommit} state. Hence use such a statement
165 # pair here as well, in order to escape from poking {AutoCommit} needlessly
166 # https://rt.cpan.org/Public/Bug/Display.html?id=80087
168 # will fail instantly if already in a txn
169 $dbh->do("-- multiline\nBEGIN");
170 $dbh->do("-- multiline\nCOMMIT");
173 ($@ =~ /transaction within a transaction/)
180 # if we were unable to determine this - we may very well be dead
181 if (not defined $really_not_in_txn) {
184 # check the AC sync-state
185 elsif ($really_not_in_txn xor $dbh->{AutoCommit}) {
187 'Internal transaction state of handle %s (apparently %s a transaction) does not seem to '
188 . 'match its AutoCommit attribute setting of %s - this is an indication of a '
189 . 'potentially serious bug in your transaction handling logic',
191 $really_not_in_txn ? 'NOT in' : 'in',
192 $dbh->{AutoCommit} ? 'TRUE' : 'FALSE',
195 # it is too dangerous to execute anything else in this state
196 # assume everything works (safer - worst case scenario next statement throws)
201 # do the actual test and return on no failure
202 ( $ping_fail ||= ! try { $dbh->do('SELECT * FROM sqlite_master LIMIT 1'); 1 } )
203 or return 1; # the actual RV of _ping()
205 # ping failed (or so it seems) - need to do some cleanup
206 # it is possible to have a proper "connection", and have "ping" return
207 # false anyway (e.g. corrupted file). In such cases DBD::SQLite still
208 # keeps the actual file handle open. We don't really want this to happen,
209 # so force-close the handle via DBI itself
211 local $@; # so that we do not clobber the real error as set above
212 eval { $dbh->disconnect }; # if it fails - it fails
213 undef; # the actual RV of _ping()
216 sub deployment_statements {
218 my ($schema, $type, $version, $dir, $sqltargs, @rest) = @_;
223 ! exists $sqltargs->{producer_args}{sqlite_version}
225 my $dver = $self->_server_info->{normalized_dbms_version}
227 $sqltargs->{producer_args}{sqlite_version} = $dver;
230 $sqltargs->{quote_identifiers}
231 = !!$self->sql_maker->_quote_chars
232 if ! exists $sqltargs->{quote_identifiers};
234 $self->next::method($schema, $type, $version, $dir, $sqltargs, @rest);
237 sub bind_attribute_by_data_type {
239 # According to http://www.sqlite.org/datatype3.html#storageclasses
240 # all numeric types are dynamically allocated up to 8 bytes per
242 # Thus it should be safe and non-wasteful to bind everything as
243 # SQL_BIGINT and have SQLite deal with storage/comparisons however
245 $_[1] =~ /^ (?: int(?:[1248]|eger)? | (?:tiny|small|medium|big)int ) $/ix
251 # FIXME - what the flying fuck... work around RT#76395
252 # DBD::SQLite warns on binding >32 bit values with 32 bit IVs
256 DBIx::Class::_ENV_::IV_SIZE < 8
258 DBIx::Class::_ENV_::OS_NAME eq 'MSWin32'
261 ! defined $DBD::SQLite::__DBIC_CHECK_dbd_mishandles_bound_BIGINT
263 $DBD::SQLite::__DBIC_CHECK_dbd_mishandles_bound_BIGINT = (
264 modver_gt_or_eq('DBD::SQLite', '1.37')
268 local $SIG{__WARN__} = sigwarn_silencer( qr/
269 \Qdatatype mismatch: bind\E \s (?:
270 param \s+ \( \d+ \) \s+ [-+]? \d+ (?: \. 0*)? \Q as integer\E
272 \d+ \s type \s @{[ DBI::SQL_BIGINT() ]} \s as \s [-+]? \d+ (?: \. 0*)?
276 DBIx::Class::_ENV_::IV_SIZE < 8
278 DBIx::Class::_ENV_::OS_NAME eq 'MSWin32'
281 $DBD::SQLite::__DBIC_CHECK_dbd_mishandles_bound_BIGINT
284 shift->next::method(@_);
287 # DBD::SQLite (at least up to version 1.31 has a bug where it will
288 # non-fatally numify a string value bound as an integer, resulting
289 # in insertions of '0' into supposed-to-be-numeric fields
290 # Since this can result in severe data inconsistency, remove the
291 # bind attr if such a situation is detected
293 # FIXME - when a DBD::SQLite version is released that eventually fixes
294 # this situation (somehow) - no-op this override once a proper DBD
295 # version is detected
296 sub _dbi_attrs_for_bind {
297 my ($self, $ident, $bind) = @_;
299 my $bindattrs = $self->next::method($ident, $bind);
301 if (! defined $DBD::SQLite::__DBIC_CHECK_dbd_can_bind_bigint_values) {
302 $DBD::SQLite::__DBIC_CHECK_dbd_can_bind_bigint_values
303 = modver_gt_or_eq('DBD::SQLite', '1.37') ? 1 : 0;
306 for my $i (0.. $#$bindattrs) {
308 defined $bindattrs->[$i]
310 defined $bind->[$i][1]
312 grep { $bindattrs->[$i] eq $_ } (
313 DBI::SQL_INTEGER(), DBI::SQL_TINYINT(), DBI::SQL_SMALLINT(), DBI::SQL_BIGINT()
316 if ( $bind->[$i][1] !~ /^ [\+\-]? [0-9]+ (?: \. 0* )? $/x ) {
317 carp_unique( sprintf (
318 "Non-integer value supplied for column '%s' despite the integer datatype",
319 $bind->[$i][0]{dbic_colname} || "# $i"
321 undef $bindattrs->[$i];
324 ! $DBD::SQLite::__DBIC_CHECK_dbd_can_bind_bigint_values
326 # unsigned 32 bit ints have a range of −2,147,483,648 to 2,147,483,647
327 # alternatively expressed as the hexadecimal numbers below
328 # the comparison math will come out right regardless of ivsize, since
329 # we are operating within 31 bits
330 # P.S. 31 because one bit is lost for the sign
331 if ($bind->[$i][1] > 0x7fff_ffff or $bind->[$i][1] < -0x8000_0000) {
332 carp_unique( sprintf (
333 "An integer value occupying more than 32 bits was supplied for column '%s' "
334 . 'which your version of DBD::SQLite (%s) can not bind properly so DBIC '
335 . 'will treat it as a string instead, consider upgrading to at least '
336 . 'DBD::SQLite version 1.37',
337 $bind->[$i][0]{dbic_colname} || "# $i",
338 DBD::SQLite->VERSION,
340 undef $bindattrs->[$i];
343 $bindattrs->[$i] = DBI::SQL_INTEGER()
352 =head2 connect_call_use_foreign_keys
356 on_connect_call => 'use_foreign_keys'
358 In L<connect_info|DBIx::Class::Storage::DBI/connect_info> to turn on foreign key
359 (including cascading) support for recent versions of SQLite and L<DBD::SQLite>.
363 PRAGMA foreign_keys = ON
365 See L<http://www.sqlite.org/foreignkeys.html> for more information.
369 sub connect_call_use_foreign_keys {
373 'PRAGMA foreign_keys = ON'
379 =head1 AUTHOR AND CONTRIBUTORS
381 See L<AUTHOR|DBIx::Class/AUTHOR> and L<CONTRIBUTORS|DBIx::Class/CONTRIBUTORS> in DBIx::Class
385 You may distribute this code under the same terms as Perl itself.