The complete fix for intermittent t/750firebird.t failures (RT#110979)
[dbsrgits/DBIx-Class.git] / t / 750firebird.t
1 use strict;
2 use warnings;
3
4 use Test::More;
5 use Test::Exception;
6 use DBIx::Class::Optional::Dependencies ();
7 use Scope::Guard ();
8 use Try::Tiny;
9 use lib qw(t/lib);
10 use DBICTest;
11
12 my $env2optdep = {
13   DBICTEST_FIREBIRD => 'test_rdbms_firebird',
14   DBICTEST_FIREBIRD_INTERBASE => 'test_rdbms_firebird_interbase',
15   DBICTEST_FIREBIRD_ODBC => 'test_rdbms_firebird_odbc',
16 };
17
18 plan skip_all => join (' ',
19   'Set $ENV{DBICTEST_FIREBIRD_DSN} and/or $ENV{DBICTEST_FIREBIRD_INTERBASE_DSN}',
20   'and/or $ENV{DBICTEST_FIREBIRD_ODBC_DSN},',
21   '_USER and _PASS to run these tests.',
22
23   'WARNING: this test creates and drops the tables "artist", "bindtype_test" and',
24   '"sequence_test"; the generators "gen_artist_artistid", "pkid1_seq", "pkid2_seq"',
25   'and "nonpkid_seq" and the trigger "artist_bi".',
26 ) unless grep { $ENV{"${_}_DSN"} } keys %$env2optdep;
27
28 # tests stolen from 749sybase_asa.t
29
30 # Example DSNs:
31 # dbi:Firebird:db=/var/lib/firebird/2.5/data/hlaghdb.fdb
32 # dbi:InterBase:db=/var/lib/firebird/2.5/data/hlaghdb.fdb
33
34 # Example ODBC DSN:
35 # dbi:ODBC:Driver=Firebird;Dbname=/var/lib/firebird/2.5/data/hlaghdb.fdb
36
37 my $schema;
38
39 my @test_order = map { "DBICTEST_FIREBIRD$_" }
40   DBICTest::RunMode->is_plain
41     ? ('', '_INTERBASE', '_ODBC')   # Least likely to fail
42     : ('_ODBC', '_INTERBASE' , ''); # Most likely to fail
43
44 for my $prefix (@test_order) { SKIP: {
45
46   skip ("Testing with ${prefix}_DSN needs " . DBIx::Class::Optional::Dependencies->req_missing_for( $env2optdep->{$prefix} ), 1)
47     unless  DBIx::Class::Optional::Dependencies->req_ok_for($env2optdep->{$prefix});
48
49   skip ("DBD::InterBase crashes if Firebird or ODBC are also loaded", 1)
50     if $prefix eq 'DBICTEST_FIREBIRD_INTERBASE' and
51       ($ENV{DBICTEST_FIREBIRD_DSN} or $ENV{DBICTEST_FIREBIRD_ODBC_DSN});
52
53   my ($dsn, $user, $pass) = map { $ENV{"${prefix}_$_"} } qw/DSN USER PASS/;
54
55   note "Testing with ${prefix}_DSN";
56
57   $schema = DBICTest::Schema->connect($dsn, $user, $pass, {
58     auto_savepoint  => 1,
59     quote_names     => 1,
60     ($dsn !~ /ODBC/ ? (on_connect_call => 'use_softcommit') : ()),
61   });
62   my $dbh = $schema->storage->dbh;
63
64   my $sg = Scope::Guard->new(sub { cleanup($schema) });
65
66   eval { $dbh->do(q[DROP TABLE "artist"]) };
67   $dbh->do(<<EOF);
68   CREATE TABLE "artist" (
69     "artistid" INT PRIMARY KEY,
70     "name" VARCHAR(255),
71     "charfield" CHAR(10),
72     "rank" INT DEFAULT 13
73   )
74 EOF
75   eval { $dbh->do(q[DROP GENERATOR "gen_artist_artistid"]) };
76   $dbh->do('CREATE GENERATOR "gen_artist_artistid"');
77   eval { $dbh->do('DROP TRIGGER "artist_bi"') };
78   $dbh->do(<<EOF);
79   CREATE TRIGGER "artist_bi" FOR "artist"
80   ACTIVE BEFORE INSERT POSITION 0
81   AS
82   BEGIN
83    IF (NEW."artistid" IS NULL) THEN
84     NEW."artistid" = GEN_ID("gen_artist_artistid",1);
85   END
86 EOF
87   eval { $dbh->do('DROP TABLE "sequence_test"') };
88   $dbh->do(<<EOF);
89   CREATE TABLE "sequence_test" (
90     "pkid1" INT NOT NULL,
91     "pkid2" INT NOT NULL,
92     "nonpkid" INT,
93     "name" VARCHAR(255)
94   )
95 EOF
96   $dbh->do('ALTER TABLE "sequence_test" ADD CONSTRAINT "sequence_test_constraint" PRIMARY KEY ("pkid1", "pkid2")');
97   eval { $dbh->do('DROP GENERATOR "pkid1_seq"') };
98   eval { $dbh->do('DROP GENERATOR pkid2_seq') };
99   eval { $dbh->do('DROP GENERATOR "nonpkid_seq"') };
100   $dbh->do('CREATE GENERATOR "pkid1_seq"');
101   $dbh->do('CREATE GENERATOR pkid2_seq');
102   $dbh->do('SET GENERATOR pkid2_seq TO 9');
103   $dbh->do('CREATE GENERATOR "nonpkid_seq"');
104   $dbh->do('SET GENERATOR "nonpkid_seq" TO 19');
105
106   my $ars = $schema->resultset('Artist');
107   is ( $ars->count, 0, 'No rows at first' );
108
109 # test primary key handling
110   my $new = $ars->create({ name => 'foo' });
111   ok($new->artistid, "Auto-PK worked");
112
113 # test auto increment using generators WITHOUT triggers
114   for (1..5) {
115       my $st = $schema->resultset('SequenceTest')->create({ name => 'foo' });
116       is($st->pkid1, $_, "Firebird Auto-PK without trigger: First primary key");
117       is($st->pkid2, $_ + 9, "Firebird Auto-PK without trigger: Second primary key");
118       is($st->nonpkid, $_ + 19, "Firebird Auto-PK without trigger: Non-primary key");
119   }
120   my $st = $schema->resultset('SequenceTest')->create({ name => 'foo', pkid1 => 55 });
121   is($st->pkid1, 55, "Firebird Auto-PK without trigger: First primary key set manually");
122
123 # test transaction commit
124   $schema->txn_do(sub {
125     $ars->create({ name => 'in_transaction' });
126   });
127   ok (($ars->search({ name => 'in_transaction' })->first),
128     'transaction committed');
129   is $schema->storage->_dbh->{AutoCommit}, 1,
130     '$dbh->{AutoCommit} is correct after transaction commit';
131
132   $ars->search({ name => 'in_transaction' })->delete;
133
134 # test savepoints
135   throws_ok {
136     $schema->txn_do(sub {
137       my ($schema, $ars) = @_;
138       eval {
139         $schema->txn_do(sub {
140           $ars->create({ name => 'in_savepoint' });
141           die "rolling back savepoint";
142         });
143       };
144       ok ((not $ars->search({ name => 'in_savepoint' })->first),
145         'savepoint rolled back');
146       $ars->create({ name => 'in_outer_txn' });
147       die "rolling back outer txn";
148     }, $schema, $ars);
149   } qr/rolling back outer txn/,
150     'correct exception for rollback';
151
152   is $schema->storage->_dbh->{AutoCommit}, 1,
153     '$dbh->{AutoCommit} is correct after transaction rollback';
154
155   ok ((not $ars->search({ name => 'in_outer_txn' })->first),
156     'outer txn rolled back');
157
158 # test explicit key spec
159   $new = $ars->create ({ name => 'bar', artistid => 66 });
160   is($new->artistid, 66, 'Explicit PK worked');
161   $new->discard_changes;
162   is($new->artistid, 66, 'Explicit PK assigned');
163
164 # row update
165   lives_ok {
166     $new->update({ name => 'baz' })
167   } 'update survived';
168   $new->discard_changes;
169   is $new->name, 'baz', 'row updated';
170
171 # test populate
172   lives_ok (sub {
173     my @pop;
174     for (1..2) {
175       push @pop, { name => "Artist_$_" };
176     }
177     $ars->populate (\@pop);
178   });
179
180 # test populate with explicit key
181   lives_ok (sub {
182     my @pop;
183     for (1..2) {
184       push @pop, { name => "Artist_expkey_$_", artistid => 100 + $_ };
185     }
186     $ars->populate (\@pop);
187   });
188
189 # count what we did so far
190   is ($ars->count, 6, 'Simple count works');
191
192 # test ResultSet UPDATE
193   lives_and {
194     $ars->search({ name => 'foo' })->update({ rank => 4 });
195
196     is eval { $ars->search({ name => 'foo' })->first->rank }, 4;
197   } 'Can update a column';
198
199   my ($updated) = $schema->resultset('Artist')->search({name => 'foo'});
200   is eval { $updated->rank }, 4, 'and the update made it to the database';
201
202 # test LIMIT support
203   my $lim = $ars->search( {},
204     {
205       rows => 3,
206       offset => 4,
207       order_by => 'artistid'
208     }
209   );
210   is( $lim->count, 2, 'ROWS+OFFSET count ok' );
211   is( $lim->all, 2, 'Number of ->all objects matches count' );
212
213 # test iterator
214   $lim->reset;
215   is( eval { $lim->next->artistid }, 101, "iterator->next ok" );
216   is( eval { $lim->next->artistid }, 102, "iterator->next ok" );
217   is( $lim->next, undef, "next past end of resultset ok" );
218
219 # test bug in paging
220   my $paged = $ars->search({ name => { -like => 'Artist%' } }, {
221     page => 1,
222     rows => 2,
223     order_by => 'artistid',
224   });
225
226   my $row;
227   lives_ok {
228     $row = $paged->next;
229   } 'paged query survived';
230
231   is try { $row->artistid }, 5, 'correct row from paged query';
232
233   # DBD bug - if any unfinished statements are present during
234   # DDL manipulation (test blobs below)- a segfault will occur
235   $paged->reset;
236
237 # test nested cursors
238   {
239     my $rs1 = $ars->search({}, { order_by => { -asc  => 'artistid' }});
240
241     my $rs2 = $ars->search({ artistid => $rs1->next->artistid }, {
242       order_by => { -desc => 'artistid' }
243     });
244
245     is $rs2->next->artistid, 1, 'nested cursors';
246   }
247
248 # test empty insert
249   lives_and {
250     my $row = $ars->create({});
251     ok $row->artistid;
252   } 'empty insert works';
253
254 # test inferring the generator from the trigger source and using it with
255 # auto_nextval
256   {
257     local $ars->result_source->column_info('artistid')->{auto_nextval} = 1;
258
259     lives_and {
260       my $row = $ars->create({ name => 'introspecting generator' });
261       ok $row->artistid;
262     } 'inferring generator from trigger source works';
263   }
264
265   # at this point there should be no active statements
266   # (finish() was called everywhere, either explicitly via
267   # reset() or on DESTROY)
268   for (keys %{$schema->storage->dbh->{CachedKids}}) {
269     fail("Unreachable cached statement still active: $_")
270       if $schema->storage->dbh->{CachedKids}{$_}->FETCH('Active');
271   }
272
273 # test blobs (stolen from 73oracle.t)
274   eval { $dbh->do('DROP TABLE "bindtype_test"') };
275   $dbh->do(q[
276   CREATE TABLE "bindtype_test"
277   (
278     "id"     INT PRIMARY KEY,
279     "bytea"  INT,
280     "blob"   BLOB,
281     "clob"   BLOB SUB_TYPE TEXT,
282     "a_memo" INT
283   )
284   ]);
285
286   my %binstr = ( 'small' => join('', map { chr($_) } ( 1 .. 127 )) );
287   $binstr{'large'} = $binstr{'small'} x 1024;
288
289   my $maxloblen = length $binstr{'large'};
290   local $dbh->{'LongReadLen'} = $maxloblen;
291
292   my $rs = $schema->resultset('BindType');
293   my $id = 0;
294
295   foreach my $type (qw( blob clob )) {
296     foreach my $size (qw( small large )) {
297       $id++;
298
299 # turn off horrendous binary DBIC_TRACE output
300       local $schema->storage->{debug} = 0;
301
302       lives_ok { $rs->create( { 'id' => $id, $type => $binstr{$size} } ) }
303       "inserted $size $type without dying";
304
305       my $got = $rs->find($id)->$type;
306
307       my $hexdump = sub { join '', map sprintf('%02X', ord), split //, shift };
308
309       ok($got eq $binstr{$size}, "verified inserted $size $type" )
310         or do {
311             diag "For " . (ref $schema->storage) . "\n";
312             diag "Got blob:\n";
313             diag $hexdump->(substr($got,0,50));
314             diag "Expecting blob:\n";
315             diag $hexdump->(substr($binstr{$size},0,50));
316         };
317     }
318   }
319 }}
320
321 done_testing;
322
323 # clean up our mess
324
325 sub cleanup {
326   my $schema = shift;
327
328   my $dbh;
329   eval {
330     $schema->storage->disconnect; # to avoid object FOO is in use errors
331     $dbh = $schema->storage->dbh;
332   };
333   return unless $dbh;
334
335   eval { $dbh->do('DROP TRIGGER "artist_bi"') };
336   diag $@ if $@;
337
338   foreach my $generator (qw/
339     "gen_artist_artistid"
340     "pkid1_seq"
341     pkid2_seq
342     "nonpkid_seq"
343   /) {
344     eval { $dbh->do(qq{DROP GENERATOR $generator}) };
345     diag $@ if $@;
346   }
347
348   foreach my $table (qw/artist sequence_test/) {
349     eval { $dbh->do(qq[DROP TABLE "$table"]) };
350     diag $@ if $@;
351   }
352
353   eval { $dbh->do(q{DROP TABLE "bindtype_test"}) };
354   diag $@ if $@;
355 }