11 my ($dsn, $user, $pass) = @ENV{map { "DBICTEST_PG_${_}" } qw/DSN USER PASS/};
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')
22 ### load any test classes that are defined further down in the file via BEGIN blocks
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;
27 ### pre-connect tests (keep each test separate as to make sure rebless() runs)
29 my $s = DBICTest::Schema->connect($dsn, $user, $pass);
31 ok (!$s->storage->_dbh, 'definitely not connected');
33 # Check that datetime_parser returns correctly before we explicitly connect.
35 eval { require DateTime::Format::Pg };
36 skip "DateTime::Format::Pg required", 2 if $@;
38 my $store = ref $s->storage;
39 is($store, 'DBIx::Class::Storage::DBI', 'Started with generic storage');
41 my $parser = $s->storage->datetime_parser;
42 is( $parser, 'DateTime::Format::Pg', 'datetime_parser is as expected');
45 ok (!$s->storage->_dbh, 'still not connected');
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');
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)
63 or die "Unparseable Pg server version: $v\n";
65 ( sprintf ('%d.%d', $1, $2) >= 8.2 ) ? 1 : 0;
68 DBICTest::Schema->connect($dsn, $user, $pass)->storage->_use_insert_returning,
69 $test_server_supports_insert_returning,
70 'insert returning capability guessed correctly'
74 for my $use_insert_returning ($test_server_supports_insert_returning
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);
86 ### test capability override
88 my $s = DBICTest::Schema->connect($dsn, $user, $pass);
90 ok (!$s->storage->_dbh, 'definitely not connected');
93 ! ($s->storage->_use_insert_returning xor $use_insert_returning),
94 'insert returning capability set correctly',
96 ok (!$s->storage->_dbh, 'still not connected (capability override works)');
99 ### connect, create postgres-specific test schema
101 $schema = DBICTest::Schema->connect($dsn, $user, $pass);
102 $schema->storage->ensure_connected;
104 drop_test_schema($schema);
105 create_test_schema($schema);
109 # run a BIG bunch of tests for last-insert-id / Auto-PK / sequence
111 run_apk_tests($schema); #< older set of auto-pk tests
112 run_extended_apk_tests($schema); #< new extended set of auto-pk tests
116 my $test_type_info = {
118 'data_type' => 'integer',
123 'data_type' => 'character varying',
126 'default_value' => undef,
129 'data_type' => 'integer',
132 'default_value' => 13,
136 'data_type' => 'character',
139 'default_value' => undef,
142 'data_type' => 'integer[]',
145 'default_value' => undef,
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');
163 package DBICTest::Schema::ArrayTest;
164 push @main::test_classes, __PACKAGE__;
168 use base 'DBIx::Class::Core';
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');
177 skip "Need DBD::Pg 2.9.2 or newer for array tests", 4 if $DBD::Pg::VERSION < 2.009002;
180 $schema->resultset('ArrayTest')->create({
181 arrayfield => [1, 2],
183 } 'inserting arrayref as pg array data';
186 $schema->resultset('ArrayTest')->update({
187 arrayfield => [3, 4],
189 } 'updating arrayref as pg array data';
191 $schema->resultset('ArrayTest')->create({
192 arrayfield => [5, 6],
197 $count = $schema->resultset('ArrayTest')->search({
198 arrayfield => \[ '= ?' => [arrayfield => [3, 4]] ], #Todo anything less ugly than this?
200 } 'comparing arrayref to pg array data does not blow up';
201 is($count, 1, 'comparing arrayref to pg array data gives correct result');
206 ########## Case check
209 package DBICTest::Schema::Casecheck;
210 push @main::test_classes, __PACKAGE__;
214 use base 'DBIx::Class::Core';
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');
222 my $name_info = $schema->source('Casecheck')->column_info( 'name' );
223 is( $name_info->{size}, 1, "Case sensitive matching info for 'name'" );
225 my $NAME_info = $schema->source('Casecheck')->column_info( 'NAME' );
226 is( $NAME_info->{size}, 2, "Case sensitive matching info for 'NAME'" );
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'" );
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' });
238 todo_skip 'update resultset with a prefetch over a might_have rel', 1;
239 $cds->update({ year => '2010' });
243 ## Test SELECT ... FOR UPDATE
246 if(eval "require Sys::SigAction" && !$@) {
247 Sys::SigAction->import( 'set_sig_handler' );
250 skip "Sys::SigAction is not available", 6;
253 my ($timed_out, $artist2);
257 # Make sure that an error was raised, and that the update failed
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");
265 # Make sure that an error was NOT raised, and that the update succeeded
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");
273 # create a new schema
274 my $schema2 = DBICTest::Schema->connect($dsn, $user, $pass);
275 $schema2->source("Artist")->name("dbic_t_schema.artist");
277 $schema->txn_do( sub {
278 my $rs = $schema->resultset('Artist')->search(
282 $t->{update_lock} ? { for => 'update' } : {}
284 ok ($rs->count, 'Count works');
286 my $artist = $rs->next;
287 is($artist->artistid, 1, "select returns artistid = 1");
291 my $h = set_sig_handler( 'ALRM', sub { die "DBICTestTimeout" } );
293 $artist2 = $schema2->resultset('Artist')->find(1);
294 $artist2->name('fooey');
298 $timed_out = $@ =~ /DBICTestTimeout/;
306 ######## other older Auto-pk tests
308 $schema->source("SequenceTest")->name("dbic_t_schema.sequence_test");
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");
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");
319 ######## test non-serial auto-pk
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({});
327 ######## test with_deferred_fk_checks
329 $schema->source('CD')->name('dbic_t_schema.cd');
330 $schema->source('Track')->name('dbic_t_schema.track');
332 $schema->storage->with_deferred_fk_checks(sub {
333 $schema->resultset('Track')->create({
334 trackid => 999, cd => 999, position => 1, title => 'deferred FK track'
336 $schema->resultset('CD')->create({
337 artist => 1, cdid => 999, year => '2003', title => 'deferred FK cd'
340 } 'with_deferred_fk_checks code survived';
342 is eval { $schema->resultset('Track')->find(999)->title }, 'deferred FK track',
343 'code in with_deferred_fk_checks worked';
346 $schema->resultset('Track')->create({
347 trackid => 1, cd => 9999, position => 1, title => 'Track1'
349 } qr/constraint/i, 'with_deferred_fk_checks is off';
355 return unless $schema;
356 drop_test_schema($schema);
357 eapk_drop_all( $schema)
361 ######### SUBROUTINES
363 sub create_test_schema {
365 $schema->storage->dbh_do(sub {
366 my (undef,$dbh) = @_;
368 local $dbh->{Warn} = 0;
370 my $std_artist_table = <<EOS;
372 artistid serial PRIMARY KEY
374 , rank INTEGER NOT NULL DEFAULT '13'
376 , arrayfield INTEGER[]
380 $dbh->do("CREATE SCHEMA dbic_t_schema");
381 $dbh->do("CREATE TABLE dbic_t_schema.artist $std_artist_table");
384 CREATE TABLE dbic_t_schema.timestamp_primary_key_test (
385 id timestamp default current_timestamp
389 CREATE TABLE dbic_t_schema.cd (
390 cdid int PRIMARY KEY,
399 CREATE TABLE dbic_t_schema.track (
401 cd int REFERENCES dbic_t_schema.cd(cdid) DEFERRABLE,
404 last_updated_on date,
405 last_updated_at date,
411 CREATE TABLE dbic_t_schema.sequence_test (
416 , CONSTRAINT pk PRIMARY KEY(pkid1, pkid2)
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");
423 CREATE TABLE dbic_t_schema.casecheck (
424 id serial PRIMARY KEY
427 , "UC_NAME" VARCHAR(3)
431 CREATE TABLE dbic_t_schema.array_test (
432 id serial PRIMARY KEY
433 , arrayfield INTEGER[]
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");
444 CREATE TABLE dbic_t_schema_4.artist
446 artistid integer not null default nextval('artist_artistid_seq'::regclass) PRIMARY KEY
448 , rank INTEGER NOT NULL DEFAULT '13'
450 , arrayfield INTEGER[]
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
456 CREATE TABLE dbic_t_schema_5.artist
458 artistid integer not null default nextval('public.artist_artistid_seq'::regclass) PRIMARY KEY
460 , rank INTEGER NOT NULL DEFAULT '13'
462 , arrayfield INTEGER[]
465 $dbh->do('set search_path=dbic_t_schema,public');
471 sub drop_test_schema {
472 my ( $schema, $warn_exceptions ) = @_;
474 $schema->storage->dbh_do(sub {
475 my (undef,$dbh) = @_;
477 local $dbh->{Warn} = 0;
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',
490 eval { $dbh->do ($stat) };
491 diag $@ if $@ && $warn_exceptions;
497 ### auto-pk / last_insert_id / sequence discovery
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');
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');
511 $unq_new = $schema->resultset('Artist')->create({ name => 'baz' });
512 } 'insert into unqualified, shadowed table succeeds';
514 is($unq_new && $unq_new->artistid, 1, "and got correct artistid");
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 |],
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");
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>');
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>');
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';
550 # sets the artist table name and clears sequence name cache
553 $s->source("Artist")->name($n);
554 $s->source('Artist')->column_info('artistid')->{sequence} = undef; #< clear sequence name cache
558 ######## EXTENDED AUTO-PK TESTS
562 package DBICTest::Schema::ExtAPK;
563 push @main::test_classes, __PACKAGE__;
567 use base 'DBIx::Class::Core';
569 __PACKAGE__->table('apk');
571 @eapk_id_columns = qw( id1 id2 id3 id4 );
572 __PACKAGE__->add_columns(
573 map { $_ => { data_type => 'integer', is_auto_increment => 1 } }
577 __PACKAGE__->set_primary_key('id2'); #< note the SECOND column is
582 BEGIN{ @eapk_schemas = map "dbic_apk_$_", 0..5 }
583 my %seqs; #< hash of schema.table.col => currval of its (DBIC) primary key sequence
585 sub run_extended_apk_tests {
588 #save the search path and reset it at the end
589 my $search_path_save = eapk_get_search_path($schema);
591 eapk_drop_all($schema);
594 # make the test schemas and sequences
595 $schema->storage->dbh_do(sub {
596 my ( undef, $dbh ) = @_;
598 $dbh->do("CREATE SCHEMA $_")
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;
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;
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;
613 $dbh->do("SET search_path = ".join ',', reverse @eapk_schemas );
616 # clear our search_path cache
617 $schema->storage->{_pg_search_path} = undef;
619 eapk_create( $schema,
620 with_search_path => [0,1],
622 eapk_create( $schema,
623 with_search_path => [1,0,'public'],
624 nextval => "$eapk_schemas[5].fooseq",
626 eapk_create( $schema,
627 with_search_path => ['public',0,1],
630 eapk_create( $schema,
631 with_search_path => [3,1,0,'public'],
632 nextval => "$eapk_schemas[4].fooseq",
634 eapk_create( $schema,
635 with_search_path => [3,1,0,'public'],
636 nextval => "$eapk_schemas[3].fooseq",
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 );
654 # set our search path back
655 eapk_set_search_path( $schema, @$search_path_save );
658 # do a DBIC create on the apk table in the given schema number (which is an
659 # index of @eapk_schemas)
662 my ($s, $schema_num) = @_;
664 my $schema_name = defined $schema_num
665 ? $eapk_schemas[$schema_num]
668 my $schema_name_actual = $schema_name || eapk_find_visible_schema($s);
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;
675 no warnings 'uninitialized';
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;
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);
691 } "create in schema '$schema_name' lives"
692 or eapk_seq_diag($s,$schema_name);
695 # print diagnostic info on which sequences were found in the ExtAPK
699 my $schema = shift || eapk_find_visible_schema($s);
701 diag "$schema.apk sequences: ",
703 map "$_:".($s->source('ExtAPK')->column_info($_)->{sequence} || '<none>'),
708 # get the postgres search path as an arrayref
709 sub eapk_get_search_path {
711 # cache the search path as ['schema','schema',...] in the storage
714 return $s->storage->dbh_do(sub {
715 my (undef, $dbh) = @_;
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'";
722 push @search_path, $1;
727 sub eapk_set_search_path {
729 my $sp = join ',',@sp;
730 $s->storage->dbh_do( sub { $_[1]->do("SET search_path = $sp") } );
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
735 my ($schema, %a) = @_;
737 $schema->storage->dbh_do(sub {
738 my (undef,$dbh) = @_;
741 if ( $a{with_search_path} ) {
742 ($searchpath_save) = $dbh->selectrow_array('SHOW search_path');
744 my $search_path = join ',',map {/\D/ ? $_ : $eapk_schemas[$_]} @{$a{with_search_path}};
746 $dbh->do("SET search_path = $search_path");
749 my $table_name = $a{qualify_table}
750 ? ($eapk_schemas[$a{qualify_table}] || die). ".apk"
752 local $_[1]->{Warn} = 0;
754 my $id_def = $a{nextval}
755 ? "integer not null default nextval('$a{nextval}'::regclass)"
758 CREATE TABLE $table_name (
761 , id3 serial primary key
766 if( $searchpath_save ) {
767 $dbh->do("SET search_path = $searchpath_save");
773 my ( $schema, $warn_exceptions ) = @_;
775 $schema->storage->dbh_do(sub {
776 my (undef,$dbh) = @_;
778 local $dbh->{Warn} = 0;
780 # drop the test schemas
781 for (@eapk_schemas ) {
782 eval{ $dbh->do("DROP SCHEMA $_ CASCADE") };
783 diag $@ if $@ && $warn_exceptions;
790 sub eapk_find_visible_schema {
794 $s->storage->dbh_do(sub {
795 $_[1]->selectrow_array(<<EOS);
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)