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