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