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', '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'
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;
28 ### pre-connect tests (keep each test separate as to make sure rebless() runs)
30 my $s = DBICTest::Schema->connect($dsn, $user, $pass);
32 ok (!$s->storage->_dbh, 'definitely not connected');
34 # Check that datetime_parser returns correctly before we explicitly connect.
36 eval { require DateTime::Format::Pg };
37 skip "DateTime::Format::Pg required", 2 if $@;
39 my $store = ref $s->storage;
40 is($store, 'DBIx::Class::Storage::DBI', 'Started with generic storage');
42 my $parser = $s->storage->datetime_parser;
43 is( $parser, 'DateTime::Format::Pg', 'datetime_parser is as expected');
46 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 ### connect, create postgres-specific test schema
58 my $schema = DBICTest::Schema->connect($dsn, $user, $pass);
60 drop_test_schema($schema);
61 create_test_schema($schema);
66 # run a BIG bunch of tests for last-insert-id / Auto-PK / sequence
68 run_apk_tests($schema); #< older set of auto-pk tests
69 run_extended_apk_tests($schema); #< new extended set of auto-pk tests
77 my $test_type_info = {
79 'data_type' => 'integer',
84 'data_type' => 'character varying',
87 'default_value' => undef,
90 'data_type' => 'integer',
93 'default_value' => 13,
97 'data_type' => 'character',
100 'default_value' => undef,
103 'data_type' => 'integer[]',
106 'default_value' => undef,
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');
124 package DBICTest::Schema::ArrayTest;
125 push @main::test_classes, __PACKAGE__;
129 use base 'DBIx::Class::Core';
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');
138 skip "Need DBD::Pg 2.9.2 or newer for array tests", 4 if $DBD::Pg::VERSION < 2.009002;
141 $schema->resultset('ArrayTest')->create({
142 arrayfield => [1, 2],
144 } 'inserting arrayref as pg array data';
147 $schema->resultset('ArrayTest')->update({
148 arrayfield => [3, 4],
150 } 'updating arrayref as pg array data';
152 $schema->resultset('ArrayTest')->create({
153 arrayfield => [5, 6],
158 $count = $schema->resultset('ArrayTest')->search({
159 arrayfield => \[ '= ?' => [arrayfield => [3, 4]] ], #Todo anything less ugly than this?
161 } 'comparing arrayref to pg array data does not blow up';
162 is($count, 1, 'comparing arrayref to pg array data gives correct result');
167 ########## Case check
170 package DBICTest::Schema::Casecheck;
171 push @main::test_classes, __PACKAGE__;
175 use base 'DBIx::Class::Core';
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');
183 my $name_info = $schema->source('Casecheck')->column_info( 'name' );
184 is( $name_info->{size}, 1, "Case sensitive matching info for 'name'" );
186 my $NAME_info = $schema->source('Casecheck')->column_info( 'NAME' );
187 is( $NAME_info->{size}, 2, "Case sensitive matching info for 'NAME'" );
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'" );
195 ## Test SELECT ... FOR UPDATE
198 if(eval "require Sys::SigAction" && !$@) {
199 Sys::SigAction->import( 'set_sig_handler' );
202 skip "Sys::SigAction is not available", 6;
205 my ($timed_out, $artist2);
209 # Make sure that an error was raised, and that the update failed
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");
217 # Make sure that an error was NOT raised, and that the update succeeded
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");
225 # create a new schema
226 my $schema2 = DBICTest::Schema->connect($dsn, $user, $pass);
227 $schema2->source("Artist")->name("dbic_t_schema.artist");
229 $schema->txn_do( sub {
230 my $artist = $schema->resultset('Artist')->search(
234 $t->{update_lock} ? { for => 'update' } : {}
236 is($artist->artistid, 1, "select returns artistid = 1");
240 my $h = set_sig_handler( 'ALRM', sub { die "DBICTestTimeout" } );
242 $artist2 = $schema2->resultset('Artist')->find(1);
243 $artist2->name('fooey');
247 $timed_out = $@ =~ /DBICTestTimeout/;
255 ######## other older Auto-pk tests
257 $schema->source("SequenceTest")->name("dbic_t_schema.sequence_test");
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");
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");
268 ######## test non-integer non-serial auto-pk
270 $schema->source('TimestampPrimaryKey')->name('dbic_t_schema.timestamp_primary_key_test');
271 my $row = $schema->resultset('TimestampPrimaryKey')->create({});
279 return unless $schema;
280 drop_test_schema($schema);
281 eapk_drop_all( $schema)
285 ######### SUBROUTINES
287 sub create_test_schema {
289 $schema->storage->dbh_do(sub {
290 my (undef,$dbh) = @_;
292 local $dbh->{Warn} = 0;
294 my $std_artist_table = <<EOS;
296 artistid serial PRIMARY KEY
298 , rank INTEGER NOT NULL DEFAULT '13'
300 , arrayfield INTEGER[]
304 $dbh->do("CREATE SCHEMA dbic_t_schema");
305 $dbh->do("CREATE TABLE dbic_t_schema.artist $std_artist_table");
308 CREATE TABLE dbic_t_schema.timestamp_primary_key_test (
309 id timestamp default current_timestamp
313 CREATE TABLE dbic_t_schema.sequence_test (
318 , CONSTRAINT pk PRIMARY KEY(pkid1, pkid2)
321 $dbh->do("CREATE SEQUENCE pkid1_seq START 1 MAXVALUE 999999 MINVALUE 0");
322 $dbh->do("CREATE SEQUENCE pkid2_seq START 10 MAXVALUE 999999 MINVALUE 0");
323 $dbh->do("CREATE SEQUENCE nonpkid_seq START 20 MAXVALUE 999999 MINVALUE 0");
325 CREATE TABLE dbic_t_schema.casecheck (
326 id serial PRIMARY KEY
329 , "UC_NAME" VARCHAR(3)
333 CREATE TABLE dbic_t_schema.array_test (
334 id serial PRIMARY KEY
335 , arrayfield INTEGER[]
338 $dbh->do("CREATE SCHEMA dbic_t_schema_2");
339 $dbh->do("CREATE TABLE dbic_t_schema_2.artist $std_artist_table");
340 $dbh->do("CREATE SCHEMA dbic_t_schema_3");
341 $dbh->do("CREATE TABLE dbic_t_schema_3.artist $std_artist_table");
342 $dbh->do('set search_path=dbic_t_schema,public');
343 $dbh->do("CREATE SCHEMA dbic_t_schema_4");
344 $dbh->do("CREATE SCHEMA dbic_t_schema_5");
346 CREATE TABLE dbic_t_schema_4.artist
348 artistid integer not null default nextval('artist_artistid_seq'::regclass) PRIMARY KEY
350 , rank INTEGER NOT NULL DEFAULT '13'
352 , arrayfield INTEGER[]
355 $dbh->do('set search_path=public,dbic_t_schema,dbic_t_schema_3');
356 $dbh->do('create sequence public.artist_artistid_seq'); #< in the public schema
358 CREATE TABLE dbic_t_schema_5.artist
360 artistid integer not null default nextval('public.artist_artistid_seq'::regclass) PRIMARY KEY
362 , rank INTEGER NOT NULL DEFAULT '13'
364 , arrayfield INTEGER[]
367 $dbh->do('set search_path=dbic_t_schema,public');
373 sub drop_test_schema {
374 my ( $schema, $warn_exceptions ) = @_;
376 $schema->storage->dbh_do(sub {
377 my (undef,$dbh) = @_;
379 local $dbh->{Warn} = 0;
382 'DROP SCHEMA dbic_t_schema_5 CASCADE',
383 'DROP SEQUENCE public.artist_artistid_seq',
384 'DROP SCHEMA dbic_t_schema_4 CASCADE',
385 'DROP SCHEMA dbic_t_schema CASCADE',
386 'DROP SEQUENCE pkid1_seq',
387 'DROP SEQUENCE pkid2_seq',
388 'DROP SEQUENCE nonpkid_seq',
389 'DROP SCHEMA dbic_t_schema_2 CASCADE',
390 'DROP SCHEMA dbic_t_schema_3 CASCADE',
392 eval { $dbh->do ($stat) };
393 diag $@ if $@ && $warn_exceptions;
399 ### auto-pk / last_insert_id / sequence discovery
403 # This is in Core now, but it's here just to test that it doesn't break
404 $schema->class('Artist')->load_components('PK::Auto');
405 cmp_ok( $schema->resultset('Artist')->count, '==', 0, 'this should start with an empty artist table');
407 # test that auto-pk also works with the defined search path by
408 # un-schema-qualifying the table name
409 apk_t_set($schema,'artist');
413 $unq_new = $schema->resultset('Artist')->create({ name => 'baz' });
414 } 'insert into unqualified, shadowed table succeeds';
416 is($unq_new && $unq_new->artistid, 1, "and got correct artistid");
418 my @test_schemas = ( [qw| dbic_t_schema_2 1 |],
419 [qw| dbic_t_schema_3 1 |],
420 [qw| dbic_t_schema_4 2 |],
421 [qw| dbic_t_schema_5 1 |],
423 foreach my $t ( @test_schemas ) {
424 my ($sch_name, $start_num) = @$t;
425 #test with dbic_t_schema_2
426 apk_t_set($schema,"$sch_name.artist");
429 $another_new = $schema->resultset('Artist')->create({ name => 'Tollbooth Willy'});
430 is( $another_new->artistid,$start_num, "got correct artistid for $sch_name")
431 or diag "USED SEQUENCE: ".($schema->source('Artist')->column_info('artistid')->{sequence} || '<none>');
432 } "$sch_name liid 1 did not die"
433 or diag "USED SEQUENCE: ".($schema->source('Artist')->column_info('artistid')->{sequence} || '<none>');
435 $another_new = $schema->resultset('Artist')->create({ name => 'Adam Sandler'});
436 is( $another_new->artistid,$start_num+1, "got correct artistid for $sch_name")
437 or diag "USED SEQUENCE: ".($schema->source('Artist')->column_info('artistid')->{sequence} || '<none>');
438 } "$sch_name liid 2 did not die"
439 or diag "USED SEQUENCE: ".($schema->source('Artist')->column_info('artistid')->{sequence} || '<none>');
444 apk_t_set($schema,'dbic_t_schema.artist');
445 my $new = $schema->resultset('Artist')->create({ name => 'foo' });
446 is($new->artistid, 4, "Auto-PK worked");
447 $new = $schema->resultset('Artist')->create({ name => 'bar' });
448 is($new->artistid, 5, "Auto-PK worked");
449 } 'old auto-pk tests did not die either';
452 # sets the artist table name and clears sequence name cache
455 $s->source("Artist")->name($n);
456 $s->source('Artist')->column_info('artistid')->{sequence} = undef; #< clear sequence name cache
460 ######## EXTENDED AUTO-PK TESTS
464 package DBICTest::Schema::ExtAPK;
465 push @main::test_classes, __PACKAGE__;
469 use base 'DBIx::Class::Core';
471 __PACKAGE__->table('apk');
473 @eapk_id_columns = qw( id1 id2 id3 id4 );
474 __PACKAGE__->add_columns(
475 map { $_ => { data_type => 'integer', is_auto_increment => 1 } }
479 __PACKAGE__->set_primary_key('id2'); #< note the SECOND column is
484 BEGIN{ @eapk_schemas = map "dbic_apk_$_", 0..5 }
485 my %seqs; #< hash of schema.table.col => currval of its (DBIC) primary key sequence
487 sub run_extended_apk_tests {
490 #save the search path and reset it at the end
491 my $search_path_save = eapk_get_search_path($schema);
493 eapk_drop_all($schema);
495 # make the test schemas and sequences
496 $schema->storage->dbh_do(sub {
497 my ( undef, $dbh ) = @_;
499 $dbh->do("CREATE SCHEMA $_")
502 $dbh->do("CREATE SEQUENCE $eapk_schemas[5].fooseq");
503 $dbh->do("SELECT setval('$eapk_schemas[5].fooseq',400)");
504 $seqs{"$eapk_schemas[1].apk.id2"} = 400;
506 $dbh->do("CREATE SEQUENCE $eapk_schemas[4].fooseq");
507 $dbh->do("SELECT setval('$eapk_schemas[4].fooseq',300)");
508 $seqs{"$eapk_schemas[3].apk.id2"} = 300;
510 $dbh->do("CREATE SEQUENCE $eapk_schemas[3].fooseq");
511 $dbh->do("SELECT setval('$eapk_schemas[3].fooseq',200)");
512 $seqs{"$eapk_schemas[4].apk.id2"} = 200;
514 $dbh->do("SET search_path = ".join ',', reverse @eapk_schemas );
517 # clear our search_path cache
518 $schema->storage->{_pg_search_path} = undef;
520 eapk_create( $schema,
521 with_search_path => [0,1],
523 eapk_create( $schema,
524 with_search_path => [1,0,'public'],
525 nextval => "$eapk_schemas[5].fooseq",
527 eapk_create( $schema,
528 with_search_path => ['public',0,1],
531 eapk_create( $schema,
532 with_search_path => [3,1,0,'public'],
533 nextval => "$eapk_schemas[4].fooseq",
535 eapk_create( $schema,
536 with_search_path => [3,1,0,'public'],
537 nextval => "$eapk_schemas[3].fooseq",
541 eapk_poke( $schema );
542 eapk_poke( $schema, 0 );
543 eapk_poke( $schema, 2 );
544 eapk_poke( $schema, 4 );
545 eapk_poke( $schema, 1 );
546 eapk_poke( $schema, 0 );
547 eapk_poke( $schema, 1 );
548 eapk_poke( $schema );
549 eapk_poke( $schema, 4 );
550 eapk_poke( $schema, 3 );
551 eapk_poke( $schema, 1 );
552 eapk_poke( $schema, 2 );
553 eapk_poke( $schema, 0 );
555 # set our search path back
556 eapk_set_search_path( $schema, @$search_path_save );
559 # do a DBIC create on the apk table in the given schema number (which is an
560 # index of @eapk_schemas)
563 my ($s, $schema_num) = @_;
565 my $schema_name = defined $schema_num
566 ? $eapk_schemas[$schema_num]
569 my $schema_name_actual = $schema_name || eapk_find_visible_schema($s);
571 $s->source('ExtAPK')->name($schema_name ? $schema_name.'.apk' : 'apk');
572 #< clear sequence name cache
573 $s->source('ExtAPK')->column_info($_)->{sequence} = undef
574 for @eapk_id_columns;
576 no warnings 'uninitialized';
579 for my $inc (1,2,3) {
580 $new = $schema->resultset('ExtAPK')->create({ id1 => 1});
581 my $proper_seqval = ++$seqs{"$schema_name_actual.apk.id2"};
582 is( $new->id2, $proper_seqval, "$schema_name_actual.apk.id2 correct inc $inc" )
583 or eapk_seq_diag($s,$schema_name);
584 $new->discard_changes;
586 for my $id ('id3','id4') {
587 my $proper_seqval = ++$seqs{"$schema_name_actual.apk.$id"};
588 is( $new->$id, $proper_seqval, "$schema_name_actual.apk.$id correct inc $inc" )
589 or eapk_seq_diag($s,$schema_name);
592 } "create in schema '$schema_name' lives"
593 or eapk_seq_diag($s,$schema_name);
596 # print diagnostic info on which sequences were found in the ExtAPK
600 my $schema = shift || eapk_find_visible_schema($s);
602 diag "$schema.apk sequences: ",
604 map "$_:".($s->source('ExtAPK')->column_info($_)->{sequence} || '<none>'),
609 # get the postgres search path as an arrayref
610 sub eapk_get_search_path {
612 # cache the search path as ['schema','schema',...] in the storage
615 return $s->storage->dbh_do(sub {
616 my (undef, $dbh) = @_;
618 my ($sp_string) = $dbh->selectrow_array('SHOW search_path');
619 while ( $sp_string =~ s/("[^"]+"|[^,]+),?// ) {
620 unless( defined $1 and length $1 ) {
621 die "search path sanity check failed: '$1'";
623 push @search_path, $1;
628 sub eapk_set_search_path {
630 my $sp = join ',',@sp;
631 $s->storage->dbh_do( sub { $_[1]->do("SET search_path = $sp") } );
634 # create the apk table in the given schema, can set whether the table name is qualified, what the nextval is for the second ID
636 my ($schema, %a) = @_;
638 $schema->storage->dbh_do(sub {
639 my (undef,$dbh) = @_;
642 if ( $a{with_search_path} ) {
643 ($searchpath_save) = $dbh->selectrow_array('SHOW search_path');
645 my $search_path = join ',',map {/\D/ ? $_ : $eapk_schemas[$_]} @{$a{with_search_path}};
647 $dbh->do("SET search_path = $search_path");
650 my $table_name = $a{qualify_table}
651 ? ($eapk_schemas[$a{qualify_table}] || die). ".apk"
653 local $_[1]->{Warn} = 0;
655 my $id_def = $a{nextval}
656 ? "integer not null default nextval('$a{nextval}'::regclass)"
659 CREATE TABLE $table_name (
662 , id3 serial primary key
667 if( $searchpath_save ) {
668 $dbh->do("SET search_path = $searchpath_save");
674 my ( $schema, $warn_exceptions ) = @_;
676 $schema->storage->dbh_do(sub {
677 my (undef,$dbh) = @_;
679 local $dbh->{Warn} = 0;
681 # drop the test schemas
682 for (@eapk_schemas ) {
683 eval{ $dbh->do("DROP SCHEMA $_ CASCADE") };
684 diag $@ if $@ && $warn_exceptions;
691 sub eapk_find_visible_schema {
695 $s->storage->dbh_do(sub {
696 $_[1]->selectrow_array(<<EOS);
698 FROM pg_catalog.pg_namespace n
699 JOIN pg_catalog.pg_class c ON c.relnamespace = n.oid
700 WHERE c.relname = 'apk'
701 AND pg_catalog.pg_table_is_visible(c.oid)