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