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