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