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