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