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