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