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