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