7 use DBIx::Class::SQLMaker::LimitDialects;
8 use DBIx::Class::Optional::Dependencies ();
11 use DBIC::SqlMakerTest;
13 plan skip_all => 'Test needs ' . DBIx::Class::Optional::Dependencies->req_missing_for ('test_rdbms_mssql_odbc')
14 unless DBIx::Class::Optional::Dependencies->req_ok_for ('test_rdbms_mssql_odbc');
16 my $OFFSET = DBIx::Class::SQLMaker::LimitDialects->__offset_bindtype;
17 my $TOTAL = DBIx::Class::SQLMaker::LimitDialects->__total_bindtype;
19 my ($dsn, $user, $pass) = @ENV{map { "DBICTEST_MSSQL_ODBC_${_}" } qw/DSN USER PASS/};
21 plan skip_all => 'Set $ENV{DBICTEST_MSSQL_ODBC_DSN}, _USER and _PASS to run this test'
22 unless ($dsn && $user);
25 my $srv_ver = DBICTest::Schema->connect($dsn, $user, $pass)->storage->_server_info->{dbms_version};
26 ok ($srv_ver, 'Got a test server version on fresh schema: ' . ($srv_ver||'???') );
29 DBICTest::Schema->load_classes('ArtistGUID');
30 my $schema = DBICTest::Schema->connect($dsn, $user, $pass);
33 no warnings 'redefine';
34 my $connect_count = 0;
35 my $orig_connect = \&DBI::connect;
36 local *DBI::connect = sub { $connect_count++; goto &$orig_connect };
38 $schema->storage->ensure_connected;
40 is( $connect_count, 1, 'only one connection made');
43 isa_ok( $schema->storage, 'DBIx::Class::Storage::DBI::ODBC::Microsoft_SQL_Server' );
46 my $schema2 = $schema->connect (@{$schema->storage->connect_info});
47 ok (! $schema2->storage->connected, 'a re-connected cloned schema starts unconnected');
49 $schema->storage->_dbh->disconnect;
52 $schema->storage->dbh_do(sub { $_[1]->do('select 1') })
57 { opts => { on_connect_call => 'use_mars' } },
58 use_dynamic_cursors =>
59 { opts => { on_connect_call => 'use_dynamic_cursors' },
60 required => $schema->storage->_using_freetds ? 0 : 1,
63 { opts => { on_connect_call => 'use_server_cursors' } },
65 { opts => {}, required => 1 },
68 for my $opts_name (keys %opts) {
70 my $opts = $opts{$opts_name}{opts};
71 $schema = DBICTest::Schema->connect($dsn, $user, $pass, $opts);
74 $schema->storage->ensure_connected
77 if ($opts{$opts_name}{required}) {
78 die "on_connect_call option '$opts_name' is not functional: $_";
82 "on_connect_call option '$opts_name' not functional in this configuration: $_",
88 $schema->storage->dbh_do (sub {
89 my ($storage, $dbh) = @_;
90 eval { $dbh->do("DROP TABLE artist") };
93 artistid INT IDENTITY NOT NULL,
95 rank INT NOT NULL DEFAULT '13',
96 charfield CHAR(10) NULL,
103 $schema->resultset('Artist')->search({ name => 'foo' })->delete;
105 my $new = $schema->resultset('Artist')->create({ name => 'foo' });
107 ok(($new->artistid||0) > 0, "Auto-PK worked for $opts_name");
109 # Test multiple active statements
111 skip 'not a multiple active statements configuration', 1
112 if $opts_name eq 'plain';
114 $schema->storage->ensure_connected;
118 no warnings 'redefine';
119 local *DBI::connect = sub { die "NO RECONNECTS!!!" };
121 my $artist_rs = $schema->resultset('Artist');
125 $artist_rs->create({ name => "Artist$_" }) for (1..3);
127 my $forward = $artist_rs->search({},
128 { order_by => { -asc => 'artistid' } });
129 my $backward = $artist_rs->search({},
130 { order_by => { -desc => 'artistid' } });
133 [qw/Artist1 Artist3/], [qw/Artist2 Artist2/], [qw/Artist3 Artist1/]
137 while (my $forward_row = $forward->next) {
138 my $backward_row = $backward->next;
139 push @result, [$forward_row->name, $backward_row->name];
142 is_deeply \@result, \@map, "multiple active statements in $opts_name";
146 is($artist_rs->count, 0, '$dbh still viable');
147 } "Multiple active statements survive $opts_name";
153 $schema->storage->dbh_do (sub {
154 my ($storage, $dbh) = @_;
155 eval { $dbh->do("DROP TABLE owners") };
156 eval { $dbh->do("DROP TABLE books") };
159 id INT IDENTITY (1, 1) NOT NULL,
166 CREATE TABLE owners (
167 id INT IDENTITY (1, 1) NOT NULL,
174 # start a new connection, make sure rebless works
175 my $schema = DBICTest::Schema->connect($dsn, $user, $pass, $opts);
176 $schema->populate ('Owners', [
189 [qw/12 face_to_face/],
194 }, 'populate with PKs supplied ok' );
198 # start a new connection, make sure rebless works
199 # test an insert with a supplied identity, followed by one without
200 my $schema = DBICTest::Schema->connect($dsn, $user, $pass, $opts);
203 $schema->resultset ('Owners')->create ({ id => $id, name => "troglodoogle $id" });
204 $schema->resultset ('Owners')->create ({ name => "troglodoogle " . ($id + 1) });
206 }, 'create with/without PKs ok' );
208 is ($schema->resultset ('Owners')->count, 19, 'owner rows really in db' );
211 # start a new connection, make sure rebless works
212 my $schema = DBICTest::Schema->connect($dsn, $user, $pass, $opts);
213 $schema->populate ('BooksInLibrary', [
214 [qw/source owner title /],
215 [qw/Library 1 secrets0/],
216 [qw/Library 1 secrets1/],
217 [qw/Eatery 1 secrets2/],
218 [qw/Library 2 secrets3/],
219 [qw/Library 3 secrets4/],
220 [qw/Eatery 3 secrets5/],
221 [qw/Library 4 secrets6/],
222 [qw/Library 5 secrets7/],
223 [qw/Eatery 5 secrets8/],
224 [qw/Library 6 secrets9/],
225 [qw/Library 7 secrets10/],
226 [qw/Eatery 7 secrets11/],
227 [qw/Library 8 secrets12/],
229 }, 'populate without PKs supplied ok' );
232 # test simple, complex LIMIT and limited prefetch support, with both dialects and quote combinations (if possible)
235 ($schema->storage->_server_info->{normalized_dbms_version} || 0 ) >= 9
240 for my $quoted (0, 1) {
242 $schema = DBICTest::Schema->connect($dsn, $user, $pass, {
243 limit_dialect => $dialect,
246 ? ( quote_char => [ qw/ [ ] / ], name_sep => '.' )
251 my $test_type = "Dialect:$dialect Quoted:$quoted";
253 # basic limit support
255 my $art_rs = $schema->resultset ('Artist');
257 $art_rs->create({ name => 'Artist ' . $_ }) for (1..6);
259 my $it = $schema->resultset('Artist')->search( {}, {
262 order_by => 'artistid',
265 is( $it->count, 3, "$test_type: LIMIT count ok" );
267 local $TODO = "Top-limit does not work when your limit ends up past the resultset"
268 if $dialect eq 'Top';
270 is( $it->next->name, 'Artist 4', "$test_type: iterator->next ok" );
272 is( $it->next->name, 'Artist 6', "$test_type: iterator->next ok" );
273 is( $it->next, undef, "$test_type: next past end of resultset ok" );
276 # plain ordered subqueries throw
278 $schema->resultset('Owners')->search ({}, { order_by => 'name' })->as_query
279 }, qr/ordered subselect encountered/, "$test_type: Ordered Subselect detection throws ok");
281 # make sure ordered subselects *somewhat* work
283 my $owners = $schema->resultset ('Owners')->search ({}, { order_by => 'name', offset => 2, rows => 3, unsafe_subselect_ok => 1 });
284 my $sealed_owners = $owners->as_subselect_rs;
287 [ map { $_->name } ($sealed_owners->all) ],
288 [ map { $_->name } ($owners->all) ],
289 "$test_type: Sort preserved from within a subquery",
293 # still even with lost order of IN, we should be getting correct
296 my $owners = $schema->resultset ('Owners')->search ({}, { order_by => 'name', offset => 2, rows => 3, unsafe_subselect_ok => 1 });
297 my $corelated_owners = $owners->result_source->resultset->search (
299 id => { -in => $owners->get_column('id')->as_query },
302 order_by => 'name' #reorder because of what is shown above
307 join ("\x00", map { $_->name } ($corelated_owners->all) ),
308 join ("\x00", map { $_->name } ($owners->all) ),
309 "$test_type: With an outer order_by, everything still matches",
313 # make sure right-join-side single-prefetch ordering limit works
315 my $rs = $schema->resultset ('BooksInLibrary')->search (
317 'owner.name' => { '!=', 'woggle' },
321 order_by => 'owner.name',
324 # this is the order in which they should come from the above query
325 my @owner_names = qw/boggle fISMBoC fREW fRIOUX fROOH fRUE wiggle wiggle/;
327 is ($rs->all, 8, "$test_type: Correct amount of objects from right-sorted joined resultset");
329 [map { $_->owner->name } ($rs->all) ],
331 "$test_type: Prefetched rows were properly ordered"
334 my $limited_rs = $rs->search ({}, {rows => 6, offset => 2, unsafe_subselect_ok => 1});
335 is ($limited_rs->count, 6, "$test_type: Correct count of limited right-sorted joined resultset");
336 is ($limited_rs->count_rs->next, 6, "$test_type: Correct count_rs of limited right-sorted joined resultset");
339 my $orig_debug = $schema->storage->debug;
340 $schema->storage->debugcb(sub { $queries++; });
341 $schema->storage->debug(1);
344 [map { $_->owner->name } ($limited_rs->all) ],
345 [@owner_names[2 .. 7]],
346 "$test_type: Prefetch-limited rows were properly ordered"
348 is ($queries, 1, "$test_type: Only one query with prefetch");
350 $schema->storage->debugcb(undef);
351 $schema->storage->debug($orig_debug);
354 [map { $_->name } ($limited_rs->search_related ('owner')->all) ],
355 [@owner_names[2 .. 7]],
356 "$test_type: Rows are still properly ordered after search_related",
360 # try a ->has_many direction with duplicates
361 my $owners = $schema->resultset ('Owners')->search (
363 'books.id' => { '!=', undef },
364 'me.name' => { '!=', 'somebogusstring' },
368 order_by => [ { -asc => \['name + ?', [ test => 'xxx' ]] }, 'me.id' ], # test bindvar propagation
369 group_by => [ map { "me.$_" } $schema->source('Owners')->columns ], # the literal order_by requires an explicit group_by
370 rows => 3, # 8 results total
371 unsafe_subselect_ok => 1,
376 $owners->page(3)->as_query,
379 SELECT TOP 2147483647 [me].[id], [me].[name],
380 [books].[id], [books].[source], [books].[owner], [books].[title], [books].[price]
382 SELECT TOP 2147483647 [me].[id], [me].[name]
384 SELECT TOP 3 [me].[id], [me].[name], [ORDER__BY__001]
386 SELECT TOP 9 [me].[id], [me].[name], name + ? AS [ORDER__BY__001]
388 LEFT JOIN [books] [books]
389 ON [books].[owner] = [me].[id]
390 WHERE [books].[id] IS NOT NULL AND [me].[name] != ?
391 GROUP BY [me].[id], [me].[name]
392 ORDER BY name + ? ASC, [me].[id]
394 ORDER BY [ORDER__BY__001] DESC, [me].[id] DESC
396 ORDER BY [ORDER__BY__001] ASC, [me].[id]
398 LEFT JOIN [books] [books]
399 ON [books].[owner] = [me].[id]
400 WHERE [books].[id] IS NOT NULL AND [me].[name] != ?
401 ORDER BY name + ? ASC, [me].[id]
404 SELECT TOP 2147483647 [me].[id], [me].[name],
405 [books].[id], [books].[source], [books].[owner], [books].[title], [books].[price]
407 SELECT TOP 2147483647 [me].[id], [me].[name]
409 SELECT [me].[id], [me].[name],
410 ROW_NUMBER() OVER( ORDER BY [ORDER__BY__001] ASC, [me].[id] ) AS [rno__row__index]
412 SELECT [me].[id], [me].[name], name + ? AS [ORDER__BY__001]
414 LEFT JOIN [books] [books]
415 ON [books].[owner] = [me].[id]
416 WHERE [books].[id] IS NOT NULL AND [me].[name] != ?
417 GROUP BY [me].[id], [me].[name]
420 WHERE [rno__row__index] >= ? AND [rno__row__index] <= ?
422 LEFT JOIN [books] [books]
423 ON [books].[owner] = [me].[id]
424 WHERE [books].[id] IS NOT NULL AND [me].[name] != ?
425 ORDER BY name + ? ASC, [me].[id]
429 [ { dbic_colname => 'test' }
431 [ { sqlt_datatype => 'varchar', sqlt_size => 100, dbic_colname => 'me.name' }
432 => 'somebogusstring' ],
435 ? [ { dbic_colname => 'test' } => 'xxx' ] # the extra re-order bind
436 : ([ $OFFSET => 7 ], [ $TOTAL => 9 ]) # parameterised RNO
439 [ { sqlt_datatype => 'varchar', sqlt_size => 100, dbic_colname => 'me.name' }
440 => 'somebogusstring' ],
441 [ { dbic_colname => 'test' }
446 is ($owners->page(1)->all, 3, "$test_type: has_many prefetch returns correct number of rows");
447 is ($owners->page(1)->count, 3, "$test_type: has-many prefetch returns correct count");
449 is ($owners->page(3)->count, 2, "$test_type: has-many prefetch returns correct count");
451 local $TODO = "Top-limit does not work when your limit ends up past the resultset"
452 if $dialect eq 'Top';
453 is ($owners->page(3)->all, 2, "$test_type: has_many prefetch returns correct number of rows");
454 is ($owners->page(3)->count_rs->next, 2, "$test_type: has-many prefetch returns correct count_rs");
458 # try a ->belongs_to direction (no select collapse, group_by should work)
459 my $books = $schema->resultset ('BooksInLibrary')->search (
461 'owner.name' => [qw/wiggle woggle/],
465 having => \['1 = ?', [ test => 1 ] ], #test having propagation
467 rows => 2, # 3 results total
468 order_by => [{ -desc => 'me.owner' }, 'me.id'],
469 unsafe_subselect_ok => 1,
474 $books->page(3)->as_query,
477 SELECT TOP 2147483647 [me].[id], [me].[source], [me].[owner], [me].[title], [me].[price],
478 [owner].[id], [owner].[name]
480 SELECT TOP 2147483647 [me].[id], [me].[source], [me].[owner], [me].[title], [me].[price]
482 SELECT TOP 2 [me].[id], [me].[source], [me].[owner], [me].[title], [me].[price]
484 SELECT TOP 6 [me].[id], [me].[source], [me].[owner], [me].[title], [me].[price]
486 JOIN [owners] [owner]
487 ON [owner].[id] = [me].[owner]
488 WHERE ( [owner].[name] = ? OR [owner].[name] = ? ) AND [source] = ?
489 GROUP BY [me].[id], [me].[source], [me].[owner], [me].[title], [me].[price]
491 ORDER BY [me].[owner] DESC, [me].[id]
493 ORDER BY [me].[owner] ASC, [me].[id] DESC
495 ORDER BY [me].[owner] DESC, [me].[id]
497 JOIN [owners] [owner]
498 ON [owner].[id] = [me].[owner]
499 WHERE ( [owner].[name] = ? OR [owner].[name] = ? ) AND [source] = ?
500 ORDER BY [me].[owner] DESC, [me].[id]
503 SELECT TOP 2147483647 [me].[id], [me].[source], [me].[owner], [me].[title], [me].[price],
504 [owner].[id], [owner].[name]
506 SELECT TOP 2147483647 [me].[id], [me].[source], [me].[owner], [me].[title], [me].[price]
508 SELECT [me].[id], [me].[source], [me].[owner], [me].[title], [me].[price],
509 ROW_NUMBER() OVER( ORDER BY [me].[owner] DESC, [me].[id] ) AS [rno__row__index]
511 SELECT [me].[id], [me].[source], [me].[owner], [me].[title], [me].[price]
513 JOIN [owners] [owner]
514 ON [owner].[id] = [me].[owner]
515 WHERE ( [owner].[name] = ? OR [owner].[name] = ? ) AND [source] = ?
516 GROUP BY [me].[id], [me].[source], [me].[owner], [me].[title], [me].[price]
520 WHERE [rno__row__index] >= ? AND [rno__row__index] <= ?
522 JOIN [owners] [owner]
523 ON [owner].[id] = [me].[owner]
524 WHERE ( [owner].[name] = ? OR [owner].[name] = ? ) AND [source] = ?
525 ORDER BY [me].[owner] DESC, [me].[id]
530 [ { sqlt_datatype => 'varchar', sqlt_size => 100, dbic_colname => 'owner.name' }
532 [ { sqlt_datatype => 'varchar', sqlt_size => 100, dbic_colname => 'owner.name' }
534 [ { sqlt_datatype => 'varchar', sqlt_size => 100, dbic_colname => 'source' }
536 [ { dbic_colname => 'test' }
542 : ( [ $OFFSET => 5 ], [ $TOTAL => 6 ] )
546 [ { sqlt_datatype => 'varchar', sqlt_size => 100, dbic_colname => 'owner.name' }
548 [ { sqlt_datatype => 'varchar', sqlt_size => 100, dbic_colname => 'owner.name' }
550 [ { sqlt_datatype => 'varchar', sqlt_size => 100, dbic_colname => 'source' }
555 is ($books->page(1)->all, 2, "$test_type: Prefetched grouped search returns correct number of rows");
556 is ($books->page(1)->count, 2, "$test_type: Prefetched grouped search returns correct count");
558 is ($books->page(2)->count, 1, "$test_type: Prefetched grouped search returns correct count");
560 local $TODO = "Top-limit does not work when your limit ends up past the resultset"
561 if $dialect eq 'Top';
562 is ($books->page(2)->all, 1, "$test_type: Prefetched grouped search returns correct number of rows");
563 is ($books->page(2)->count_rs->next, 1, "$test_type: Prefetched grouped search returns correct count_rs");
571 $schema->storage->dbh_do (sub {
572 my ($storage, $dbh) = @_;
573 eval { $dbh->do("DROP TABLE artist_guid") };
575 CREATE TABLE artist_guid (
576 artistid UNIQUEIDENTIFIER NOT NULL,
578 rank INT NOT NULL DEFAULT '13',
579 charfield CHAR(10) NULL,
580 a_guid UNIQUEIDENTIFIER,
581 primary key(artistid)
586 # start disconnected to make sure insert works on an un-reblessed storage
587 $schema = DBICTest::Schema->connect($dsn, $user, $pass, $opts);
591 $row = $schema->resultset('ArtistGUID')->create({ name => 'mtfnpy' })
592 } 'created a row with a GUID';
595 eval { $row->artistid },
596 'row has GUID PK col populated',
601 eval { $row->a_guid },
602 'row has a GUID col with auto_nextval populated',
606 my $row_from_db = $schema->resultset('ArtistGUID')
607 ->search({ name => 'mtfnpy' })->first;
609 is $row_from_db->artistid, $row->artistid,
610 'PK GUID round trip';
612 is $row_from_db->a_guid, $row->a_guid,
613 'NON-PK GUID round trip';
618 $schema->storage->dbh_do (sub {
619 my ($storage, $dbh) = @_;
620 eval { $dbh->do("DROP TABLE money_test") };
622 CREATE TABLE money_test (
623 id INT IDENTITY PRIMARY KEY,
630 my $freetds_and_dynamic_cursors = 1
631 if $opts_name eq 'use_dynamic_cursors' &&
632 $schema->storage->_using_freetds;
635 'these tests fail on freetds with dynamic cursors for some reason'
636 if $freetds_and_dynamic_cursors;
637 local $ENV{DBIC_NULLABLE_KEY_NOWARN} = 1
638 if $freetds_and_dynamic_cursors;
640 my $rs = $schema->resultset('Money');
644 $row = $rs->create({ amount => 100 });
645 } 'inserted a money value';
647 cmp_ok ((try { $rs->find($row->id)->amount })||0, '==', 100,
648 'money value round-trip');
651 $row->update({ amount => 200 });
652 } 'updated a money value';
654 cmp_ok ((try { $rs->find($row->id)->amount })||0, '==', 200,
655 'updated money value round-trip');
658 $row->update({ amount => undef });
659 } 'updated a money value to NULL';
661 is try { $rs->find($row->id)->amount }, undef,
662 'updated money value to NULL round-trip';
672 if (my $dbh = eval { $schema->storage->_dbh }) {
673 eval { $dbh->do("DROP TABLE $_") }
674 for qw/artist artist_guid money_test books owners/;