Introduce GOVERNANCE document and empty RESOLUTIONS file.
[dbsrgits/DBIx-Class.git] / lib / DBIx / Class / Storage / DBI / SQLite.pm
CommitLineData
843f8ecd 1package DBIx::Class::Storage::DBI::SQLite;
2
3use strict;
4use warnings;
2ad62d97 5
6use base qw/DBIx::Class::Storage::DBI/;
7use mro 'c3';
8
b5ce6748 9use SQL::Abstract 'is_plain_value';
e2741c7f 10use DBIx::Class::_Util qw(
11 modver_gt_or_eq sigwarn_silencer
12 dbic_internal_try dbic_internal_catch
13);
632d1e0f 14use DBIx::Class::Carp;
632d1e0f 15use namespace::clean;
16
d5dedbd6 17__PACKAGE__->sql_maker_class('DBIx::Class::SQLMaker::SQLite');
6a247f33 18__PACKAGE__->sql_limit_dialect ('LimitOffset');
2b8cc2f2 19__PACKAGE__->sql_quote_char ('"');
6f7a118e 20__PACKAGE__->datetime_parser_type ('DateTime::Format::SQLite');
09cedb88 21
2fa97c7d 22=head1 NAME
23
24DBIx::Class::Storage::DBI::SQLite - Automatic primary key class for SQLite
25
26=head1 SYNOPSIS
27
28 # In your table classes
29 use base 'DBIx::Class::Core';
30 __PACKAGE__->set_primary_key('id');
31
32=head1 DESCRIPTION
33
34This class implements autoincrements for SQLite.
35
75a1d824 36=head2 Known Issues
37
38=over
39
40=item RT79576
41
42 NOTE - This section applies to you only if ALL of these are true:
43
44 * You are or were using DBD::SQLite with a version lesser than 1.38_01
45
46 * You are or were using DBIx::Class versions between 0.08191 and 0.08209
47 (inclusive) or between 0.08240-TRIAL and 0.08242-TRIAL (also inclusive)
48
49 * You use objects with overloaded stringification and are feeding them
50 to DBIC CRUD methods directly
51
52An unfortunate chain of events led to DBIx::Class silently hitting the problem
53described in L<RT#79576|https://rt.cpan.org/Public/Bug/Display.html?id=79576>.
54
55In order to trigger the bug condition one needs to supply B<more than one>
4a0eed52 56bind value that is an object with overloaded stringification (numification
75a1d824 57is not relevant, only stringification is). When this is the case the internal
58DBIx::Class call to C<< $sth->bind_param >> would be executed in a way that
59triggers the above-mentioned DBD::SQLite bug. As a result all the logs and
60tracers will contain the expected values, however SQLite will receive B<all>
61these bind positions being set to the value of the B<last> supplied
62stringifiable object.
63
64Even if you upgrade DBIx::Class (which works around the bug starting from
65version 0.08210) you may still have corrupted/incorrect data in your database.
cff17b97 66DBIx::Class warned about this condition for several years, hoping to give
67anyone affected sufficient notice of the potential issues. The warning was
f0c2d11f 68removed in 2015/v0.082820.
75a1d824 69
70=back
71
2fa97c7d 72=head1 METHODS
73
74=cut
75
357eb92c 76sub backup {
77
78 require File::Spec;
79 require File::Copy;
80 require POSIX;
81
8795fefb 82 my ($self, $dir) = @_;
83 $dir ||= './';
c9d2e0a2 84
85 ## Where is the db file?
12c9beea 86 my $dsn = $self->_dbi_connect_info()->[0];
c9d2e0a2 87
88 my $dbname = $1 if($dsn =~ /dbname=([^;]+)/);
89 if(!$dbname)
90 {
91 $dbname = $1 if($dsn =~ /^dbi:SQLite:(.+)$/i);
92 }
357eb92c 93 $self->throw_exception("Cannot determine name of SQLite db file")
c9d2e0a2 94 if(!$dbname || !-f $dbname);
95
96# print "Found database: $dbname\n";
79923569 97# my $dbfile = file($dbname);
8795fefb 98 my ($vol, $dbdir, $file) = File::Spec->splitpath($dbname);
79923569 99# my $file = $dbfile->basename();
357eb92c 100 $file = POSIX::strftime("%Y-%m-%d-%H_%M_%S", localtime()) . $file;
c9d2e0a2 101 $file = "B$file" while(-f $file);
8795fefb 102
103 mkdir($dir) unless -f $dir;
104 my $backupfile = File::Spec->catfile($dir, $file);
105
357eb92c 106 my $res = File::Copy::copy($dbname, $backupfile);
c9d2e0a2 107 $self->throw_exception("Backup failed! ($!)") if(!$res);
108
8795fefb 109 return $backupfile;
c9d2e0a2 110}
111
86a51471 112sub _exec_svp_begin {
113 my ($self, $name) = @_;
114
115 $self->_dbh->do("SAVEPOINT $name");
116}
117
118sub _exec_svp_release {
119 my ($self, $name) = @_;
120
121 $self->_dbh->do("RELEASE SAVEPOINT $name");
122}
123
124sub _exec_svp_rollback {
125 my ($self, $name) = @_;
126
398215b1 127 $self->_dbh->do("ROLLBACK TO SAVEPOINT $name");
86a51471 128
66c817df 129 # resync state for older DBD::SQLite (RT#67843)
130 # https://github.com/DBD-SQLite/DBD-SQLite/commit/9b3cdbf
131 if (
132 ! modver_gt_or_eq('DBD::SQLite', '1.33')
133 and
134 $self->_dbh->FETCH('AutoCommit')
135 ) {
136 $self->_dbh->STORE('AutoCommit', 0);
137 $self->_dbh->STORE('BegunWork', 1);
138 }
86a51471 139}
140
8d1fb3e2 141sub _ping {
142 my $self = shift;
2aeb3c7f 143
144 # Be extremely careful what we do here. SQLite is notoriously bad at
145 # synchronizing its internal transaction state with {AutoCommit}
146 # https://metacpan.org/source/ADAMK/DBD-SQLite-1.37/lib/DBD/SQLite.pm#L921
147 # There is a function http://www.sqlite.org/c3ref/get_autocommit.html
148 # but DBD::SQLite does not expose it (nor does it seem to properly use it)
149
150 # Therefore only execute a "ping" when we have no other choice *AND*
151 # scrutinize the thrown exceptions to make sure we are where we think we are
152 my $dbh = $self->_dbh or return undef;
153 return undef unless $dbh->FETCH('Active');
154 return undef unless $dbh->ping;
155
ab0b0a09 156 my $ping_fail;
157
158 # older DBD::SQLite does not properly synchronize commit state between
159 # the libsqlite and the $dbh
160 unless (defined $DBD::SQLite::__DBIC_TXN_SYNC_SANE__) {
b1dbf716 161 $DBD::SQLite::__DBIC_TXN_SYNC_SANE__ = modver_gt_or_eq('DBD::SQLite', '1.38_02');
ab0b0a09 162 }
2aeb3c7f 163
ab0b0a09 164 # fallback to travesty
165 unless ($DBD::SQLite::__DBIC_TXN_SYNC_SANE__) {
166 # since we do not have access to sqlite3_get_autocommit(), do a trick
167 # to attempt to *safely* determine what state are we *actually* in.
ddcc02d1 168
169 my $really_not_in_txn;
170
171 # not assigning RV directly to env above, because this causes a bizarre
172 # leak of the catch{} cref on older perls... wtf
173 dbic_internal_try {
ab0b0a09 174
175 # older versions of DBD::SQLite do not properly detect multiline BEGIN/COMMIT
176 # statements to adjust their {AutoCommit} state. Hence use such a statement
177 # pair here as well, in order to escape from poking {AutoCommit} needlessly
178 # https://rt.cpan.org/Public/Bug/Display.html?id=80087
ddcc02d1 179 #
180 # will fail instantly if already in a txn
181 $dbh->do("-- multiline\nBEGIN");
182 $dbh->do("-- multiline\nCOMMIT");
183
184 $really_not_in_txn = 1;
185 }
e2741c7f 186 dbic_internal_catch {
ddcc02d1 187 $really_not_in_txn = ( $_[0] =~ qr/transaction within a transaction/
188 ? 0
189 : undef
190 );
2aeb3c7f 191 };
2aeb3c7f 192
ab0b0a09 193 # if we were unable to determine this - we may very well be dead
194 if (not defined $really_not_in_txn) {
195 $ping_fail = 1;
196 }
197 # check the AC sync-state
198 elsif ($really_not_in_txn xor $dbh->{AutoCommit}) {
199 carp_unique (sprintf
200 'Internal transaction state of handle %s (apparently %s a transaction) does not seem to '
201 . 'match its AutoCommit attribute setting of %s - this is an indication of a '
202 . 'potentially serious bug in your transaction handling logic',
203 $dbh,
204 $really_not_in_txn ? 'NOT in' : 'in',
205 $dbh->{AutoCommit} ? 'TRUE' : 'FALSE',
206 );
207
208 # it is too dangerous to execute anything else in this state
209 # assume everything works (safer - worst case scenario next statement throws)
210 return 1;
211 }
2aeb3c7f 212 }
213
ab0b0a09 214 # do the actual test and return on no failure
ddcc02d1 215 ( $ping_fail ||= ! dbic_internal_try { $dbh->do('SELECT * FROM sqlite_master LIMIT 1'); 1 } )
ab0b0a09 216 or return 1; # the actual RV of _ping()
217
218 # ping failed (or so it seems) - need to do some cleanup
219 # it is possible to have a proper "connection", and have "ping" return
220 # false anyway (e.g. corrupted file). In such cases DBD::SQLite still
221 # keeps the actual file handle open. We don't really want this to happen,
222 # so force-close the handle via DBI itself
223 #
ddcc02d1 224 dbic_internal_try { $dbh->disconnect }; # if it fails - it fails
ab0b0a09 225 undef; # the actual RV of _ping()
8d1fb3e2 226}
227
2361982d 228sub deployment_statements {
96736321 229 my $self = shift;
2361982d 230 my ($schema, $type, $version, $dir, $sqltargs, @rest) = @_;
231
232 $sqltargs ||= {};
233
96736321 234 if (
235 ! exists $sqltargs->{producer_args}{sqlite_version}
236 and
237 my $dver = $self->_server_info->{normalized_dbms_version}
238 ) {
239 $sqltargs->{producer_args}{sqlite_version} = $dver;
6d766626 240 }
2361982d 241
242 $self->next::method($schema, $type, $version, $dir, $sqltargs, @rest);
243}
244
0e773352 245sub bind_attribute_by_data_type {
04ab4eb1 246
247 # According to http://www.sqlite.org/datatype3.html#storageclasses
248 # all numeric types are dynamically allocated up to 8 bytes per
249 # individual value
250 # Thus it should be safe and non-wasteful to bind everything as
251 # SQL_BIGINT and have SQLite deal with storage/comparisons however
252 # it deems correct
253 $_[1] =~ /^ (?: int(?:[1248]|eger)? | (?:tiny|small|medium|big)int ) $/ix
254 ? DBI::SQL_BIGINT()
0e773352 255 : undef
256 ;
257}
258
04ab4eb1 259# FIXME - what the flying fuck... work around RT#76395
260# DBD::SQLite warns on binding >32 bit values with 32 bit IVs
261sub _dbh_execute {
1363f0f5 262 if (
00882d2c 263 (
264 DBIx::Class::_ENV_::IV_SIZE < 8
265 or
266 DBIx::Class::_ENV_::OS_NAME eq 'MSWin32'
267 )
1363f0f5 268 and
269 ! defined $DBD::SQLite::__DBIC_CHECK_dbd_mishandles_bound_BIGINT
270 ) {
271 $DBD::SQLite::__DBIC_CHECK_dbd_mishandles_bound_BIGINT = (
272 modver_gt_or_eq('DBD::SQLite', '1.37')
273 ) ? 1 : 0;
04ab4eb1 274 }
275
1363f0f5 276 local $SIG{__WARN__} = sigwarn_silencer( qr/
277 \Qdatatype mismatch: bind\E \s (?:
278 param \s+ \( \d+ \) \s+ [-+]? \d+ (?: \. 0*)? \Q as integer\E
279 |
280 \d+ \s type \s @{[ DBI::SQL_BIGINT() ]} \s as \s [-+]? \d+ (?: \. 0*)?
281 )
00882d2c 282 /x ) if (
283 (
284 DBIx::Class::_ENV_::IV_SIZE < 8
285 or
286 DBIx::Class::_ENV_::OS_NAME eq 'MSWin32'
287 )
288 and
289 $DBD::SQLite::__DBIC_CHECK_dbd_mishandles_bound_BIGINT
290 );
1363f0f5 291
04ab4eb1 292 shift->next::method(@_);
293}
294
632d1e0f 295# DBD::SQLite (at least up to version 1.31 has a bug where it will
4a0eed52 296# non-fatally numify a string value bound as an integer, resulting
632d1e0f 297# in insertions of '0' into supposed-to-be-numeric fields
298# Since this can result in severe data inconsistency, remove the
4a0eed52 299# bind attr if such a situation is detected
632d1e0f 300#
301# FIXME - when a DBD::SQLite version is released that eventually fixes
4a0eed52 302# this situation (somehow) - no-op this override once a proper DBD
632d1e0f 303# version is detected
304sub _dbi_attrs_for_bind {
305 my ($self, $ident, $bind) = @_;
75a1d824 306
632d1e0f 307 my $bindattrs = $self->next::method($ident, $bind);
308
04ab4eb1 309 if (! defined $DBD::SQLite::__DBIC_CHECK_dbd_can_bind_bigint_values) {
215102b9 310 $DBD::SQLite::__DBIC_CHECK_dbd_can_bind_bigint_values
311 = modver_gt_or_eq('DBD::SQLite', '1.37') ? 1 : 0;
04ab4eb1 312 }
313
49f7b6c7 314 for my $i (0.. $#$bindattrs) {
632d1e0f 315 if (
49f7b6c7 316 defined $bindattrs->[$i]
632d1e0f 317 and
49f7b6c7 318 defined $bind->[$i][1]
632d1e0f 319 and
d830d9f4 320 grep { $bindattrs->[$i] eq $_ } (
321 DBI::SQL_INTEGER(), DBI::SQL_TINYINT(), DBI::SQL_SMALLINT(), DBI::SQL_BIGINT()
322 )
632d1e0f 323 ) {
04ab4eb1 324 if ( $bind->[$i][1] !~ /^ [\+\-]? [0-9]+ (?: \. 0* )? $/x ) {
325 carp_unique( sprintf (
326 "Non-integer value supplied for column '%s' despite the integer datatype",
327 $bind->[$i][0]{dbic_colname} || "# $i"
328 ) );
329 undef $bindattrs->[$i];
330 }
331 elsif (
332 ! $DBD::SQLite::__DBIC_CHECK_dbd_can_bind_bigint_values
215102b9 333 ) {
04ab4eb1 334 # unsigned 32 bit ints have a range of −2,147,483,648 to 2,147,483,647
335 # alternatively expressed as the hexadecimal numbers below
336 # the comparison math will come out right regardless of ivsize, since
337 # we are operating within 31 bits
338 # P.S. 31 because one bit is lost for the sign
215102b9 339 if ($bind->[$i][1] > 0x7fff_ffff or $bind->[$i][1] < -0x8000_0000) {
340 carp_unique( sprintf (
341 "An integer value occupying more than 32 bits was supplied for column '%s' "
342 . 'which your version of DBD::SQLite (%s) can not bind properly so DBIC '
343 . 'will treat it as a string instead, consider upgrading to at least '
344 . 'DBD::SQLite version 1.37',
345 $bind->[$i][0]{dbic_colname} || "# $i",
346 DBD::SQLite->VERSION,
347 ) );
348 undef $bindattrs->[$i];
349 }
350 else {
351 $bindattrs->[$i] = DBI::SQL_INTEGER()
352 }
04ab4eb1 353 }
632d1e0f 354 }
355 }
356
357 return $bindattrs;
358}
359
732e4282 360=head2 connect_call_use_foreign_keys
361
362Used as:
363
364 on_connect_call => 'use_foreign_keys'
365
8384a713 366In L<connect_info|DBIx::Class::Storage::DBI/connect_info> to turn on foreign key
367(including cascading) support for recent versions of SQLite and L<DBD::SQLite>.
732e4282 368
369Executes:
370
8273e845 371 PRAGMA foreign_keys = ON
732e4282 372
373See L<http://www.sqlite.org/foreignkeys.html> for more information.
374
375=cut
376
377sub connect_call_use_foreign_keys {
378 my $self = shift;
379
380 $self->_do_query(
381 'PRAGMA foreign_keys = ON'
382 );
383}
384
a2bd3796 385=head1 FURTHER QUESTIONS?
843f8ecd 386
a2bd3796 387Check the list of L<additional DBIC resources|DBIx::Class/GETTING HELP/SUPPORT>.
843f8ecd 388
a2bd3796 389=head1 COPYRIGHT AND LICENSE
843f8ecd 390
a2bd3796 391This module is free software L<copyright|DBIx::Class/COPYRIGHT AND LICENSE>
392by the L<DBIx::Class (DBIC) authors|DBIx::Class/AUTHORS>. You can
393redistribute it and/or modify it under the same terms as the
394L<DBIx::Class library|DBIx::Class/COPYRIGHT AND LICENSE>.
843f8ecd 395
396=cut
a2bd3796 397
3981;