Fix spurious ROLLBACK statements when a TxnScopeGuard fails a deferred commit
[dbsrgits/DBIx-Class.git] / t / 72pg.t
CommitLineData
70350518 1use strict;
4617b792 2use warnings;
70350518 3
4use Test::More;
9ba627e3 5use Test::Exception;
2fb5f18c 6use Test::Warn;
bbdda281 7use Sub::Name;
bb961936 8use Config;
199fbc45 9use DBIx::Class::Optional::Dependencies ();
70350518 10use lib qw(t/lib);
11use DBICTest;
b5ce6748 12use SQL::Abstract 'is_literal_value';
bb961936 13use DBIx::Class::_Util 'is_exception';
70350518 14
199fbc45 15plan skip_all => 'Test needs ' . DBIx::Class::Optional::Dependencies->req_missing_for ('test_rdbms_pg')
16 unless DBIx::Class::Optional::Dependencies->req_ok_for ('test_rdbms_pg');
89add887 17
0567538f 18my ($dsn, $user, $pass) = @ENV{map { "DBICTEST_PG_${_}" } qw/DSN USER PASS/};
19
67b79ae1 20plan skip_all => <<'EOM' unless $dsn && $user;
21Set $ENV{DBICTEST_PG_DSN}, _USER and _PASS to run this test
bab40dee 22( NOTE: This test drops and creates tables called 'artist', 'cd',
23'timestamp_primary_key_test', 'track', 'casecheck', 'array_test' and
24'sequence_test' as well as following sequences: 'pkid1_seq', 'pkid2_seq' and
67b79ae1 25'nonpkid_seq'. as well as following schemas: 'dbic_t_schema',
bab40dee 26'dbic_t_schema_2', 'dbic_t_schema_3', 'dbic_t_schema_4', and 'dbic_t_schema_5')
609c5f1b 27EOM
0567538f 28
52c53388 29### load any test classes that are defined further down in the file via BEGIN blocks
efd38994 30
70a201a5 31our @test_classes; #< array that will be pushed into by test classes defined in this file
32DBICTest::Schema->load_classes( map {s/.+:://;$_} @test_classes ) if @test_classes;
efd38994 33
52c53388 34### pre-connect tests (keep each test separate as to make sure rebless() runs)
bab40dee 35 {
36 my $s = DBICTest::Schema->connect($dsn, $user, $pass);
eabde904 37
bab40dee 38 ok (!$s->storage->_dbh, 'definitely not connected');
eabde904 39
bab40dee 40 # Check that datetime_parser returns correctly before we explicitly connect.
41 SKIP: {
68de9438 42 skip (
43 "Pg parser detection test needs " . DBIx::Class::Optional::Dependencies->req_missing_for ('test_dt_pg'),
44 2
45 ) unless DBIx::Class::Optional::Dependencies->req_ok_for ('test_dt_pg');
114780ee 46
bab40dee 47 my $store = ref $s->storage;
48 is($store, 'DBIx::Class::Storage::DBI', 'Started with generic storage');
114780ee 49
bab40dee 50 my $parser = $s->storage->datetime_parser;
51 is( $parser, 'DateTime::Format::Pg', 'datetime_parser is as expected');
52 }
114780ee 53
bab40dee 54 ok (!$s->storage->_dbh, 'still not connected');
55 }
bbdda281 56
bab40dee 57 {
58 my $s = DBICTest::Schema->connect($dsn, $user, $pass);
59 # make sure sqlt_type overrides work (::Storage::DBI::Pg does this)
60 ok (!$s->storage->_dbh, 'definitely not connected');
61 is ($s->storage->sqlt_type, 'PostgreSQL', 'sqlt_type correct pre-connection');
62 ok (!$s->storage->_dbh, 'still not connected');
63 }
0567538f 64
97277745 65# test LIMIT support
66{
67 my $schema = DBICTest::Schema->connect($dsn, $user, $pass);
68 drop_test_schema($schema);
69 create_test_schema($schema);
70 for (1..6) {
71 $schema->resultset('Artist')->create({ name => 'Artist ' . $_ });
72 }
73 my $it = $schema->resultset('Artist')->search( {},
74 { rows => 3,
75 offset => 2,
76 order_by => 'artistid' }
77 );
78 is( $it->count, 3, "LIMIT count ok" ); # ask for 3 rows out of 6 artists
79 is( $it->next->name, "Artist 3", "iterator->next ok" );
80 $it->next;
81 $it->next;
82 $it->next;
83 is( $it->next, undef, "next past end of resultset ok" );
e5372da4 84
85 # Limit with select-lock
86 lives_ok {
87 $schema->txn_do (sub {
88 isa_ok (
89 $schema->resultset('Artist')->find({artistid => 1}, {for => 'update', rows => 1}),
90 'DBICTest::Schema::Artist',
91 );
92 });
93 } 'Limited FOR UPDATE select works';
97277745 94}
95
bbdda281 96# check if we indeed do support stuff
97my $test_server_supports_insert_returning = do {
af1f4f84 98
99 my $si = DBICTest::Schema->connect($dsn, $user, $pass)->storage->_server_info;
100 die "Unparseable Pg server version: $si->{dbms_version}\n"
101 unless $si->{normalized_dbms_version};
102
103 $si->{normalized_dbms_version} < 8.002 ? 0 : 1;
bbdda281 104};
105is (
106 DBICTest::Schema->connect($dsn, $user, $pass)->storage->_use_insert_returning,
107 $test_server_supports_insert_returning,
108 'insert returning capability guessed correctly'
109);
110
111my $schema;
112for my $use_insert_returning ($test_server_supports_insert_returning
113 ? (0,1)
114 : (0)
115) {
116
6892eb09 117 no warnings qw/once redefine/;
118 my $old_connection = DBICTest::Schema->can('connection');
bbdda281 119 local *DBICTest::Schema::connection = subname 'DBICTest::Schema::connection' => sub {
6892eb09 120 my $s = shift->$old_connection(@_);
bbdda281 121 $s->storage->_use_insert_returning ($use_insert_returning);
122 $s;
123 };
124
125### test capability override
126 {
127 my $s = DBICTest::Schema->connect($dsn, $user, $pass);
128
129 ok (!$s->storage->_dbh, 'definitely not connected');
130
131 ok (
132 ! ($s->storage->_use_insert_returning xor $use_insert_returning),
133 'insert returning capability set correctly',
134 );
135 ok (!$s->storage->_dbh, 'still not connected (capability override works)');
136 }
137
70a201a5 138### connect, create postgres-specific test schema
c3af542a 139
bab40dee 140 $schema = DBICTest::Schema->connect($dsn, $user, $pass);
1f5aae08 141 $schema->storage->ensure_connected;
142
bab40dee 143 drop_test_schema($schema);
144 create_test_schema($schema);
609c5f1b 145
70a201a5 146### begin main tests
4617b792 147
372da819 148# run a BIG bunch of tests for last-insert-id / Auto-PK / sequence
149# discovery
bab40dee 150 run_apk_tests($schema); #< older set of auto-pk tests
151 run_extended_apk_tests($schema); #< new extended set of auto-pk tests
70a201a5 152
bab40dee 153### type_info tests
52c53388 154
bab40dee 155 my $test_type_info = {
156 'artistid' => {
157 'data_type' => 'integer',
158 'is_nullable' => 0,
159 'size' => 4,
160 },
161 'name' => {
162 'data_type' => 'character varying',
163 'is_nullable' => 1,
164 'size' => 100,
165 'default_value' => undef,
166 },
167 'rank' => {
168 'data_type' => 'integer',
169 'is_nullable' => 0,
170 'size' => 4,
171 'default_value' => 13,
52c53388 172
bab40dee 173 },
174 'charfield' => {
175 'data_type' => 'character',
176 'is_nullable' => 1,
177 'size' => 10,
178 'default_value' => undef,
179 },
180 'arrayfield' => {
181 'data_type' => 'integer[]',
182 'is_nullable' => 1,
183 'size' => undef,
184 'default_value' => undef,
185 },
186 };
52c53388 187
bab40dee 188 my $type_info = $schema->storage->columns_info_for('dbic_t_schema.artist');
189 my $artistid_defval = delete $type_info->{artistid}->{default_value};
190 like($artistid_defval,
191 qr/^nextval\('([^\.]*\.){0,1}artist_artistid_seq'::(?:text|regclass)\)/,
192 'columns_info_for - sequence matches Pg get_autoinc_seq expectations');
193 is_deeply($type_info, $test_type_info,
194 'columns_info_for - column data types');
52c53388 195
70a201a5 196
a953d8d9 197
a953d8d9 198
bab40dee 199####### Array tests
70a201a5 200
bab40dee 201 BEGIN {
202 package DBICTest::Schema::ArrayTest;
203 push @main::test_classes, __PACKAGE__;
70a201a5 204
bab40dee 205 use strict;
206 use warnings;
41519379 207 use base 'DBICTest::BaseResult';
70a201a5 208
bab40dee 209 __PACKAGE__->table('dbic_t_schema.array_test');
210 __PACKAGE__->add_columns(qw/id arrayfield/);
211 __PACKAGE__->column_info_from_storage(1);
212 __PACKAGE__->set_primary_key('id');
70a201a5 213
bab40dee 214 }
215 SKIP: {
0647e0cc 216 skip "Need DBD::Pg 2.9.2 or newer for array tests", 4 if $DBD::Pg::VERSION < 2.009002;
70a201a5 217
41519379 218 my $arr_rs = $schema->resultset('ArrayTest');
219
bab40dee 220 lives_ok {
41519379 221 $arr_rs->create({
bab40dee 222 arrayfield => [1, 2],
223 });
224 } 'inserting arrayref as pg array data';
70a201a5 225
bab40dee 226 lives_ok {
41519379 227 $arr_rs->update({
bab40dee 228 arrayfield => [3, 4],
229 });
230 } 'updating arrayref as pg array data';
ac45262b 231
41519379 232 $arr_rs->create({
0647e0cc 233 arrayfield => [5, 6],
9ba627e3 234 });
c224117b 235
f6faeab8 236 lives_ok {
237 $schema->populate('ArrayTest', [
238 [ qw/arrayfield/ ],
239 [ [0,0] ],
240 ]);
241 } 'inserting arrayref using void ctx populate';
242
41519379 243 # Search using arrays
244 lives_ok {
245 is_deeply (
246 $arr_rs->search({ arrayfield => { -value => [3,4] } })->first->arrayfield,
247 [3,4],
248 'Array value matches'
249 );
250 } 'searching by arrayref';
a780a0ff 251
bab40dee 252 lives_ok {
41519379 253 is_deeply (
254 $arr_rs->search({ arrayfield => { '=' => { -value => [3,4] }} })->first->arrayfield,
49eeb48d 255 [3,4],
41519379 256 'Array value matches explicit equal'
257 );
258 } 'searching by arrayref (explicit equal sign)';
a780a0ff 259
41519379 260 lives_ok {
261 is_deeply (
262 $arr_rs->search({ arrayfield => { '>' => { -value => [3,1] }} })->first->arrayfield,
263 [3,4],
264 'Array value matches greater than'
265 );
266 } 'searching by arrayref (greater than)';
267
268 lives_ok {
269 is (
270 $arr_rs->search({ arrayfield => { '>' => { -value => [3,7] }} })->count,
271 1,
272 'Greater than search found [5,6]',
273 );
274 } 'searching by arrayref (greater than)';
275
276 # Find using arrays
277 lives_ok {
278 is_deeply (
279 $arr_rs->find({ arrayfield => { -value => [3,4] } })->arrayfield,
280 [3,4],
281 'Array value matches implicit equal'
282 );
283 } 'find by arrayref';
284
285 lives_ok {
286 is_deeply (
287 $arr_rs->find({ arrayfield => { '=' => { -value => [3,4] }} })->arrayfield,
288 [3,4],
289 'Array value matches explicit equal'
290 );
291 } 'find by arrayref (equal)';
292
293 # test inferred condition for creation
4ca1fd6f 294 for my $cond (
41519379 295 { -value => [3,4] },
296 \[ '= ?' => [arrayfield => [3, 4]] ],
297 ) {
5f35ba0f 298 local $TODO = 'No introspection of complex literal conditions :('
299 if is_literal_value $cond;
300
301
41519379 302 my $arr_rs_cond = $arr_rs->search({ arrayfield => $cond });
303
304 my $row = $arr_rs_cond->create({});
a780a0ff 305 is_deeply ($row->arrayfield, [3,4], 'Array value taken from $rs condition');
306 $row->discard_changes;
307 is_deeply ($row->arrayfield, [3,4], 'Array value made it to storage');
308 }
bab40dee 309 }
9ba627e3 310
70a201a5 311########## Case check
312
bab40dee 313 BEGIN {
314 package DBICTest::Schema::Casecheck;
315 push @main::test_classes, __PACKAGE__;
70a201a5 316
bab40dee 317 use strict;
318 use warnings;
319 use base 'DBIx::Class::Core';
70a201a5 320
bab40dee 321 __PACKAGE__->table('dbic_t_schema.casecheck');
322 __PACKAGE__->add_columns(qw/id name NAME uc_name/);
323 __PACKAGE__->column_info_from_storage(1);
324 __PACKAGE__->set_primary_key('id');
325 }
70a201a5 326
bab40dee 327 my $name_info = $schema->source('Casecheck')->column_info( 'name' );
328 is( $name_info->{size}, 1, "Case sensitive matching info for 'name'" );
ae515736 329
bab40dee 330 my $NAME_info = $schema->source('Casecheck')->column_info( 'NAME' );
331 is( $NAME_info->{size}, 2, "Case sensitive matching info for 'NAME'" );
ae515736 332
bab40dee 333 my $uc_name_info = $schema->source('Casecheck')->column_info( 'uc_name' );
334 is( $uc_name_info->{size}, 3, "Case insensitive matching info for 'uc_name'" );
ae515736 335
70a201a5 336
ecccae8a 337## Test ResultSet->update
338my $artist = $schema->resultset('Artist')->first;
339my $cds = $artist->cds_unordered->search({
340 year => { '!=' => 2010 }
341}, { prefetch => 'liner_notes' });
67b79ae1 342lives_ok { $cds->update({ year => '2010' }) } 'Update on prefetched rs';
70a201a5 343
344## Test SELECT ... FOR UPDATE
bab40dee 345 SKIP: {
bb961936 346 skip "Your system does not support unsafe signals (d_sigaction) - unable to run deadlock test", 1
347 unless eval { $Config{d_sigaction} and require POSIX };
bab40dee 348
349 my ($timed_out, $artist2);
350
351 for my $t (
352 {
353 # Make sure that an error was raised, and that the update failed
354 update_lock => 1,
355 test_sub => sub {
356 ok($timed_out, "update from second schema times out");
357 ok($artist2->is_column_changed('name'), "'name' column is still dirty from second schema");
358 },
52c53388 359 },
bab40dee 360 {
361 # Make sure that an error was NOT raised, and that the update succeeded
362 update_lock => 0,
363 test_sub => sub {
364 ok(! $timed_out, "update from second schema DOES NOT timeout");
365 ok(! $artist2->is_column_changed('name'), "'name' column is NOT dirty from second schema");
366 },
52c53388 367 },
bab40dee 368 ) {
369 # create a new schema
370 my $schema2 = DBICTest::Schema->connect($dsn, $user, $pass);
371 $schema2->source("Artist")->name("dbic_t_schema.artist");
372
373 $schema->txn_do( sub {
d2408067 374 my $rs = $schema->resultset('Artist')->search(
bab40dee 375 {
376 artistid => 1
377 },
378 $t->{update_lock} ? { for => 'update' } : {}
d2408067 379 );
380 ok ($rs->count, 'Count works');
381
382 my $artist = $rs->next;
bab40dee 383 is($artist->artistid, 1, "select returns artistid = 1");
384
385 $timed_out = 0;
bb961936 386
bab40dee 387 eval {
bb961936 388 # can not use %SIG assignment directly - we need sigaction below
389 # localization to a block still works however
390 local $SIG{ALRM};
391
392 POSIX::sigaction( POSIX::SIGALRM() => POSIX::SigAction->new(
393 sub { die "DBICTestTimeout" },
394 ));
395
bab40dee 396 $artist2 = $schema2->resultset('Artist')->find(1);
397 $artist2->name('fooey');
3eb0ec80 398
399 # FIXME - this needs to go away in lieu of a non-retrying runner
400 # ( i.e. after solving RT#47005 )
401 local *DBIx::Class::Storage::DBI::_ping = sub { 1 }, DBIx::Class::_ENV_::OLD_MRO && Class::C3->reinitialize()
402 if DBIx::Class::_Util::modver_gt_or_eq( 'DBD::Pg' => '3.5.0' );
403
404 alarm(1);
bab40dee 405 $artist2->update;
bab40dee 406 };
bb961936 407
408 alarm(0);
409
410 if (is_exception($@)) {
411 $timed_out = $@ =~ /DBICTestTimeout/
412 or die $@;
413 }
bab40dee 414 });
415
416 $t->{test_sub}->();
417 }
418 }
95ba7ee4 419
70a201a5 420
372da819 421######## other older Auto-pk tests
70a201a5 422
bab40dee 423 $schema->source("SequenceTest")->name("dbic_t_schema.sequence_test");
424 for (1..5) {
425 my $st = $schema->resultset('SequenceTest')->create({ name => 'foo' });
426 is($st->pkid1, $_, "Auto-PK for sequence without default: First primary key");
427 is($st->pkid2, $_ + 9, "Auto-PK for sequence without default: Second primary key");
428 is($st->nonpkid, $_ + 19, "Auto-PK for sequence without default: Non-primary key");
429 }
430 my $st = $schema->resultset('SequenceTest')->create({ name => 'foo', pkid1 => 55 });
431 is($st->pkid1, 55, "Auto-PK for sequence without default: First primary key set manually");
4d4dc518 432
433
38d5ea9f 434######## test non-serial auto-pk
4d4dc518 435
bbdda281 436 if ($schema->storage->_use_insert_returning) {
bab40dee 437 $schema->source('TimestampPrimaryKey')->name('dbic_t_schema.timestamp_primary_key_test');
438 my $row = $schema->resultset('TimestampPrimaryKey')->create({});
439 ok $row->id;
440 }
d093d3eb 441
be860760 442######## test with_deferred_fk_checks
443
bab40dee 444 $schema->source('CD')->name('dbic_t_schema.cd');
445 $schema->source('Track')->name('dbic_t_schema.track');
446 lives_ok {
447 $schema->storage->with_deferred_fk_checks(sub {
448 $schema->resultset('Track')->create({
449 trackid => 999, cd => 999, position => 1, title => 'deferred FK track'
450 });
451 $schema->resultset('CD')->create({
452 artist => 1, cdid => 999, year => '2003', title => 'deferred FK cd'
453 });
be860760 454 });
bab40dee 455 } 'with_deferred_fk_checks code survived';
be860760 456
bab40dee 457 is eval { $schema->resultset('Track')->find(999)->title }, 'deferred FK track',
8273e845 458 'code in with_deferred_fk_checks worked';
be860760 459
bab40dee 460 throws_ok {
461 $schema->resultset('Track')->create({
462 trackid => 1, cd => 9999, position => 1, title => 'Track1'
463 });
2fb5f18c 464 } qr/violates foreign key constraint/i, 'with_deferred_fk_checks is off outside of TXN';
465
466 # rerun the same under with_deferred_fk_checks
467 # it is expected to fail, hence the eval
468 # but it also should not warn
469 warnings_like {
470
471 # workaround for PG 9.5, fix pending in mainline
472 local $schema->storage->_dbh->{PrintWarn} = 0;
473
474 eval {
475 $schema->storage->with_deferred_fk_checks(sub {
476 $schema->resultset('Track')->create({
477 trackid => 1, cd => 9999, position => 1, title => 'Track1'
478 });
479 } )
480 };
481
482 like $@, qr/violates foreign key constraint/i,
483 "Still expected exception on deferred failure at commit time";
484
485 } [], 'No warnings on deferred rollback';
bab40dee 486}
be860760 487
2fbf50ff 488done_testing;
609c5f1b 489
5935c90a 490END {
f66c9ba8 491 return unless $schema;
5935c90a 492 drop_test_schema($schema);
65d35121 493 eapk_drop_all($schema);
494 undef $schema;
5935c90a 495};
70a201a5 496
497
498######### SUBROUTINES
499
500sub create_test_schema {
2fbf50ff 501 my $schema = shift;
502 $schema->storage->dbh_do(sub {
503 my (undef,$dbh) = @_;
70a201a5 504
2fbf50ff 505 local $dbh->{Warn} = 0;
70a201a5 506
2fbf50ff 507 my $std_artist_table = <<EOS;
70a201a5 508(
509 artistid serial PRIMARY KEY
510 , name VARCHAR(100)
511 , rank INTEGER NOT NULL DEFAULT '13'
512 , charfield CHAR(10)
513 , arrayfield INTEGER[]
514)
515EOS
516
881def48 517 $dbh->do("CREATE SCHEMA dbic_t_schema");
518 $dbh->do("CREATE TABLE dbic_t_schema.artist $std_artist_table");
4d4dc518 519
520 $dbh->do(<<EOS);
521CREATE TABLE dbic_t_schema.timestamp_primary_key_test (
be860760 522 id timestamp default current_timestamp
4d4dc518 523)
524EOS
2fbf50ff 525 $dbh->do(<<EOS);
be860760 526CREATE TABLE dbic_t_schema.cd (
527 cdid int PRIMARY KEY,
528 artist int,
529 title varchar(255),
530 year varchar(4),
531 genreid int,
532 single_track int
533)
534EOS
535 $dbh->do(<<EOS);
536CREATE TABLE dbic_t_schema.track (
537 trackid int,
538 cd int REFERENCES dbic_t_schema.cd(cdid) DEFERRABLE,
539 position int,
540 title varchar(255),
541 last_updated_on date,
3d98c75e 542 last_updated_at date
be860760 543)
544EOS
545
546 $dbh->do(<<EOS);
881def48 547CREATE TABLE dbic_t_schema.sequence_test (
70a201a5 548 pkid1 integer
549 , pkid2 integer
550 , nonpkid integer
551 , name VARCHAR(100)
552 , CONSTRAINT pk PRIMARY KEY(pkid1, pkid2)
553)
554EOS
2fbf50ff 555 $dbh->do("CREATE SEQUENCE pkid1_seq START 1 MAXVALUE 999999 MINVALUE 0");
556 $dbh->do("CREATE SEQUENCE pkid2_seq START 10 MAXVALUE 999999 MINVALUE 0");
557 $dbh->do("CREATE SEQUENCE nonpkid_seq START 20 MAXVALUE 999999 MINVALUE 0");
558 $dbh->do(<<EOS);
881def48 559CREATE TABLE dbic_t_schema.casecheck (
70a201a5 560 id serial PRIMARY KEY
561 , "name" VARCHAR(1)
562 , "NAME" VARCHAR(2)
563 , "UC_NAME" VARCHAR(3)
70a201a5 564)
565EOS
2fbf50ff 566 $dbh->do(<<EOS);
881def48 567CREATE TABLE dbic_t_schema.array_test (
70a201a5 568 id serial PRIMARY KEY
569 , arrayfield INTEGER[]
570)
571EOS
881def48 572 $dbh->do("CREATE SCHEMA dbic_t_schema_2");
573 $dbh->do("CREATE TABLE dbic_t_schema_2.artist $std_artist_table");
574 $dbh->do("CREATE SCHEMA dbic_t_schema_3");
575 $dbh->do("CREATE TABLE dbic_t_schema_3.artist $std_artist_table");
576 $dbh->do('set search_path=dbic_t_schema,public');
577 $dbh->do("CREATE SCHEMA dbic_t_schema_4");
578 $dbh->do("CREATE SCHEMA dbic_t_schema_5");
2fbf50ff 579 $dbh->do(<<EOS);
881def48 580 CREATE TABLE dbic_t_schema_4.artist
70a201a5 581 (
582 artistid integer not null default nextval('artist_artistid_seq'::regclass) PRIMARY KEY
583 , name VARCHAR(100)
584 , rank INTEGER NOT NULL DEFAULT '13'
585 , charfield CHAR(10)
586 , arrayfield INTEGER[]
587 );
588EOS
881def48 589 $dbh->do('set search_path=public,dbic_t_schema,dbic_t_schema_3');
2fbf50ff 590 $dbh->do('create sequence public.artist_artistid_seq'); #< in the public schema
591 $dbh->do(<<EOS);
881def48 592 CREATE TABLE dbic_t_schema_5.artist
70a201a5 593 (
594 artistid integer not null default nextval('public.artist_artistid_seq'::regclass) PRIMARY KEY
595 , name VARCHAR(100)
596 , rank INTEGER NOT NULL DEFAULT '13'
597 , charfield CHAR(10)
598 , arrayfield INTEGER[]
599 );
600EOS
881def48 601 $dbh->do('set search_path=dbic_t_schema,public');
2fbf50ff 602 });
70a201a5 603}
604
605
606
607sub drop_test_schema {
52c53388 608 my ( $schema, $warn_exceptions ) = @_;
2fbf50ff 609
610 $schema->storage->dbh_do(sub {
611 my (undef,$dbh) = @_;
612
613 local $dbh->{Warn} = 0;
614
615 for my $stat (
881def48 616 'DROP SCHEMA dbic_t_schema_5 CASCADE',
e78c769d 617 'DROP SEQUENCE public.artist_artistid_seq CASCADE',
881def48 618 'DROP SCHEMA dbic_t_schema_4 CASCADE',
619 'DROP SCHEMA dbic_t_schema CASCADE',
e78c769d 620 'DROP SEQUENCE pkid1_seq CASCADE',
621 'DROP SEQUENCE pkid2_seq CASCADE',
622 'DROP SEQUENCE nonpkid_seq CASCADE',
881def48 623 'DROP SCHEMA dbic_t_schema_2 CASCADE',
624 'DROP SCHEMA dbic_t_schema_3 CASCADE',
2fbf50ff 625 ) {
626 eval { $dbh->do ($stat) };
52c53388 627 diag $@ if $@ && $warn_exceptions;
2fbf50ff 628 }
629 });
3ff5b740 630}
7603d2a5 631
372da819 632
ee9f372c 633### auto-pk / last_insert_id / sequence discovery
634sub run_apk_tests {
635 my $schema = shift;
636
637 # This is in Core now, but it's here just to test that it doesn't break
638 $schema->class('Artist')->load_components('PK::Auto');
639 cmp_ok( $schema->resultset('Artist')->count, '==', 0, 'this should start with an empty artist table');
640
641 # test that auto-pk also works with the defined search path by
642 # un-schema-qualifying the table name
643 apk_t_set($schema,'artist');
644
645 my $unq_new;
646 lives_ok {
647 $unq_new = $schema->resultset('Artist')->create({ name => 'baz' });
648 } 'insert into unqualified, shadowed table succeeds';
649
650 is($unq_new && $unq_new->artistid, 1, "and got correct artistid");
651
652 my @test_schemas = ( [qw| dbic_t_schema_2 1 |],
653 [qw| dbic_t_schema_3 1 |],
654 [qw| dbic_t_schema_4 2 |],
655 [qw| dbic_t_schema_5 1 |],
656 );
657 foreach my $t ( @test_schemas ) {
658 my ($sch_name, $start_num) = @$t;
659 #test with dbic_t_schema_2
660 apk_t_set($schema,"$sch_name.artist");
661 my $another_new;
662 lives_ok {
663 $another_new = $schema->resultset('Artist')->create({ name => 'Tollbooth Willy'});
664 is( $another_new->artistid,$start_num, "got correct artistid for $sch_name")
665 or diag "USED SEQUENCE: ".($schema->source('Artist')->column_info('artistid')->{sequence} || '<none>');
666 } "$sch_name liid 1 did not die"
667 or diag "USED SEQUENCE: ".($schema->source('Artist')->column_info('artistid')->{sequence} || '<none>');
668 lives_ok {
669 $another_new = $schema->resultset('Artist')->create({ name => 'Adam Sandler'});
670 is( $another_new->artistid,$start_num+1, "got correct artistid for $sch_name")
671 or diag "USED SEQUENCE: ".($schema->source('Artist')->column_info('artistid')->{sequence} || '<none>');
672 } "$sch_name liid 2 did not die"
673 or diag "USED SEQUENCE: ".($schema->source('Artist')->column_info('artistid')->{sequence} || '<none>');
674
675 }
676
677 lives_ok {
678 apk_t_set($schema,'dbic_t_schema.artist');
679 my $new = $schema->resultset('Artist')->create({ name => 'foo' });
680 is($new->artistid, 4, "Auto-PK worked");
681 $new = $schema->resultset('Artist')->create({ name => 'bar' });
682 is($new->artistid, 5, "Auto-PK worked");
683 } 'old auto-pk tests did not die either';
684}
685
ee9f372c 686# sets the artist table name and clears sequence name cache
687sub apk_t_set {
688 my ( $s, $n ) = @_;
689 $s->source("Artist")->name($n);
690 $s->source('Artist')->column_info('artistid')->{sequence} = undef; #< clear sequence name cache
691}
692
372da819 693
5935c90a 694######## EXTENDED AUTO-PK TESTS
695
f295a73c 696my @eapk_id_columns;
5935c90a 697BEGIN {
698 package DBICTest::Schema::ExtAPK;
699 push @main::test_classes, __PACKAGE__;
700
701 use strict;
702 use warnings;
d88ecca6 703 use base 'DBIx::Class::Core';
5935c90a 704
f295a73c 705 __PACKAGE__->table('apk');
5935c90a 706
f295a73c 707 @eapk_id_columns = qw( id1 id2 id3 id4 );
5935c90a 708 __PACKAGE__->add_columns(
709 map { $_ => { data_type => 'integer', is_auto_increment => 1 } }
f295a73c 710 @eapk_id_columns
5935c90a 711 );
712
f295a73c 713 __PACKAGE__->set_primary_key('id2'); #< note the SECOND column is
714 #the primary key
5935c90a 715}
716
f295a73c 717my @eapk_schemas;
718BEGIN{ @eapk_schemas = map "dbic_apk_$_", 0..5 }
ae645c61 719my %seqs; #< hash of schema.table.col => currval of its (DBIC) primary key sequence
5935c90a 720
372da819 721sub run_extended_apk_tests {
11da4e66 722 my $schema = shift;
372da819 723
f295a73c 724 #save the search path and reset it at the end
49aa7e87 725 my $search_path_save = eapk_get_search_path($schema);
f295a73c 726
52c53388 727 eapk_drop_all($schema);
bab40dee 728 %seqs = ();
5935c90a 729
f295a73c 730 # make the test schemas and sequences
11da4e66 731 $schema->storage->dbh_do(sub {
f295a73c 732 my ( undef, $dbh ) = @_;
733
734 $dbh->do("CREATE SCHEMA $_")
735 for @eapk_schemas;
736
737 $dbh->do("CREATE SEQUENCE $eapk_schemas[5].fooseq");
ae645c61 738 $dbh->do("SELECT setval('$eapk_schemas[5].fooseq',400)");
739 $seqs{"$eapk_schemas[1].apk.id2"} = 400;
740
fb7be534 741 $dbh->do("CREATE SEQUENCE $eapk_schemas[4].fooseq");
ae645c61 742 $dbh->do("SELECT setval('$eapk_schemas[4].fooseq',300)");
743 $seqs{"$eapk_schemas[3].apk.id2"} = 300;
744
93a6e8fa 745 $dbh->do("CREATE SEQUENCE $eapk_schemas[3].fooseq");
ae645c61 746 $dbh->do("SELECT setval('$eapk_schemas[3].fooseq',200)");
747 $seqs{"$eapk_schemas[4].apk.id2"} = 200;
f295a73c 748
78c9596c 749 $dbh->do("SET search_path = ".join ',', reverse @eapk_schemas );
11da4e66 750 });
372da819 751
f295a73c 752 # clear our search_path cache
753 $schema->storage->{_pg_search_path} = undef;
754
755 eapk_create( $schema,
756 with_search_path => [0,1],
757 );
758 eapk_create( $schema,
759 with_search_path => [1,0,'public'],
760 nextval => "$eapk_schemas[5].fooseq",
761 );
762 eapk_create( $schema,
763 with_search_path => ['public',0,1],
764 qualify_table => 2,
765 );
fb7be534 766 eapk_create( $schema,
767 with_search_path => [3,1,0,'public'],
768 nextval => "$eapk_schemas[4].fooseq",
769 );
93a6e8fa 770 eapk_create( $schema,
771 with_search_path => [3,1,0,'public'],
772 nextval => "$eapk_schemas[3].fooseq",
773 qualify_table => 4,
774 );
372da819 775
78c9596c 776 eapk_poke( $schema );
f295a73c 777 eapk_poke( $schema, 0 );
eb80e8d5 778 eapk_poke( $schema, 2 );
93a6e8fa 779 eapk_poke( $schema, 4 );
f295a73c 780 eapk_poke( $schema, 1 );
eb80e8d5 781 eapk_poke( $schema, 0 );
f295a73c 782 eapk_poke( $schema, 1 );
78c9596c 783 eapk_poke( $schema );
93a6e8fa 784 eapk_poke( $schema, 4 );
fb7be534 785 eapk_poke( $schema, 3 );
eb80e8d5 786 eapk_poke( $schema, 1 );
787 eapk_poke( $schema, 2 );
788 eapk_poke( $schema, 0 );
f295a73c 789
790 # set our search path back
791 eapk_set_search_path( $schema, @$search_path_save );
792}
793
794# do a DBIC create on the apk table in the given schema number (which is an
795# index of @eapk_schemas)
796
f295a73c 797sub eapk_poke {
798 my ($s, $schema_num) = @_;
372da819 799
f295a73c 800 my $schema_name = defined $schema_num
801 ? $eapk_schemas[$schema_num]
802 : '';
803
78c9596c 804 my $schema_name_actual = $schema_name || eapk_find_visible_schema($s);
f295a73c 805
8ce84173 806 $s->source('ExtAPK')->name($schema_name ? $schema_name.'.apk' : 'apk');
f295a73c 807 #< clear sequence name cache
808 $s->source('ExtAPK')->column_info($_)->{sequence} = undef
809 for @eapk_id_columns;
810
811 no warnings 'uninitialized';
812 lives_ok {
813 my $new;
814 for my $inc (1,2,3) {
ae645c61 815 $new = $schema->resultset('ExtAPK')->create({ id1 => 1});
691f3663 816 my $proper_seqval = ++$seqs{"$schema_name_actual.apk.id2"};
817 is( $new->id2, $proper_seqval, "$schema_name_actual.apk.id2 correct inc $inc" )
818 or eapk_seq_diag($s,$schema_name);
819 $new->discard_changes;
ae645c61 820 is( $new->id1, 1 );
821 for my $id ('id3','id4') {
f295a73c 822 my $proper_seqval = ++$seqs{"$schema_name_actual.apk.$id"};
93a6e8fa 823 is( $new->$id, $proper_seqval, "$schema_name_actual.apk.$id correct inc $inc" )
fb7be534 824 or eapk_seq_diag($s,$schema_name);
f295a73c 825 }
826 }
827 } "create in schema '$schema_name' lives"
fb7be534 828 or eapk_seq_diag($s,$schema_name);
372da819 829}
830
f295a73c 831# print diagnostic info on which sequences were found in the ExtAPK
832# class
833sub eapk_seq_diag {
834 my $s = shift;
78c9596c 835 my $schema = shift || eapk_find_visible_schema($s);
f295a73c 836
837 diag "$schema.apk sequences: ",
838 join(', ',
839 map "$_:".($s->source('ExtAPK')->column_info($_)->{sequence} || '<none>'),
840 @eapk_id_columns
841 );
842}
843
49aa7e87 844# get the postgres search path as an arrayref
845sub eapk_get_search_path {
846 my ( $s ) = @_;
847 # cache the search path as ['schema','schema',...] in the storage
848 # obj
849
850 return $s->storage->dbh_do(sub {
851 my (undef, $dbh) = @_;
852 my @search_path;
853 my ($sp_string) = $dbh->selectrow_array('SHOW search_path');
854 while ( $sp_string =~ s/("[^"]+"|[^,]+),?// ) {
855 unless( defined $1 and length $1 ) {
856 die "search path sanity check failed: '$1'";
857 }
858 push @search_path, $1;
859 }
860 \@search_path
861 });
862}
f295a73c 863sub eapk_set_search_path {
864 my ($s,@sp) = @_;
865 my $sp = join ',',@sp;
866 $s->storage->dbh_do( sub { $_[1]->do("SET search_path = $sp") } );
867}
868
869# create the apk table in the given schema, can set whether the table name is qualified, what the nextval is for the second ID
5935c90a 870sub eapk_create {
871 my ($schema, %a) = @_;
872
372da819 873 $schema->storage->dbh_do(sub {
5935c90a 874 my (undef,$dbh) = @_;
372da819 875
5935c90a 876 my $searchpath_save;
877 if ( $a{with_search_path} ) {
878 ($searchpath_save) = $dbh->selectrow_array('SHOW search_path');
879
f295a73c 880 my $search_path = join ',',map {/\D/ ? $_ : $eapk_schemas[$_]} @{$a{with_search_path}};
5935c90a 881
882 $dbh->do("SET search_path = $search_path");
883 }
884
f295a73c 885 my $table_name = $a{qualify_table}
886 ? ($eapk_schemas[$a{qualify_table}] || die). ".apk"
887 : 'apk';
e25fe566 888 local $_[1]->{Warn} = 0;
f295a73c 889
890 my $id_def = $a{nextval}
ae645c61 891 ? "integer not null default nextval('$a{nextval}'::regclass)"
892 : 'serial';
5935c90a 893 $dbh->do(<<EOS);
f295a73c 894CREATE TABLE $table_name (
895 id1 serial
896 , id2 $id_def
ae645c61 897 , id3 serial primary key
5935c90a 898 , id4 serial
899)
900EOS
372da819 901
5935c90a 902 if( $searchpath_save ) {
903 $dbh->do("SET search_path = $searchpath_save");
904 }
372da819 905 });
906}
907
5935c90a 908sub eapk_drop_all {
52c53388 909 my ( $schema, $warn_exceptions ) = @_;
372da819 910
911 $schema->storage->dbh_do(sub {
912 my (undef,$dbh) = @_;
913
914 local $dbh->{Warn} = 0;
5935c90a 915
916 # drop the test schemas
f295a73c 917 for (@eapk_schemas ) {
11da4e66 918 eval{ $dbh->do("DROP SCHEMA $_ CASCADE") };
52c53388 919 diag $@ if $@ && $warn_exceptions;
11da4e66 920 }
921
372da819 922
372da819 923 });
924}
78c9596c 925
926sub eapk_find_visible_schema {
927 my ($s) = @_;
928
929 my ($schema) =
930 $s->storage->dbh_do(sub {
931 $_[1]->selectrow_array(<<EOS);
932SELECT n.nspname
933FROM pg_catalog.pg_namespace n
934JOIN pg_catalog.pg_class c ON c.relnamespace = n.oid
935WHERE c.relname = 'apk'
936 AND pg_catalog.pg_table_is_visible(c.oid)
937EOS
938 });
939 return $schema;
940}