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