Fix failures and protect the suite from spurious VERSION-related warnings
[dbsrgits/DBIx-Class.git] / t / 752sqlite.t
1 use strict;
2 use warnings;
3
4 use Test::More;
5 use Test::Exception;
6 use Test::Warn;
7 use Time::HiRes 'time';
8 use Math::BigInt;
9
10 use lib qw(t/lib);
11 use DBICTest;
12 use DBIx::Class::_Util qw( sigwarn_silencer modver_gt_or_eq modver_gt_or_eq_and_lt );
13
14 # make one deploy() round before we load anything else - need this in order
15 # to prime SQLT if we are using it (deep depchain is deep)
16 DBICTest->init_schema( no_populate => 1 );
17
18 # check that we work somewhat OK with braindead SQLite transaction handling
19 #
20 # As per https://metacpan.org/source/ADAMK/DBD-SQLite-1.37/lib/DBD/SQLite.pm#L921
21 # SQLite does *not* try to synchronize
22 #
23 # However DBD::SQLite 1.38_02 seems to fix this, with an accompanying test:
24 # https://metacpan.org/source/ADAMK/DBD-SQLite-1.38_02/t/54_literal_txn.t
25 my $lit_txn_todo = modver_gt_or_eq('DBD::SQLite', '1.38_02')
26   ? undef
27   : "DBD::SQLite before 1.38_02 is retarded wrt detecting literal BEGIN/COMMIT statements"
28 ;
29
30 for my $prefix_comment (qw/Begin_only Commit_only Begin_and_Commit/) {
31   note "Testing with comment prefixes on $prefix_comment";
32
33   # FIXME warning won't help us for the time being
34   # perhaps when (if ever) DBD::SQLite gets fixed,
35   # we can do something extra here
36   local $SIG{__WARN__} = sigwarn_silencer( qr/Internal transaction state .+? does not seem to match/ )
37     if ( $lit_txn_todo && !$ENV{TEST_VERBOSE} );
38
39   my ($c_begin, $c_commit) = map { $prefix_comment =~ $_ ? 1 : 0 } (qr/Begin/, qr/Commit/);
40
41   my $schema = DBICTest->init_schema( no_deploy => 1 );
42   my $ars = $schema->resultset('Artist');
43
44   ok (! $schema->storage->connected, 'No connection yet');
45
46   $schema->storage->dbh->do(<<'DDL');
47 CREATE TABLE artist (
48   artistid INTEGER PRIMARY KEY NOT NULL,
49   name varchar(100),
50   rank integer DEFAULT 13,
51   charfield char(10) NULL
52 );
53 DDL
54
55   my $artist = $ars->create({ name => 'Artist_' . time() });
56   is ($ars->count, 1, 'Inserted artist ' . $artist->name);
57
58   ok ($schema->storage->connected, 'Connected');
59   ok ($schema->storage->_dbh->{AutoCommit}, 'DBD not in txn yet');
60
61   $schema->storage->dbh->do(join "\n",
62     $c_begin ? '-- comment' : (),
63     'BEGIN TRANSACTION'
64   );
65   ok ($schema->storage->connected, 'Still connected');
66   {
67     local $TODO = $lit_txn_todo if $c_begin;
68     ok (! $schema->storage->_dbh->{AutoCommit}, "DBD aware of txn begin with comments on $prefix_comment");
69   }
70
71   $schema->storage->dbh->do(join "\n",
72     $c_commit ? '-- comment' : (),
73     'COMMIT'
74   );
75   ok ($schema->storage->connected, 'Still connected');
76   {
77     local $TODO = $lit_txn_todo if $c_commit and ! $c_begin;
78     ok ($schema->storage->_dbh->{AutoCommit}, "DBD aware txn ended with comments on $prefix_comment");
79   }
80
81   is ($ars->count, 1, 'Inserted artists still there');
82
83   {
84     # this never worked in the 1st place
85     local $TODO = $lit_txn_todo if ! $c_begin and $c_commit;
86
87     # odd argument passing, because such nested crefs leak on 5.8
88     lives_ok {
89       $schema->storage->txn_do (sub {
90         ok ($_[0]->find({ name => $_[1] }), "Artist still where we left it after cycle with comments on $prefix_comment");
91       }, $ars, $artist->name );
92     } "Succesfull transaction with comments on $prefix_comment";
93   }
94 }
95
96 # test blank begin/svp/commit/begin cycle
97 warnings_are {
98   my $schema = DBICTest->init_schema( no_populate => 1 );
99   my $rs = $schema->resultset('Artist');
100   is ($rs->count, 0, 'Start with empty table');
101
102   for my $do_commit (1, 0) {
103     $schema->txn_begin;
104     $schema->svp_begin;
105     $schema->svp_rollback;
106
107     $schema->svp_begin;
108     $schema->svp_rollback;
109
110     $schema->svp_release;
111
112     $schema->svp_begin;
113
114     $schema->txn_rollback;
115
116     $schema->txn_begin;
117     $schema->svp_begin;
118     $schema->svp_rollback;
119
120     $schema->svp_begin;
121     $schema->svp_rollback;
122
123     $schema->svp_release;
124
125     $schema->svp_begin;
126
127     $do_commit ? $schema->txn_commit : $schema->txn_rollback;
128
129     is_deeply $schema->storage->savepoints, [], 'Savepoint names cleared away'
130   }
131
132   $schema->txn_do(sub {
133     ok (1, 'all seems fine');
134   });
135 } [], 'No warnings emitted';
136
137 my $schema = DBICTest->init_schema();
138
139 # make sure the side-effects of RT#67581 do not result in data loss
140 my $row;
141 warnings_exist { $row = $schema->resultset('Artist')->create ({ name => 'alpha rank', rank => 'abc' }) }
142   [qr/Non-integer value supplied for column 'rank' despite the integer datatype/],
143   'proper warning on string insertion into an numeric column'
144 ;
145 $row->discard_changes;
146 is ($row->rank, 'abc', 'proper rank inserted into database');
147
148 # and make sure we do not lose actual bigints
149 SKIP: {
150
151 skip "Not testing bigint handling on known broken DBD::SQLite trial versions", 1
152   if( modver_gt_or_eq('DBD::SQLite', '1.45') and ! modver_gt_or_eq('DBD::SQLite', '1.45_03') );
153
154 {
155   package DBICTest::BigIntArtist;
156   use base 'DBICTest::Schema::Artist';
157   __PACKAGE__->table('artist');
158   __PACKAGE__->add_column(bigint => { data_type => 'bigint' });
159 }
160 $schema->register_class(BigIntArtist => 'DBICTest::BigIntArtist');
161 $schema->storage->dbh_do(sub {
162   $_[1]->do('ALTER TABLE artist ADD COLUMN bigint BIGINT');
163 });
164
165 my $sqlite_broken_bigint = modver_gt_or_eq_and_lt( 'DBD::SQLite', '1.34', '1.37' );
166
167 # 63 bit integer
168 my $many_bits = (Math::BigInt->new(2) ** 62);
169
170 # test upper/lower boundaries for sqlite and some values inbetween
171 # range is -(2**63) .. 2**63 - 1
172 #
173 # Not testing -0 - it seems to overflow to ~0 on some combinations,
174 # thus not triggering the >32 bit guards
175 # interesting read: https://en.wikipedia.org/wiki/Signed_zero#Representations
176 for my $bi ( qw(
177   -2
178   -1
179   0
180   +0
181   1
182   2
183
184   -9223372036854775807
185   -8694837494948124658
186   -6848440844435891639
187   -5664812265578554454
188   -5380388020020483213
189   -2564279463598428141
190   2442753333597784273
191   4790993557925631491
192   6773854980030157393
193   7627910776496326154
194   8297530189347439311
195   9223372036854775806
196   9223372036854775807
197
198   4294967295
199   4294967296
200
201   -4294967296
202   -4294967295
203   -4294967294
204
205   -2147483649
206   -2147483648
207   -2147483647
208   -2147483646
209
210   2147483646
211   2147483647
212 ),
213   # these values cause exceptions even with all workarounds in place on these
214   # fucked DBD::SQLite versions *regardless* of ivsize >.<
215   $sqlite_broken_bigint
216     ? ()
217     : ( '2147483648', '2147483649' )
218   ,
219
220   # with newer compilers ( gcc 4.9+ ) older DBD::SQLite does not
221   # play well with the "Most Negative Number"
222   modver_gt_or_eq( 'DBD::SQLite', '1.33' )
223     ? ( '-9223372036854775808' )
224     : ()
225   ,
226
227 ) {
228   # unsigned 32 bit ints have a range of −2,147,483,648 to 2,147,483,647
229   # alternatively expressed as the hexadecimal numbers below
230   # the comparison math will come out right regardless of ivsize, since
231   # we are operating within 31 bits
232   # P.S. 31 because one bit is lost for the sign
233   my $v_bits = ($bi > 0x7fff_ffff || $bi < -0x8000_0000) ? 64 : 32;
234
235   my $v_desc = sprintf '%s (%d bit signed int)', $bi, $v_bits;
236
237   my @w;
238   local $SIG{__WARN__} = sub {
239     if ($_[0] =~ /datatype mismatch/) {
240       push @w, @_;
241     }
242     elsif ($_[0] =~ /An integer value occupying more than 32 bits was supplied .+ can not bind properly so DBIC will treat it as a string instead/ ) {
243       # do nothing, this warning will pop up here and there depending on
244       # DBD/bitness combination
245       # we don't want to test for it explicitly, we are just interested
246       # in the results matching at the end
247     }
248     else {
249       warn @_;
250     }
251   };
252
253   # some combinations of SQLite 1.35 and older 5.8 faimly is wonky
254   # instead of a warning we get a full exception. Sod it
255   eval {
256     $row = $schema->resultset('BigIntArtist')->create({ bigint => $bi });
257   } or do {
258     fail("Exception on inserting $v_desc: $@") unless $sqlite_broken_bigint;
259     next;
260   };
261
262   # explicitly using eq, to make sure we did not nummify the argument
263   # which can be an issue on 32 bit ivsize
264   cmp_ok ($row->bigint, 'eq', $bi, "value in object correct ($v_desc)");
265
266   $row->discard_changes;
267
268   cmp_ok (
269     $row->bigint,
270
271     # the test will not pass an == if we are running under 32 bit ivsize
272     # use 'eq' on the numified (and possibly "scientificied") returned value
273     (DBIx::Class::_ENV_::IV_SIZE < 8 and $v_bits > 32) ? 'eq' : '==',
274
275     # in 1.37 DBD::SQLite switched to proper losless representation of bigints
276     # regardless of ivize
277     # before this use 'eq' (from above) on the numified (and possibly
278     # "scientificied") returned value
279     (DBIx::Class::_ENV_::IV_SIZE < 8 and ! modver_gt_or_eq('DBD::SQLite', '1.37')) ? $bi+0 : $bi,
280
281     "value in database correct ($v_desc)"
282   );
283
284 # FIXME - temporary smoke-only escape
285 SKIP: {
286   skip 'Potential for false negatives - investigation pending', 1
287     if DBICTest::RunMode->is_plain;
288
289   # check if math works
290   # start by adding/subtracting a 50 bit integer, and then divide by 2 for good measure
291   my ($sqlop, $expect) = $bi < 0
292     ? ( '(bigint + ? )', ($bi + $many_bits) )
293     : ( '(bigint - ? )', ($bi - $many_bits) )
294   ;
295
296   $expect = ($expect + ($expect % 2)) / 2;
297
298   # read https://en.wikipedia.org/wiki/Modulo_operation#Common_pitfalls
299   # and check the tables on the right side of the article for an
300   # enlightening journey on why a mere bigint % 2 won't work
301   $sqlop = "( $sqlop + ( ((bigint % 2)+2)%2 ) ) / 2";
302
303   for my $dtype (undef, \'int', \'bigint') {
304
305     # FIXME - the double-load should not be needed
306     # will fix in the future
307     $row->update({ bigint => $bi });
308     $row->discard_changes;
309     $row->update({ bigint => \[ $sqlop, [ $dtype => $many_bits ] ] });
310     $row->discard_changes;
311
312     # can't use cmp_ok - will not engage the M::BI overload of $many_bits
313     ok (
314       $row->bigint
315
316       ==
317
318       (DBIx::Class::_ENV_::IV_SIZE < 8 and ! modver_gt_or_eq('DBD::SQLite', '1.37')) ? $expect->bstr + 0 : $expect
319     , "simple integer math with@{[ $dtype ? '' : 'out' ]} bindtype in database correct (base $v_desc)")
320       or diag sprintf '%s != %s', $row->bigint, $expect;
321   }
322 # end of fixme
323 }
324
325   is_deeply (\@w, [], "No mismatch warnings on bigint operations ($v_desc)" );
326
327 }}
328
329 done_testing;
330
331 # vim:sts=2 sw=2: