10 my ($dsn, $user, $pass) = @ENV{map { "DBICTEST_PG_${_}" } qw/DSN USER PASS/};
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')
21 ### load any test classes that are defined further down in the file via BEGIN blocks
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;
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;
34 for my $use_insert_returning ($test_server_supports_insert_returning
38 no warnings qw/redefine once/;
39 local *DBIx::Class::Storage::DBI::Pg::_supports_insert_returning = sub {
43 ### pre-connect tests (keep each test separate as to make sure rebless() runs)
45 my $s = DBICTest::Schema->connect($dsn, $user, $pass);
47 ok (!$s->storage->_dbh, 'definitely not connected');
49 # Check that datetime_parser returns correctly before we explicitly connect.
51 eval { require DateTime::Format::Pg };
52 skip "DateTime::Format::Pg required", 2 if $@;
54 my $store = ref $s->storage;
55 is($store, 'DBIx::Class::Storage::DBI', 'Started with generic storage');
57 my $parser = $s->storage->datetime_parser;
58 is( $parser, 'DateTime::Format::Pg', 'datetime_parser is as expected');
61 ok (!$s->storage->_dbh, 'still not connected');
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');
71 ### connect, create postgres-specific test schema
73 $schema = DBICTest::Schema->connect($dsn, $user, $pass);
74 $schema->storage->ensure_connected;
76 drop_test_schema($schema);
77 create_test_schema($schema);
81 # run a BIG bunch of tests for last-insert-id / Auto-PK / sequence
83 run_apk_tests($schema); #< older set of auto-pk tests
84 run_extended_apk_tests($schema); #< new extended set of auto-pk tests
88 my $test_type_info = {
90 'data_type' => 'integer',
95 'data_type' => 'character varying',
98 'default_value' => undef,
101 'data_type' => 'integer',
104 'default_value' => 13,
108 'data_type' => 'character',
111 'default_value' => undef,
114 'data_type' => 'integer[]',
117 'default_value' => undef,
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');
135 package DBICTest::Schema::ArrayTest;
136 push @main::test_classes, __PACKAGE__;
140 use base 'DBIx::Class::Core';
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');
149 skip "Need DBD::Pg 2.9.2 or newer for array tests", 4 if $DBD::Pg::VERSION < 2.009002;
152 $schema->resultset('ArrayTest')->create({
153 arrayfield => [1, 2],
155 } 'inserting arrayref as pg array data';
158 $schema->resultset('ArrayTest')->update({
159 arrayfield => [3, 4],
161 } 'updating arrayref as pg array data';
163 $schema->resultset('ArrayTest')->create({
164 arrayfield => [5, 6],
169 $count = $schema->resultset('ArrayTest')->search({
170 arrayfield => \[ '= ?' => [arrayfield => [3, 4]] ], #Todo anything less ugly than this?
172 } 'comparing arrayref to pg array data does not blow up';
173 is($count, 1, 'comparing arrayref to pg array data gives correct result');
178 ########## Case check
181 package DBICTest::Schema::Casecheck;
182 push @main::test_classes, __PACKAGE__;
186 use base 'DBIx::Class::Core';
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');
194 my $name_info = $schema->source('Casecheck')->column_info( 'name' );
195 is( $name_info->{size}, 1, "Case sensitive matching info for 'name'" );
197 my $NAME_info = $schema->source('Casecheck')->column_info( 'NAME' );
198 is( $NAME_info->{size}, 2, "Case sensitive matching info for 'NAME'" );
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'" );
206 ## Test SELECT ... FOR UPDATE
209 if(eval "require Sys::SigAction" && !$@) {
210 Sys::SigAction->import( 'set_sig_handler' );
213 skip "Sys::SigAction is not available", 6;
216 my ($timed_out, $artist2);
220 # Make sure that an error was raised, and that the update failed
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");
228 # Make sure that an error was NOT raised, and that the update succeeded
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");
236 # create a new schema
237 my $schema2 = DBICTest::Schema->connect($dsn, $user, $pass);
238 $schema2->source("Artist")->name("dbic_t_schema.artist");
240 $schema->txn_do( sub {
241 my $rs = $schema->resultset('Artist')->search(
245 $t->{update_lock} ? { for => 'update' } : {}
247 ok ($rs->count, 'Count works');
249 my $artist = $rs->next;
250 is($artist->artistid, 1, "select returns artistid = 1");
254 my $h = set_sig_handler( 'ALRM', sub { die "DBICTestTimeout" } );
256 $artist2 = $schema2->resultset('Artist')->find(1);
257 $artist2->name('fooey');
261 $timed_out = $@ =~ /DBICTestTimeout/;
269 ######## other older Auto-pk tests
271 $schema->source("SequenceTest")->name("dbic_t_schema.sequence_test");
273 my $st = $schema->resultset('SequenceTest')->create({ name => 'foo' });
274 is($st->pkid1, $_, "Auto-PK for sequence without default: First primary key");
275 is($st->pkid2, $_ + 9, "Auto-PK for sequence without default: Second primary key");
276 is($st->nonpkid, $_ + 19, "Auto-PK for sequence without default: Non-primary key");
278 my $st = $schema->resultset('SequenceTest')->create({ name => 'foo', pkid1 => 55 });
279 is($st->pkid1, 55, "Auto-PK for sequence without default: First primary key set manually");
282 ######## test non-serial auto-pk
284 if ($schema->storage->_supports_insert_returning) {
285 $schema->source('TimestampPrimaryKey')->name('dbic_t_schema.timestamp_primary_key_test');
286 my $row = $schema->resultset('TimestampPrimaryKey')->create({});
290 ######## test with_deferred_fk_checks
292 $schema->source('CD')->name('dbic_t_schema.cd');
293 $schema->source('Track')->name('dbic_t_schema.track');
295 $schema->storage->with_deferred_fk_checks(sub {
296 $schema->resultset('Track')->create({
297 trackid => 999, cd => 999, position => 1, title => 'deferred FK track'
299 $schema->resultset('CD')->create({
300 artist => 1, cdid => 999, year => '2003', title => 'deferred FK cd'
303 } 'with_deferred_fk_checks code survived';
305 is eval { $schema->resultset('Track')->find(999)->title }, 'deferred FK track',
306 'code in with_deferred_fk_checks worked';
309 $schema->resultset('Track')->create({
310 trackid => 1, cd => 9999, position => 1, title => 'Track1'
312 } qr/constraint/i, 'with_deferred_fk_checks is off';
318 return unless $schema;
319 drop_test_schema($schema);
320 eapk_drop_all( $schema)
324 ######### SUBROUTINES
326 sub create_test_schema {
328 $schema->storage->dbh_do(sub {
329 my (undef,$dbh) = @_;
331 local $dbh->{Warn} = 0;
333 my $std_artist_table = <<EOS;
335 artistid serial PRIMARY KEY
337 , rank INTEGER NOT NULL DEFAULT '13'
339 , arrayfield INTEGER[]
343 $dbh->do("CREATE SCHEMA dbic_t_schema");
344 $dbh->do("CREATE TABLE dbic_t_schema.artist $std_artist_table");
347 CREATE TABLE dbic_t_schema.timestamp_primary_key_test (
348 id timestamp default current_timestamp
352 CREATE TABLE dbic_t_schema.cd (
353 cdid int PRIMARY KEY,
362 CREATE TABLE dbic_t_schema.track (
364 cd int REFERENCES dbic_t_schema.cd(cdid) DEFERRABLE,
367 last_updated_on date,
368 last_updated_at date,
374 CREATE TABLE dbic_t_schema.sequence_test (
379 , CONSTRAINT pk PRIMARY KEY(pkid1, pkid2)
382 $dbh->do("CREATE SEQUENCE pkid1_seq START 1 MAXVALUE 999999 MINVALUE 0");
383 $dbh->do("CREATE SEQUENCE pkid2_seq START 10 MAXVALUE 999999 MINVALUE 0");
384 $dbh->do("CREATE SEQUENCE nonpkid_seq START 20 MAXVALUE 999999 MINVALUE 0");
386 CREATE TABLE dbic_t_schema.casecheck (
387 id serial PRIMARY KEY
390 , "UC_NAME" VARCHAR(3)
394 CREATE TABLE dbic_t_schema.array_test (
395 id serial PRIMARY KEY
396 , arrayfield INTEGER[]
399 $dbh->do("CREATE SCHEMA dbic_t_schema_2");
400 $dbh->do("CREATE TABLE dbic_t_schema_2.artist $std_artist_table");
401 $dbh->do("CREATE SCHEMA dbic_t_schema_3");
402 $dbh->do("CREATE TABLE dbic_t_schema_3.artist $std_artist_table");
403 $dbh->do('set search_path=dbic_t_schema,public');
404 $dbh->do("CREATE SCHEMA dbic_t_schema_4");
405 $dbh->do("CREATE SCHEMA dbic_t_schema_5");
407 CREATE TABLE dbic_t_schema_4.artist
409 artistid integer not null default nextval('artist_artistid_seq'::regclass) PRIMARY KEY
411 , rank INTEGER NOT NULL DEFAULT '13'
413 , arrayfield INTEGER[]
416 $dbh->do('set search_path=public,dbic_t_schema,dbic_t_schema_3');
417 $dbh->do('create sequence public.artist_artistid_seq'); #< in the public schema
419 CREATE TABLE dbic_t_schema_5.artist
421 artistid integer not null default nextval('public.artist_artistid_seq'::regclass) PRIMARY KEY
423 , rank INTEGER NOT NULL DEFAULT '13'
425 , arrayfield INTEGER[]
428 $dbh->do('set search_path=dbic_t_schema,public');
434 sub drop_test_schema {
435 my ( $schema, $warn_exceptions ) = @_;
437 $schema->storage->dbh_do(sub {
438 my (undef,$dbh) = @_;
440 local $dbh->{Warn} = 0;
443 'DROP SCHEMA dbic_t_schema_5 CASCADE',
444 'DROP SEQUENCE public.artist_artistid_seq',
445 'DROP SCHEMA dbic_t_schema_4 CASCADE',
446 'DROP SCHEMA dbic_t_schema CASCADE',
447 'DROP SEQUENCE pkid1_seq',
448 'DROP SEQUENCE pkid2_seq',
449 'DROP SEQUENCE nonpkid_seq',
450 'DROP SCHEMA dbic_t_schema_2 CASCADE',
451 'DROP SCHEMA dbic_t_schema_3 CASCADE',
453 eval { $dbh->do ($stat) };
454 diag $@ if $@ && $warn_exceptions;
460 ### auto-pk / last_insert_id / sequence discovery
464 # This is in Core now, but it's here just to test that it doesn't break
465 $schema->class('Artist')->load_components('PK::Auto');
466 cmp_ok( $schema->resultset('Artist')->count, '==', 0, 'this should start with an empty artist table');
468 # test that auto-pk also works with the defined search path by
469 # un-schema-qualifying the table name
470 apk_t_set($schema,'artist');
474 $unq_new = $schema->resultset('Artist')->create({ name => 'baz' });
475 } 'insert into unqualified, shadowed table succeeds';
477 is($unq_new && $unq_new->artistid, 1, "and got correct artistid");
479 my @test_schemas = ( [qw| dbic_t_schema_2 1 |],
480 [qw| dbic_t_schema_3 1 |],
481 [qw| dbic_t_schema_4 2 |],
482 [qw| dbic_t_schema_5 1 |],
484 foreach my $t ( @test_schemas ) {
485 my ($sch_name, $start_num) = @$t;
486 #test with dbic_t_schema_2
487 apk_t_set($schema,"$sch_name.artist");
490 $another_new = $schema->resultset('Artist')->create({ name => 'Tollbooth Willy'});
491 is( $another_new->artistid,$start_num, "got correct artistid for $sch_name")
492 or diag "USED SEQUENCE: ".($schema->source('Artist')->column_info('artistid')->{sequence} || '<none>');
493 } "$sch_name liid 1 did not die"
494 or diag "USED SEQUENCE: ".($schema->source('Artist')->column_info('artistid')->{sequence} || '<none>');
496 $another_new = $schema->resultset('Artist')->create({ name => 'Adam Sandler'});
497 is( $another_new->artistid,$start_num+1, "got correct artistid for $sch_name")
498 or diag "USED SEQUENCE: ".($schema->source('Artist')->column_info('artistid')->{sequence} || '<none>');
499 } "$sch_name liid 2 did not die"
500 or diag "USED SEQUENCE: ".($schema->source('Artist')->column_info('artistid')->{sequence} || '<none>');
505 apk_t_set($schema,'dbic_t_schema.artist');
506 my $new = $schema->resultset('Artist')->create({ name => 'foo' });
507 is($new->artistid, 4, "Auto-PK worked");
508 $new = $schema->resultset('Artist')->create({ name => 'bar' });
509 is($new->artistid, 5, "Auto-PK worked");
510 } 'old auto-pk tests did not die either';
513 # sets the artist table name and clears sequence name cache
516 $s->source("Artist")->name($n);
517 $s->source('Artist')->column_info('artistid')->{sequence} = undef; #< clear sequence name cache
521 ######## EXTENDED AUTO-PK TESTS
525 package DBICTest::Schema::ExtAPK;
526 push @main::test_classes, __PACKAGE__;
530 use base 'DBIx::Class::Core';
532 __PACKAGE__->table('apk');
534 @eapk_id_columns = qw( id1 id2 id3 id4 );
535 __PACKAGE__->add_columns(
536 map { $_ => { data_type => 'integer', is_auto_increment => 1 } }
540 __PACKAGE__->set_primary_key('id2'); #< note the SECOND column is
545 BEGIN{ @eapk_schemas = map "dbic_apk_$_", 0..5 }
546 my %seqs; #< hash of schema.table.col => currval of its (DBIC) primary key sequence
548 sub run_extended_apk_tests {
551 #save the search path and reset it at the end
552 my $search_path_save = eapk_get_search_path($schema);
554 eapk_drop_all($schema);
557 # make the test schemas and sequences
558 $schema->storage->dbh_do(sub {
559 my ( undef, $dbh ) = @_;
561 $dbh->do("CREATE SCHEMA $_")
564 $dbh->do("CREATE SEQUENCE $eapk_schemas[5].fooseq");
565 $dbh->do("SELECT setval('$eapk_schemas[5].fooseq',400)");
566 $seqs{"$eapk_schemas[1].apk.id2"} = 400;
568 $dbh->do("CREATE SEQUENCE $eapk_schemas[4].fooseq");
569 $dbh->do("SELECT setval('$eapk_schemas[4].fooseq',300)");
570 $seqs{"$eapk_schemas[3].apk.id2"} = 300;
572 $dbh->do("CREATE SEQUENCE $eapk_schemas[3].fooseq");
573 $dbh->do("SELECT setval('$eapk_schemas[3].fooseq',200)");
574 $seqs{"$eapk_schemas[4].apk.id2"} = 200;
576 $dbh->do("SET search_path = ".join ',', reverse @eapk_schemas );
579 # clear our search_path cache
580 $schema->storage->{_pg_search_path} = undef;
582 eapk_create( $schema,
583 with_search_path => [0,1],
585 eapk_create( $schema,
586 with_search_path => [1,0,'public'],
587 nextval => "$eapk_schemas[5].fooseq",
589 eapk_create( $schema,
590 with_search_path => ['public',0,1],
593 eapk_create( $schema,
594 with_search_path => [3,1,0,'public'],
595 nextval => "$eapk_schemas[4].fooseq",
597 eapk_create( $schema,
598 with_search_path => [3,1,0,'public'],
599 nextval => "$eapk_schemas[3].fooseq",
603 eapk_poke( $schema );
604 eapk_poke( $schema, 0 );
605 eapk_poke( $schema, 2 );
606 eapk_poke( $schema, 4 );
607 eapk_poke( $schema, 1 );
608 eapk_poke( $schema, 0 );
609 eapk_poke( $schema, 1 );
610 eapk_poke( $schema );
611 eapk_poke( $schema, 4 );
612 eapk_poke( $schema, 3 );
613 eapk_poke( $schema, 1 );
614 eapk_poke( $schema, 2 );
615 eapk_poke( $schema, 0 );
617 # set our search path back
618 eapk_set_search_path( $schema, @$search_path_save );
621 # do a DBIC create on the apk table in the given schema number (which is an
622 # index of @eapk_schemas)
625 my ($s, $schema_num) = @_;
627 my $schema_name = defined $schema_num
628 ? $eapk_schemas[$schema_num]
631 my $schema_name_actual = $schema_name || eapk_find_visible_schema($s);
633 $s->source('ExtAPK')->name($schema_name ? $schema_name.'.apk' : 'apk');
634 #< clear sequence name cache
635 $s->source('ExtAPK')->column_info($_)->{sequence} = undef
636 for @eapk_id_columns;
638 no warnings 'uninitialized';
641 for my $inc (1,2,3) {
642 $new = $schema->resultset('ExtAPK')->create({ id1 => 1});
643 my $proper_seqval = ++$seqs{"$schema_name_actual.apk.id2"};
644 is( $new->id2, $proper_seqval, "$schema_name_actual.apk.id2 correct inc $inc" )
645 or eapk_seq_diag($s,$schema_name);
646 $new->discard_changes;
648 for my $id ('id3','id4') {
649 my $proper_seqval = ++$seqs{"$schema_name_actual.apk.$id"};
650 is( $new->$id, $proper_seqval, "$schema_name_actual.apk.$id correct inc $inc" )
651 or eapk_seq_diag($s,$schema_name);
654 } "create in schema '$schema_name' lives"
655 or eapk_seq_diag($s,$schema_name);
658 # print diagnostic info on which sequences were found in the ExtAPK
662 my $schema = shift || eapk_find_visible_schema($s);
664 diag "$schema.apk sequences: ",
666 map "$_:".($s->source('ExtAPK')->column_info($_)->{sequence} || '<none>'),
671 # get the postgres search path as an arrayref
672 sub eapk_get_search_path {
674 # cache the search path as ['schema','schema',...] in the storage
677 return $s->storage->dbh_do(sub {
678 my (undef, $dbh) = @_;
680 my ($sp_string) = $dbh->selectrow_array('SHOW search_path');
681 while ( $sp_string =~ s/("[^"]+"|[^,]+),?// ) {
682 unless( defined $1 and length $1 ) {
683 die "search path sanity check failed: '$1'";
685 push @search_path, $1;
690 sub eapk_set_search_path {
692 my $sp = join ',',@sp;
693 $s->storage->dbh_do( sub { $_[1]->do("SET search_path = $sp") } );
696 # create the apk table in the given schema, can set whether the table name is qualified, what the nextval is for the second ID
698 my ($schema, %a) = @_;
700 $schema->storage->dbh_do(sub {
701 my (undef,$dbh) = @_;
704 if ( $a{with_search_path} ) {
705 ($searchpath_save) = $dbh->selectrow_array('SHOW search_path');
707 my $search_path = join ',',map {/\D/ ? $_ : $eapk_schemas[$_]} @{$a{with_search_path}};
709 $dbh->do("SET search_path = $search_path");
712 my $table_name = $a{qualify_table}
713 ? ($eapk_schemas[$a{qualify_table}] || die). ".apk"
715 local $_[1]->{Warn} = 0;
717 my $id_def = $a{nextval}
718 ? "integer not null default nextval('$a{nextval}'::regclass)"
721 CREATE TABLE $table_name (
724 , id3 serial primary key
729 if( $searchpath_save ) {
730 $dbh->do("SET search_path = $searchpath_save");
736 my ( $schema, $warn_exceptions ) = @_;
738 $schema->storage->dbh_do(sub {
739 my (undef,$dbh) = @_;
741 local $dbh->{Warn} = 0;
743 # drop the test schemas
744 for (@eapk_schemas ) {
745 eval{ $dbh->do("DROP SCHEMA $_ CASCADE") };
746 diag $@ if $@ && $warn_exceptions;
753 sub eapk_find_visible_schema {
757 $s->storage->dbh_do(sub {
758 $_[1]->selectrow_array(<<EOS);
760 FROM pg_catalog.pg_namespace n
761 JOIN pg_catalog.pg_class c ON c.relnamespace = n.oid
762 WHERE c.relname = 'apk'
763 AND pg_catalog.pg_table_is_visible(c.oid)