Fix spurious ROLLBACK statements when a TxnScopeGuard fails a deferred commit
[dbsrgits/DBIx-Class.git] / t / 72pg.t
1 use DBIx::Class::Optional::Dependencies -skip_all_without => 'test_rdbms_pg';
2
3 use strict;
4 use warnings;
5
6 use Test::More;
7 use Test::Exception;
8 use Test::Warn;
9 use Sub::Name;
10 use Config;
11 use DBIx::Class::Optional::Dependencies ();
12 use lib qw(t/lib);
13 use DBICTest;
14 use SQL::Abstract 'is_literal_value';
15 use DBIx::Class::_Util 'is_exception';
16
17 my ($dsn, $user, $pass) = @ENV{map { "DBICTEST_PG_${_}" } qw/DSN USER PASS/};
18
19 ### load any test classes that are defined further down in the file via BEGIN blocks
20 our @test_classes; #< array that will be pushed into by test classes defined in this file
21 DBICTest::Schema->load_classes( map {s/.+:://;$_} @test_classes ) if @test_classes;
22
23 ###  pre-connect tests (keep each test separate as to make sure rebless() runs)
24   {
25     my $s = DBICTest::Schema->connect($dsn, $user, $pass);
26     # make sure sqlt_type overrides work (::Storage::DBI::Pg does this)
27     ok (!$s->storage->_dbh, 'definitely not connected');
28     is ($s->storage->sqlt_type, 'PostgreSQL', 'sqlt_type correct pre-connection');
29     ok (!$s->storage->_dbh, 'still not connected');
30   }
31
32 # test LIMIT support
33 {
34   my $schema = DBICTest::Schema->connect($dsn, $user, $pass);
35   drop_test_schema($schema);
36   create_test_schema($schema);
37   for (1..6) {
38     $schema->resultset('Artist')->create({ name => 'Artist ' . $_ });
39   }
40   my $it = $schema->resultset('Artist')->search( {},
41     { rows => 3,
42       offset => 2,
43       order_by => 'artistid' }
44   );
45   is( $it->count, 3, "LIMIT count ok" );  # ask for 3 rows out of 6 artists
46   is( $it->next->name, "Artist 3", "iterator->next ok" );
47   $it->next;
48   $it->next;
49   $it->next;
50   is( $it->next, undef, "next past end of resultset ok" );
51
52   # Limit with select-lock
53   lives_ok {
54     $schema->txn_do (sub {
55       isa_ok (
56         $schema->resultset('Artist')->find({artistid => 1}, {for => 'update', rows => 1}),
57         'DBICTest::Schema::Artist',
58       );
59     });
60   } 'Limited FOR UPDATE select works';
61 }
62
63 # check if we indeed do support stuff
64 my $test_server_supports_insert_returning = do {
65
66   my $si = DBICTest::Schema->connect($dsn, $user, $pass)->storage->_server_info;
67   die "Unparseable Pg server version: $si->{dbms_version}\n"
68     unless $si->{normalized_dbms_version};
69
70   $si->{normalized_dbms_version} < 8.002 ? 0 : 1;
71 };
72 is (
73   DBICTest::Schema->connect($dsn, $user, $pass)->storage->_use_insert_returning,
74   $test_server_supports_insert_returning,
75   'insert returning capability guessed correctly'
76 );
77
78 my $schema;
79 for my $use_insert_returning ($test_server_supports_insert_returning
80   ? (0,1)
81   : (0)
82 ) {
83
84   no warnings qw/once redefine/;
85   my $old_connection = DBICTest::Schema->can('connection');
86   local *DBICTest::Schema::connection = subname 'DBICTest::Schema::connection' => sub {
87     my $s = shift->$old_connection(@_);
88     $s->storage->_use_insert_returning ($use_insert_returning);
89     $s;
90   };
91
92 ### test capability override
93   {
94     my $s = DBICTest::Schema->connect($dsn, $user, $pass);
95
96     ok (!$s->storage->_dbh, 'definitely not connected');
97
98     ok (
99       ! ($s->storage->_use_insert_returning xor $use_insert_returning),
100       'insert returning capability set correctly',
101     );
102     ok (!$s->storage->_dbh, 'still not connected (capability override works)');
103   }
104
105 ### connect, create postgres-specific test schema
106
107   $schema = DBICTest::Schema->connect($dsn, $user, $pass);
108   $schema->storage->ensure_connected;
109
110   drop_test_schema($schema);
111   create_test_schema($schema);
112
113 ### begin main tests
114
115 # run a BIG bunch of tests for last-insert-id / Auto-PK / sequence
116 # discovery
117   run_apk_tests($schema); #< older set of auto-pk tests
118   run_extended_apk_tests($schema); #< new extended set of auto-pk tests
119
120
121 ######## test the pg-specific syntax from https://rt.cpan.org/Ticket/Display.html?id=99503
122   lives_ok {
123     is(
124       $schema->resultset('Artist')->search({ artistid => { -in => \ '(select 4) union (select 5)' } })->count,
125       2,
126       'Two expected artists found on subselect union within IN',
127     );
128   };
129
130 ### type_info tests
131
132   my $test_type_info = {
133       'artistid' => {
134           'data_type' => 'integer',
135           'is_nullable' => 0,
136           'size' => 4,
137       },
138       'name' => {
139           'data_type' => 'character varying',
140           'is_nullable' => 1,
141           'size' => 100,
142           'default_value' => undef,
143       },
144       'rank' => {
145           'data_type' => 'integer',
146           'is_nullable' => 0,
147           'size' => 4,
148           'default_value' => 13,
149
150       },
151       'charfield' => {
152           'data_type' => 'character',
153           'is_nullable' => 1,
154           'size' => 10,
155           'default_value' => undef,
156       },
157       'arrayfield' => {
158           'data_type' => 'integer[]',
159           'is_nullable' => 1,
160           'size' => undef,
161           'default_value' => undef,
162       },
163   };
164
165   my $type_info = $schema->storage->columns_info_for('dbic_t_schema.artist');
166   my $artistid_defval = delete $type_info->{artistid}->{default_value};
167
168   # The curor info is too radically different from what is in the column_info
169   # call - just punt it (DBD::SQLite tests the codepath plenty enough)
170   unless (DBIx::Class::_ENV_::STRESSTEST_COLUMN_INFO_UNAWARE_STORAGE) {
171     like(
172       $artistid_defval,
173       qr/^nextval\('([^\.]*\.){0,1}artist_artistid_seq'::(?:text|regclass)\)/,
174       'columns_info_for - sequence matches Pg get_autoinc_seq expectations'
175     );
176
177     is_deeply($type_info, $test_type_info,
178             'columns_info_for - column data types');
179   }
180
181 ####### Array tests
182
183   BEGIN {
184     package DBICTest::Schema::ArrayTest;
185     push @main::test_classes, __PACKAGE__;
186
187     use strict;
188     use warnings;
189     use base 'DBICTest::BaseResult';
190
191     __PACKAGE__->table('dbic_t_schema.array_test');
192     __PACKAGE__->add_columns(qw/id arrayfield/);
193     __PACKAGE__->column_info_from_storage(1);
194     __PACKAGE__->set_primary_key('id');
195
196   }
197   SKIP: {
198     skip "Need DBD::Pg 2.9.2 or newer for array tests", 4 if $DBD::Pg::VERSION < 2.009002;
199
200     my $arr_rs = $schema->resultset('ArrayTest');
201
202     lives_ok {
203       $arr_rs->create({
204         arrayfield => [1, 2],
205       });
206     } 'inserting arrayref as pg array data';
207
208     lives_ok {
209       $arr_rs->update({
210         arrayfield => [3, 4],
211       });
212     } 'updating arrayref as pg array data';
213
214     $arr_rs->create({
215       arrayfield => [5, 6],
216     });
217
218     lives_ok {
219       $schema->populate('ArrayTest', [
220         [ qw/arrayfield/ ],
221         [ [0,0]          ],
222       ]);
223     } 'inserting arrayref using void ctx populate';
224
225     # Search using arrays
226     lives_ok {
227       is_deeply (
228         $arr_rs->search({ arrayfield => { -value => [3,4] } })->first->arrayfield,
229         [3,4],
230         'Array value matches'
231       );
232     } 'searching by arrayref';
233
234     lives_ok {
235       is_deeply (
236         $arr_rs->search({ arrayfield => { '=' => { -value => [3,4] }} })->first->arrayfield,
237         [3,4],
238         'Array value matches explicit equal'
239       );
240     } 'searching by arrayref (explicit equal sign)';
241
242     lives_ok {
243       is_deeply (
244         $arr_rs->search({ arrayfield => { '>' => { -value => [3,1] }} })->first->arrayfield,
245         [3,4],
246         'Array value matches greater than'
247       );
248     } 'searching by arrayref (greater than)';
249
250     lives_ok {
251       is (
252         $arr_rs->search({ arrayfield => { '>' => { -value => [3,7] }} })->count,
253         1,
254         'Greater than search found [5,6]',
255       );
256     } 'searching by arrayref (greater than)';
257
258     # Find using arrays
259     lives_ok {
260       is_deeply (
261         $arr_rs->find({ arrayfield => { -value => [3,4] } })->arrayfield,
262         [3,4],
263         'Array value matches implicit equal'
264       );
265     } 'find by arrayref';
266
267     lives_ok {
268       is_deeply (
269         $arr_rs->find({ arrayfield => { '=' => { -value => [3,4] }} })->arrayfield,
270         [3,4],
271         'Array value matches explicit equal'
272       );
273     } 'find by arrayref (equal)';
274
275     # test inferred condition for creation
276     for my $cond (
277       { -value => [3,4] },
278       \[ '= ?' => [3, 4] ],
279     ) {
280       local $TODO = 'No introspection of complex literal conditions :('
281         if is_literal_value $cond;
282
283
284       my $arr_rs_cond = $arr_rs->search({ arrayfield => $cond });
285
286       my $row = $arr_rs_cond->create({});
287       is_deeply ($row->arrayfield, [3,4], 'Array value taken from $rs condition');
288       $row->discard_changes;
289       is_deeply ($row->arrayfield, [3,4], 'Array value made it to storage');
290     }
291
292     my $arr = [ 1..10 ];
293     # exercise the creation-logic even more (akin to t/100populate.t)
294     for my $insert_value (
295       $arr,
296       { -value => $arr },
297       \[ '?', $arr ],
298     ) {
299       $arr_rs->delete;
300
301       my @objs = (
302         $arr_rs->create({ arrayfield => $insert_value }),
303         $arr_rs->populate([ { arrayfield => $insert_value } ]),
304         $arr_rs->populate([ ['arrayfield'], [ $insert_value ] ]),
305       );
306
307       my $loose_obj = $arr_rs->new({ arrayfield => $insert_value });
308
309       unless (is_literal_value $insert_value) {
310         is_deeply( $_->arrayfield, $arr, 'array value preserved during set_columns' )
311           for ($loose_obj, @objs)
312       }
313
314       push @objs, $loose_obj->insert;
315
316       $_->discard_changes for @objs;
317       is_deeply( $_->arrayfield, $arr, 'array value correct after discard_changes' )
318         for (@objs);
319
320       # insert couple more in void ctx
321       $arr_rs->populate([ { arrayfield => $insert_value } ]);
322       $arr_rs->populate([ ['arrayfield'], [ $insert_value ] ]);
323
324       # should have a total of 6 now, all pristine
325       my @retrieved_objs = $arr_rs->search({
326         arrayfield => ref $insert_value eq 'ARRAY'
327           ? { -value => $insert_value }
328           : { '=' => $insert_value }
329       })->all;
330       is scalar @retrieved_objs, 6, 'Correct count of inserted rows';
331       is_deeply( $_->arrayfield, $arr, 'array value correct after storage retrieval' )
332         for (@retrieved_objs);
333     }
334   }
335
336 ########## Case check
337
338   BEGIN {
339     package DBICTest::Schema::Casecheck;
340     push @main::test_classes, __PACKAGE__;
341
342     use strict;
343     use warnings;
344     use base 'DBIx::Class::Core';
345
346     __PACKAGE__->table('dbic_t_schema.casecheck');
347     __PACKAGE__->add_columns(qw/id name NAME uc_name/);
348     __PACKAGE__->column_info_from_storage(1);
349     __PACKAGE__->set_primary_key('id');
350   }
351
352   my $name_info = $schema->source('Casecheck')->column_info( 'name' );
353   is( $name_info->{size}, 1, "Case sensitive matching info for 'name'" );
354
355   my $NAME_info = $schema->source('Casecheck')->column_info( 'NAME' );
356   is( $NAME_info->{size}, 2, "Case sensitive matching info for 'NAME'" );
357
358   my $uc_name_info = $schema->source('Casecheck')->column_info( 'uc_name' );
359   is( $uc_name_info->{size}, 3, "Case insensitive matching info for 'uc_name'" );
360
361
362 ## Test ResultSet->update
363 my $artist = $schema->resultset('Artist')->first;
364 my $cds = $artist->cds_unordered->search({
365     year => { '!=' => 2010 }
366 }, { prefetch => 'liner_notes' });
367 lives_ok { $cds->update({ year => '2010' }) } 'Update on prefetched rs';
368
369 ## Test SELECT ... FOR UPDATE
370   SKIP: {
371       skip "Your system does not support unsafe signals (d_sigaction) - unable to run deadlock test", 1
372         unless eval { $Config{d_sigaction} and require POSIX };
373
374       my ($timed_out, $artist2);
375
376       for my $t (
377         {
378           # Make sure that an error was raised, and that the update failed
379           update_lock => 1,
380           test_sub => sub {
381             ok($timed_out, "update from second schema times out");
382             ok($artist2->is_column_changed('name'), "'name' column is still dirty from second schema");
383           },
384         },
385         {
386           # Make sure that an error was NOT raised, and that the update succeeded
387           update_lock => 0,
388           test_sub => sub {
389             ok(! $timed_out, "update from second schema DOES NOT timeout");
390             ok(! $artist2->is_column_changed('name'), "'name' column is NOT dirty from second schema");
391           },
392         },
393       ) {
394         # create a new schema
395         my $schema2 = DBICTest::Schema->connect($dsn, $user, $pass);
396         $schema2->source("Artist")->name("dbic_t_schema.artist");
397
398         $schema->txn_do( sub {
399           my $rs = $schema->resultset('Artist')->search(
400               {
401                   artistid => 1
402               },
403               $t->{update_lock} ? { for => 'update' } : {}
404           );
405           ok ($rs->count, 'Count works');
406
407           my $artist = $rs->next;
408           is($artist->artistid, 1, "select returns artistid = 1");
409
410           $timed_out = 0;
411
412           eval {
413               # can not use %SIG assignment directly - we need sigaction below
414               # localization to a block still works however
415               local $SIG{ALRM};
416
417               POSIX::sigaction( POSIX::SIGALRM() => POSIX::SigAction->new(
418                 sub { die "DBICTestTimeout" },
419               ));
420
421               $artist2 = $schema2->resultset('Artist')->find(1);
422               $artist2->name('fooey');
423
424               # FIXME - this needs to go away in lieu of a non-retrying runner
425               # ( i.e. after solving RT#47005 )
426               local *DBIx::Class::Storage::DBI::_ping = sub { 1 }, DBIx::Class::_ENV_::OLD_MRO && Class::C3->reinitialize()
427                 if DBIx::Class::_Util::modver_gt_or_eq( 'DBD::Pg' => '3.5.0' );
428
429               alarm(1);
430               $artist2->update;
431           };
432
433           alarm(0);
434
435           if (is_exception($@)) {
436             $timed_out = $@ =~ /DBICTestTimeout/
437               or die $@;
438           }
439         });
440
441         $t->{test_sub}->();
442       }
443   }
444
445
446 ######## other older Auto-pk tests
447
448   $schema->source("SequenceTest")->name("dbic_t_schema.sequence_test");
449   for (1..5) {
450       my $st = $schema->resultset('SequenceTest')->create({ name => 'foo' });
451       is($st->pkid1, $_, "Auto-PK for sequence without default: First primary key");
452       is($st->pkid2, $_ + 9, "Auto-PK for sequence without default: Second primary key");
453       is($st->nonpkid, $_ + 19, "Auto-PK for sequence without default: Non-primary key");
454   }
455   my $st = $schema->resultset('SequenceTest')->create({ name => 'foo', pkid1 => 55 });
456   is($st->pkid1, 55, "Auto-PK for sequence without default: First primary key set manually");
457
458
459 ######## test non-serial auto-pk
460
461   if ($schema->storage->_use_insert_returning) {
462     $schema->source('TimestampPrimaryKey')->name('dbic_t_schema.timestamp_primary_key_test');
463     my $row = $schema->resultset('TimestampPrimaryKey')->create({});
464     ok $row->id;
465   }
466
467 ######## test with_deferred_fk_checks
468
469   $schema->source('CD')->name('dbic_t_schema.cd');
470   $schema->source('Track')->name('dbic_t_schema.track');
471   lives_ok {
472     $schema->storage->with_deferred_fk_checks(sub {
473       $schema->resultset('Track')->create({
474         trackid => 999, cd => 999, position => 1, title => 'deferred FK track'
475       });
476       $schema->resultset('CD')->create({
477         artist => 1, cdid => 999, year => '2003', title => 'deferred FK cd'
478       });
479     });
480   } 'with_deferred_fk_checks code survived';
481
482   is eval { $schema->resultset('Track')->find(999)->title }, 'deferred FK track',
483      'code in with_deferred_fk_checks worked';
484
485   throws_ok {
486     $schema->resultset('Track')->create({
487       trackid => 1, cd => 9999, position => 1, title => 'Track1'
488     });
489   } qr/violates foreign key constraint/i, 'with_deferred_fk_checks is off outside of TXN';
490
491   # rerun the same under with_deferred_fk_checks
492   # it is expected to fail, hence the eval
493   # but it also should not warn
494   warnings_like {
495     eval {
496       $schema->storage->with_deferred_fk_checks(sub {
497         $schema->resultset('Track')->create({
498           trackid => 1, cd => 9999, position => 1, title => 'Track1'
499         });
500       } )
501     };
502
503     like $@, qr/violates foreign key constraint/i,
504       "Still expected exception on deferred failure at commit time";
505
506   } [], 'No warnings on deferred rollback';
507 }
508
509 done_testing;
510
511 END {
512     return unless $schema;
513     drop_test_schema($schema);
514     eapk_drop_all($schema);
515     undef $schema;
516 };
517
518
519 ######### SUBROUTINES
520
521 sub create_test_schema {
522     my $schema = shift;
523     $schema->storage->dbh_do(sub {
524       my (undef,$dbh) = @_;
525
526       local $dbh->{Warn} = 0;
527
528       my $std_artist_table = <<EOS;
529 (
530   artistid serial PRIMARY KEY
531   , name VARCHAR(100)
532   , rank INTEGER NOT NULL DEFAULT '13'
533   , charfield CHAR(10)
534   , arrayfield INTEGER[]
535 )
536 EOS
537
538       $dbh->do("CREATE SCHEMA dbic_t_schema");
539       $dbh->do("CREATE TABLE dbic_t_schema.artist $std_artist_table");
540
541       $dbh->do(<<EOS);
542 CREATE TABLE dbic_t_schema.timestamp_primary_key_test (
543   id timestamp default current_timestamp
544 )
545 EOS
546       $dbh->do(<<EOS);
547 CREATE TABLE dbic_t_schema.cd (
548   cdid int PRIMARY KEY,
549   artist int,
550   title varchar(255),
551   year varchar(4),
552   genreid int,
553   single_track int
554 )
555 EOS
556       $dbh->do(<<EOS);
557 CREATE TABLE dbic_t_schema.track (
558   trackid int,
559   cd int REFERENCES dbic_t_schema.cd(cdid) DEFERRABLE,
560   position int,
561   title varchar(255),
562   last_updated_on date,
563   last_updated_at date
564 )
565 EOS
566
567       $dbh->do(<<EOS);
568 CREATE TABLE dbic_t_schema.sequence_test (
569     pkid1 integer
570     , pkid2 integer
571     , nonpkid integer
572     , name VARCHAR(100)
573     , CONSTRAINT pk PRIMARY KEY(pkid1, pkid2)
574 )
575 EOS
576       $dbh->do("CREATE SEQUENCE pkid1_seq START 1 MAXVALUE 999999 MINVALUE 0");
577       $dbh->do("CREATE SEQUENCE pkid2_seq START 10 MAXVALUE 999999 MINVALUE 0");
578       $dbh->do("CREATE SEQUENCE nonpkid_seq START 20 MAXVALUE 999999 MINVALUE 0");
579       $dbh->do(<<EOS);
580 CREATE TABLE dbic_t_schema.casecheck (
581     id serial PRIMARY KEY
582     , "name" VARCHAR(1)
583     , "NAME" VARCHAR(2)
584     , "UC_NAME" VARCHAR(3)
585 )
586 EOS
587       $dbh->do(<<EOS);
588 CREATE TABLE dbic_t_schema.array_test (
589     id serial PRIMARY KEY
590     , arrayfield INTEGER[]
591 )
592 EOS
593       $dbh->do("CREATE SCHEMA dbic_t_schema_2");
594       $dbh->do("CREATE TABLE dbic_t_schema_2.artist $std_artist_table");
595       $dbh->do("CREATE SCHEMA dbic_t_schema_3");
596       $dbh->do("CREATE TABLE dbic_t_schema_3.artist $std_artist_table");
597       $dbh->do('set search_path=dbic_t_schema,public');
598       $dbh->do("CREATE SCHEMA dbic_t_schema_4");
599       $dbh->do("CREATE SCHEMA dbic_t_schema_5");
600       $dbh->do(<<EOS);
601  CREATE TABLE dbic_t_schema_4.artist
602  (
603    artistid integer not null default nextval('artist_artistid_seq'::regclass) PRIMARY KEY
604    , name VARCHAR(100)
605    , rank INTEGER NOT NULL DEFAULT '13'
606    , charfield CHAR(10)
607    , arrayfield INTEGER[]
608  );
609 EOS
610       $dbh->do('set search_path=public,dbic_t_schema,dbic_t_schema_3');
611       $dbh->do('create sequence public.artist_artistid_seq'); #< in the public schema
612       $dbh->do(<<EOS);
613  CREATE TABLE dbic_t_schema_5.artist
614  (
615    artistid integer not null default nextval('public.artist_artistid_seq'::regclass) PRIMARY KEY
616    , name VARCHAR(100)
617    , rank INTEGER NOT NULL DEFAULT '13'
618    , charfield CHAR(10)
619    , arrayfield INTEGER[]
620  );
621 EOS
622       $dbh->do('set search_path=dbic_t_schema,public');
623   });
624 }
625
626
627
628 sub drop_test_schema {
629     my ( $schema, $warn_exceptions ) = @_;
630
631     $schema->storage->dbh_do(sub {
632         my (undef,$dbh) = @_;
633
634         local $dbh->{Warn} = 0;
635
636         for my $stat (
637                       'DROP SCHEMA dbic_t_schema_5 CASCADE',
638                       'DROP SEQUENCE public.artist_artistid_seq CASCADE',
639                       'DROP SCHEMA dbic_t_schema_4 CASCADE',
640                       'DROP SCHEMA dbic_t_schema CASCADE',
641                       'DROP SEQUENCE pkid1_seq CASCADE',
642                       'DROP SEQUENCE pkid2_seq CASCADE',
643                       'DROP SEQUENCE nonpkid_seq CASCADE',
644                       'DROP SCHEMA dbic_t_schema_2 CASCADE',
645                       'DROP SCHEMA dbic_t_schema_3 CASCADE',
646                      ) {
647             eval { $dbh->do ($stat) };
648             diag $@ if $@ && $warn_exceptions;
649         }
650     });
651 }
652
653
654 ###  auto-pk / last_insert_id / sequence discovery
655 sub run_apk_tests {
656     my $schema = shift;
657
658     # This is in Core now, but it's here just to test that it doesn't break
659     $schema->class('Artist')->load_components('PK::Auto');
660     cmp_ok( $schema->resultset('Artist')->count, '==', 0, 'this should start with an empty artist table');
661
662     # test that auto-pk also works with the defined search path by
663     # un-schema-qualifying the table name
664     apk_t_set($schema,'artist');
665
666     my $unq_new;
667     lives_ok {
668         $unq_new = $schema->resultset('Artist')->create({ name => 'baz' });
669     } 'insert into unqualified, shadowed table succeeds';
670
671     is($unq_new && $unq_new->artistid, 1, "and got correct artistid");
672
673     my @test_schemas = ( [qw| dbic_t_schema_2    1  |],
674                          [qw| dbic_t_schema_3    1  |],
675                          [qw| dbic_t_schema_4    2  |],
676                          [qw| dbic_t_schema_5    1  |],
677                        );
678     foreach my $t ( @test_schemas ) {
679         my ($sch_name, $start_num) = @$t;
680         #test with dbic_t_schema_2
681         apk_t_set($schema,"$sch_name.artist");
682         my $another_new;
683         lives_ok {
684             $another_new = $schema->resultset('Artist')->create({ name => 'Tollbooth Willy'});
685             is( $another_new->artistid,$start_num, "got correct artistid for $sch_name")
686                 or diag "USED SEQUENCE: ".($schema->source('Artist')->column_info('artistid')->{sequence} || '<none>');
687         } "$sch_name liid 1 did not die"
688             or diag "USED SEQUENCE: ".($schema->source('Artist')->column_info('artistid')->{sequence} || '<none>');
689         lives_ok {
690             $another_new = $schema->resultset('Artist')->create({ name => 'Adam Sandler'});
691             is( $another_new->artistid,$start_num+1, "got correct artistid for $sch_name")
692                 or diag "USED SEQUENCE: ".($schema->source('Artist')->column_info('artistid')->{sequence} || '<none>');
693         } "$sch_name liid 2 did not die"
694             or diag "USED SEQUENCE: ".($schema->source('Artist')->column_info('artistid')->{sequence} || '<none>');
695
696     }
697
698     lives_ok {
699         apk_t_set($schema,'dbic_t_schema.artist');
700         my $new = $schema->resultset('Artist')->create({ name => 'foo' });
701         is($new->artistid, 4, "Auto-PK worked");
702         $new = $schema->resultset('Artist')->create({ name => 'bar' });
703         is($new->artistid, 5, "Auto-PK worked");
704     } 'old auto-pk tests did not die either';
705 }
706
707 # sets the artist table name and clears sequence name cache
708 sub apk_t_set {
709     my ( $s, $n ) = @_;
710     $s->source("Artist")->name($n);
711     $s->source('Artist')->column_info('artistid')->{sequence} = undef; #< clear sequence name cache
712 }
713
714
715 ######## EXTENDED AUTO-PK TESTS
716
717 my @eapk_id_columns;
718 BEGIN {
719   package DBICTest::Schema::ExtAPK;
720   push @main::test_classes, __PACKAGE__;
721
722   use strict;
723   use warnings;
724   use base 'DBIx::Class::Core';
725
726   __PACKAGE__->table('apk');
727
728   @eapk_id_columns = qw( id1 id2 id3 id4 );
729   __PACKAGE__->add_columns(
730     map { $_ => { data_type => 'integer', is_auto_increment => 1 } }
731        @eapk_id_columns
732   );
733
734   __PACKAGE__->set_primary_key('id2'); #< note the SECOND column is
735                                        #the primary key
736 }
737
738 my @eapk_schemas;
739 BEGIN{ @eapk_schemas = map "dbic_apk_$_", 0..5 }
740 my %seqs; #< hash of schema.table.col => currval of its (DBIC) primary key sequence
741
742 sub run_extended_apk_tests {
743   my $schema = shift;
744
745   #save the search path and reset it at the end
746   my $search_path_save = eapk_get_search_path($schema);
747
748   eapk_drop_all($schema);
749   %seqs = ();
750
751   # make the test schemas and sequences
752   $schema->storage->dbh_do(sub {
753     my ( undef, $dbh ) = @_;
754
755     $dbh->do("CREATE SCHEMA $_")
756         for @eapk_schemas;
757
758     $dbh->do("CREATE SEQUENCE $eapk_schemas[5].fooseq");
759     $dbh->do("SELECT setval('$eapk_schemas[5].fooseq',400)");
760     $seqs{"$eapk_schemas[1].apk.id2"} = 400;
761
762     $dbh->do("CREATE SEQUENCE $eapk_schemas[4].fooseq");
763     $dbh->do("SELECT setval('$eapk_schemas[4].fooseq',300)");
764     $seqs{"$eapk_schemas[3].apk.id2"} = 300;
765
766     $dbh->do("CREATE SEQUENCE $eapk_schemas[3].fooseq");
767     $dbh->do("SELECT setval('$eapk_schemas[3].fooseq',200)");
768     $seqs{"$eapk_schemas[4].apk.id2"} = 200;
769
770     $dbh->do("SET search_path = ".join ',', reverse @eapk_schemas );
771   });
772
773   # clear our search_path cache
774   $schema->storage->{_pg_search_path} = undef;
775
776   eapk_create( $schema,
777                with_search_path => [0,1],
778              );
779   eapk_create( $schema,
780                with_search_path => [1,0,'public'],
781                nextval => "$eapk_schemas[5].fooseq",
782              );
783   eapk_create( $schema,
784                with_search_path => ['public',0,1],
785                qualify_table => 2,
786              );
787   eapk_create( $schema,
788                with_search_path => [3,1,0,'public'],
789                nextval => "$eapk_schemas[4].fooseq",
790              );
791   eapk_create( $schema,
792                with_search_path => [3,1,0,'public'],
793                nextval => "$eapk_schemas[3].fooseq",
794                qualify_table => 4,
795              );
796
797   eapk_poke( $schema );
798   eapk_poke( $schema, 0 );
799   eapk_poke( $schema, 2 );
800   eapk_poke( $schema, 4 );
801   eapk_poke( $schema, 1 );
802   eapk_poke( $schema, 0 );
803   eapk_poke( $schema, 1 );
804   eapk_poke( $schema );
805   eapk_poke( $schema, 4 );
806   eapk_poke( $schema, 3 );
807   eapk_poke( $schema, 1 );
808   eapk_poke( $schema, 2 );
809   eapk_poke( $schema, 0 );
810
811   # set our search path back
812   eapk_set_search_path( $schema, @$search_path_save );
813 }
814
815 # do a DBIC create on the apk table in the given schema number (which is an
816 # index of @eapk_schemas)
817
818 sub eapk_poke {
819   my ($s, $schema_num) = @_;
820
821   my $schema_name = defined $schema_num
822       ? $eapk_schemas[$schema_num]
823       : '';
824
825   my $schema_name_actual = $schema_name || eapk_find_visible_schema($s);
826
827   $s->source('ExtAPK')->name($schema_name ? $schema_name.'.apk' : 'apk');
828   #< clear sequence name cache
829   $s->source('ExtAPK')->column_info($_)->{sequence} = undef
830       for @eapk_id_columns;
831
832   no warnings 'uninitialized';
833   lives_ok {
834     my $new;
835     for my $inc (1,2,3) {
836       $new = $schema->resultset('ExtAPK')->create({ id1 => 1});
837       my $proper_seqval = ++$seqs{"$schema_name_actual.apk.id2"};
838       is( $new->id2, $proper_seqval, "$schema_name_actual.apk.id2 correct inc $inc" )
839           or eapk_seq_diag($s,$schema_name);
840       $new->discard_changes;
841       is( $new->id1, 1 );
842       for my $id ('id3','id4') {
843         my $proper_seqval = ++$seqs{"$schema_name_actual.apk.$id"};
844         is( $new->$id, $proper_seqval, "$schema_name_actual.apk.$id correct inc $inc" )
845             or eapk_seq_diag($s,$schema_name);
846       }
847     }
848   } "create in schema '$schema_name' lives"
849       or eapk_seq_diag($s,$schema_name);
850 }
851
852 # print diagnostic info on which sequences were found in the ExtAPK
853 # class
854 sub eapk_seq_diag {
855     my $s = shift;
856     my $schema = shift || eapk_find_visible_schema($s);
857
858     diag "$schema.apk sequences: ",
859         join(', ',
860              map "$_:".($s->source('ExtAPK')->column_info($_)->{sequence} || '<none>'),
861              @eapk_id_columns
862             );
863 }
864
865 # get the postgres search path as an arrayref
866 sub eapk_get_search_path {
867     my ( $s ) = @_;
868     # cache the search path as ['schema','schema',...] in the storage
869     # obj
870
871     return $s->storage->dbh_do(sub {
872         my (undef, $dbh) = @_;
873         my @search_path;
874         my ($sp_string) = $dbh->selectrow_array('SHOW search_path');
875         while ( $sp_string =~ s/("[^"]+"|[^,]+),?// ) {
876             unless( defined $1 and length $1 ) {
877                 die "search path sanity check failed: '$1'";
878             }
879             push @search_path, $1;
880         }
881         \@search_path
882     });
883 }
884 sub eapk_set_search_path {
885     my ($s,@sp) = @_;
886     my $sp = join ',',@sp;
887     $s->storage->dbh_do( sub { $_[1]->do("SET search_path = $sp") } );
888 }
889
890 # create the apk table in the given schema, can set whether the table name is qualified, what the nextval is for the second ID
891 sub eapk_create {
892     my ($schema, %a) = @_;
893
894     $schema->storage->dbh_do(sub {
895         my (undef,$dbh) = @_;
896
897         my $searchpath_save;
898         if ( $a{with_search_path} ) {
899             ($searchpath_save) = $dbh->selectrow_array('SHOW search_path');
900
901             my $search_path = join ',',map {/\D/ ? $_ : $eapk_schemas[$_]} @{$a{with_search_path}};
902
903             $dbh->do("SET search_path = $search_path");
904         }
905
906         my $table_name = $a{qualify_table}
907             ? ($eapk_schemas[$a{qualify_table}] || die). ".apk"
908             : 'apk';
909         local $_[1]->{Warn} = 0;
910
911         my $id_def = $a{nextval}
912             ? "integer not null default nextval('$a{nextval}'::regclass)"
913             : 'serial';
914         $dbh->do(<<EOS);
915 CREATE TABLE $table_name (
916   id1 serial
917   , id2 $id_def
918   , id3 serial primary key
919   , id4 serial
920 )
921 EOS
922
923         if( $searchpath_save ) {
924             $dbh->do("SET search_path = $searchpath_save");
925         }
926     });
927 }
928
929 sub eapk_drop_all {
930     my ( $schema, $warn_exceptions ) = @_;
931
932     $schema->storage->dbh_do(sub {
933         my (undef,$dbh) = @_;
934
935         local $dbh->{Warn} = 0;
936
937         # drop the test schemas
938         for (@eapk_schemas ) {
939             eval{ $dbh->do("DROP SCHEMA $_ CASCADE") };
940             diag $@ if $@ && $warn_exceptions;
941         }
942
943
944     });
945 }
946
947 sub eapk_find_visible_schema {
948     my ($s) = @_;
949
950     my ($schema) =
951         $s->storage->dbh_do(sub {
952             $_[1]->selectrow_array(<<EOS);
953 SELECT n.nspname
954 FROM pg_catalog.pg_namespace n
955 JOIN pg_catalog.pg_class c ON c.relnamespace = n.oid
956 WHERE c.relname = 'apk'
957   AND pg_catalog.pg_table_is_visible(c.oid)
958 EOS
959         });
960     return $schema;
961 }