Got a failing test
[dbsrgits/DBIx-Class.git] / t / 746mssql.t
1 use strict;
2 use warnings;
3
4 use Test::More;
5 use Test::Exception;
6 use lib qw(t/lib);
7 use DBICTest;
8 use DBIC::SqlMakerTest;
9
10 my ($dsn, $user, $pass) = @ENV{map { "DBICTEST_MSSQL_ODBC_${_}" } qw/DSN USER PASS/};
11
12 plan skip_all => 'Set $ENV{DBICTEST_MSSQL_ODBC_DSN}, _USER and _PASS to run this test'
13   unless ($dsn && $user);
14
15 DBICTest::Schema->load_classes('ArtistGUID');
16 my $schema = DBICTest::Schema->connect($dsn, $user, $pass);
17
18 {
19   no warnings 'redefine';
20   my $connect_count = 0;
21   my $orig_connect = \&DBI::connect;
22   local *DBI::connect = sub { $connect_count++; goto &$orig_connect };
23
24   $schema->storage->ensure_connected;
25
26   is( $connect_count, 1, 'only one connection made');
27 }
28
29 isa_ok( $schema->storage, 'DBIx::Class::Storage::DBI::ODBC::Microsoft_SQL_Server' );
30
31 {
32   my $schema2 = $schema->connect ($schema->storage->connect_info);
33   ok (! $schema2->storage->connected, 'a re-connected cloned schema starts unconnected');
34 }
35
36 $schema->storage->dbh_do (sub {
37     my ($storage, $dbh) = @_;
38     eval { $dbh->do("DROP TABLE artist") };
39     $dbh->do(<<'SQL');
40 CREATE TABLE artist (
41    artistid INT IDENTITY NOT NULL,
42    name VARCHAR(100),
43    rank INT NOT NULL DEFAULT '13',
44    charfield CHAR(10) NULL,
45    primary key(artistid)
46 )
47 SQL
48 });
49
50 my %seen_id;
51
52 my @opts = (
53   { on_connect_call => 'use_dynamic_cursors' },
54   {},
55 );
56 my $new;
57
58 # test Auto-PK with different options
59 for my $opts (@opts) {
60   SKIP: {
61     $schema = DBICTest::Schema->connect($dsn, $user, $pass, $opts);
62
63     eval {
64       $schema->storage->ensure_connected
65     };
66     if ($@ =~ /dynamic cursors/) {
67       skip
68 'Dynamic Cursors not functional, tds_version 8.0 or greater required if using'.
69 ' FreeTDS', 1;
70     }
71
72     $schema->resultset('Artist')->search({ name => 'foo' })->delete;
73
74     $new = $schema->resultset('Artist')->create({ name => 'foo' });
75
76     ok($new->artistid > 0, "Auto-PK worked");
77   }
78 }
79
80 $seen_id{$new->artistid}++;
81
82 # test LIMIT support
83 for (1..6) {
84     $new = $schema->resultset('Artist')->create({ name => 'Artist ' . $_ });
85     is ( $seen_id{$new->artistid}, undef, "id for Artist $_ is unique" );
86     $seen_id{$new->artistid}++;
87 }
88
89 my $it = $schema->resultset('Artist')->search( {}, {
90     rows => 3,
91     order_by => 'artistid',
92 });
93
94 is( $it->count, 3, "LIMIT count ok" );
95 is( $it->next->name, "foo", "iterator->next ok" );
96 $it->next;
97 is( $it->next->name, "Artist 2", "iterator->next ok" );
98 is( $it->next, undef, "next past end of resultset ok" );
99
100 # test GUID columns
101
102 $schema->storage->dbh_do (sub {
103     my ($storage, $dbh) = @_;
104     eval { $dbh->do("DROP TABLE artist") };
105     $dbh->do(<<'SQL');
106 CREATE TABLE artist (
107    artistid UNIQUEIDENTIFIER NOT NULL,
108    name VARCHAR(100),
109    rank INT NOT NULL DEFAULT '13',
110    charfield CHAR(10) NULL,
111    a_guid UNIQUEIDENTIFIER,
112    primary key(artistid)
113 )
114 SQL
115 });
116
117 # start disconnected to make sure insert works on an un-reblessed storage
118 $schema = DBICTest::Schema->connect($dsn, $user, $pass);
119
120 my $row;
121 lives_ok {
122   $row = $schema->resultset('ArtistGUID')->create({ name => 'mtfnpy' })
123 } 'created a row with a GUID';
124
125 ok(
126   eval { $row->artistid },
127   'row has GUID PK col populated',
128 );
129 diag $@ if $@;
130
131 ok(
132   eval { $row->a_guid },
133   'row has a GUID col with auto_nextval populated',
134 );
135 diag $@ if $@;
136
137 my $row_from_db = $schema->resultset('ArtistGUID')
138   ->search({ name => 'mtfnpy' })->first;
139
140 is $row_from_db->artistid, $row->artistid,
141   'PK GUID round trip';
142
143 is $row_from_db->a_guid, $row->a_guid,
144   'NON-PK GUID round trip';
145
146 # test MONEY type
147 $schema->storage->dbh_do (sub {
148     my ($storage, $dbh) = @_;
149     eval { $dbh->do("DROP TABLE money_test") };
150     $dbh->do(<<'SQL');
151 CREATE TABLE money_test (
152    id INT IDENTITY PRIMARY KEY,
153    amount MONEY NULL
154 )
155 SQL
156 });
157
158 my $rs = $schema->resultset('Money');
159
160 lives_ok {
161   $row = $rs->create({ amount => 100 });
162 } 'inserted a money value';
163
164 cmp_ok $rs->find($row->id)->amount, '==', 100, 'money value round-trip';
165
166 lives_ok {
167   $row->update({ amount => 200 });
168 } 'updated a money value';
169
170 cmp_ok $rs->find($row->id)->amount, '==', 200,
171   'updated money value round-trip';
172
173 lives_ok {
174   $row->update({ amount => undef });
175 } 'updated a money value to NULL';
176
177 is $rs->find($row->id)->amount, undef,'updated money value to NULL round-trip';
178
179 $schema->storage->dbh_do (sub {
180     my ($storage, $dbh) = @_;
181     eval { $dbh->do("DROP TABLE Owners") };
182     eval { $dbh->do("DROP TABLE Books") };
183     $dbh->do(<<'SQL');
184 CREATE TABLE Books (
185    id INT IDENTITY (1, 1) NOT NULL,
186    source VARCHAR(100),
187    owner INT,
188    title VARCHAR(10),
189    price INT NULL
190 )
191
192 CREATE TABLE Owners (
193    id INT IDENTITY (1, 1) NOT NULL,
194    name VARCHAR(100),
195 )
196 SQL
197
198 });
199
200 lives_ok ( sub {
201   # start a new connection, make sure rebless works
202   my $schema = DBICTest::Schema->connect($dsn, $user, $pass);
203   $schema->populate ('Owners', [
204     [qw/id  name  /],
205     [qw/1   wiggle/],
206     [qw/2   woggle/],
207     [qw/3   boggle/],
208     [qw/4   fRIOUX/],
209     [qw/5   fRUE/],
210     [qw/6   fREW/],
211     [qw/7   fROOH/],
212     [qw/8   fISMBoC/],
213     [qw/9   station/],
214     [qw/10   mirror/],
215     [qw/11   dimly/],
216     [qw/12   face_to_face/],
217     [qw/13   icarus/],
218     [qw/14   dream/],
219     [qw/15   dyrstyggyr/],
220   ]);
221 }, 'populate with PKs supplied ok' );
222
223 lives_ok (sub {
224   # start a new connection, make sure rebless works
225   # test an insert with a supplied identity, followed by one without
226   my $schema = DBICTest::Schema->connect($dsn, $user, $pass);
227   for (1..2) {
228     my $id = $_ * 20 ;
229     $schema->resultset ('Owners')->create ({ id => $id, name => "troglodoogle $id" });
230     $schema->resultset ('Owners')->create ({ name => "troglodoogle " . ($id + 1) });
231   }
232 }, 'create with/without PKs ok' );
233
234 is ($schema->resultset ('Owners')->count, 19, 'owner rows really in db' );
235
236 lives_ok ( sub {
237   # start a new connection, make sure rebless works
238   my $schema = DBICTest::Schema->connect($dsn, $user, $pass);
239   $schema->populate ('BooksInLibrary', [
240     [qw/source  owner title   /],
241     [qw/Library 7     secrets10/],
242     [qw/Eatery  1     secrets2/],
243     [qw/Library 3     secrets4/],
244     [qw/Eatery  5     secrets8/],
245     [qw/Library 5     secrets7/],
246     [qw/Library 2     secrets3/],
247     [qw/Eatery  7     secrets11/],
248     [qw/Library 4     secrets6/],
249     [qw/Library 1     secrets0/],
250     [qw/Eatery  3     secrets5/],
251     [qw/Library 6     secrets9/],
252     [qw/Library 1     secrets1/],
253     [qw/Library 8     secrets12/],
254   ]);
255 }, 'populate without PKs supplied ok' );
256
257 # make sure ordered subselects work
258 {
259   my $book_owner_ids = $schema->resultset ('BooksInLibrary')
260                                ->search ({}, { join => 'owner', distinct => 1, order_by => { -desc => 'owner'} })
261                                 ->get_column ('owner');
262
263   my $owners = $schema->resultset ('Owners')->search ({
264     id => { -in => $book_owner_ids->as_query }
265   });
266
267   is ($owners->count, 8, 'Correct amount of book owners');
268   is ($owners->all, 8, 'Correct amount of book owner objects');
269 }
270
271 #
272 # try a prefetch on tables with identically named columns
273 #
274
275 # set quote char - make sure things work while quoted
276 $schema->storage->_sql_maker->{quote_char} = [qw/[ ]/];
277 $schema->storage->_sql_maker->{name_sep} = '.';
278
279 {
280   # try a ->has_many direction
281   my $owners = $schema->resultset ('Owners')->search (
282     {
283       'books.id' => { '!=', undef },
284       'me.name' => { '!=', 'somebogusstring' },
285     },
286     {
287       prefetch => 'books',
288       order_by => { -asc => \['name + ?', [ test => 'xxx' ]] }, # test bindvar propagation
289       rows     => 3,  # 8 results total
290     },
291   );
292
293   my ($sql, @bind) = @${$owners->page(3)->as_query};
294   is_deeply (
295     \@bind,
296     [ ([ 'me.name' => 'somebogusstring' ], [ test => 'xxx' ]) x 2 ],  # double because of the prefetch subq
297   );
298
299   is ($owners->page(1)->all, 3, 'has_many prefetch returns correct number of rows');
300   is ($owners->page(1)->count, 3, 'has-many prefetch returns correct count');
301
302   is ($owners->page(3)->all, 2, 'has_many prefetch returns correct number of rows');
303   is ($owners->page(3)->count, 2, 'has-many prefetch returns correct count');
304   is ($owners->page(3)->count_rs->next, 2, 'has-many prefetch returns correct count_rs');
305
306
307   # try a ->belongs_to direction (no select collapse, group_by should work)
308   my $books = $schema->resultset ('BooksInLibrary')->search (
309     {
310       'owner.name' => [qw/wiggle woggle/],
311     },
312     {
313       distinct => 1,
314       having => \['1 = ?', [ test => 1 ] ], #test having propagation
315       prefetch => 'owner',
316       rows     => 2,  # 3 results total
317       order_by => { -desc => 'owner' },
318     },
319   );
320
321   ($sql, @bind) = @${$books->page(3)->as_query};
322   is_deeply (
323     \@bind,
324     [
325       # inner
326       [ 'owner.name' => 'wiggle' ], [ 'owner.name' => 'woggle' ], [ source => 'Library' ], [ test => '1' ],
327       # outer
328       [ 'owner.name' => 'wiggle' ], [ 'owner.name' => 'woggle' ], [ source => 'Library' ],
329     ],
330   );
331
332   is ($books->page(1)->all, 2, 'Prefetched grouped search returns correct number of rows');
333   is ($books->page(1)->count, 2, 'Prefetched grouped search returns correct count');
334
335   is ($books->page(2)->all, 1, 'Prefetched grouped search returns correct number of rows');
336   is ($books->page(2)->count, 1, 'Prefetched grouped search returns correct count');
337   is ($books->page(2)->count_rs->next, 1, 'Prefetched grouped search returns correct count_rs');
338 }
339
340 # make sure right-join-side single-prefetch ordering limit works
341 {
342   my $rs = $schema->resultset ('BooksInLibrary')->search (
343     {
344       'owner.name' => { '!=', 'woggle' },
345     },
346     {
347       prefetch => 'owner',
348       order_by => 'owner.name',
349     }
350   );
351   # this is the order in which they should come from the above query
352   my @owner_names = qw/boggle fISMBoC fREW fRIOUX fROOH fRUE wiggle wiggle/;
353
354   is ($rs->all, 8, 'Correct amount of objects from right-sorted joined resultset');
355   is_deeply (
356     [map { $_->owner->name } ($rs->all) ],
357     \@owner_names,
358     'Rows were properly ordered'
359   );
360
361   my $limited_rs = $rs->search ({}, {rows => 7, offset => 2});
362   is ($limited_rs->count, 6, 'Correct count of limited right-sorted joined resultset');
363   is ($limited_rs->count_rs->next, 6, 'Correct count_rs of limited right-sorted joined resultset');
364
365   my $queries;
366   $schema->storage->debugcb(sub { $queries++; });
367   $schema->storage->debug(1);
368
369   is_deeply (
370     [map { $_->owner->name } ($limited_rs->all) ],
371     [@owner_names[2 .. 7]],
372     'Limited rows were properly ordered'
373   );
374   is ($queries, 1, 'Only one query with prefetch');
375
376   $schema->storage->debugcb(undef);
377   $schema->storage->debug(0);
378
379
380   is_deeply (
381     [map { $_->name } ($limited_rs->search_related ('owner')->all) ],
382     [@owner_names[2 .. 7]],
383     'Rows are still properly ordered after search_related'
384   );
385
386
387 # Just to aid bug-hunting, delete block before merging
388 {
389
390 =begin
391
392 Alan's SQL:
393
394       SELECT me.id, me.surveyor_id, me.survey_site_id, me.year, surveyor.id, surveyor.name, surveyor.email, surveyor.phone, surveyor.login, surveyor.password, surveyor.is_active, surveyor.is_verifier, surveyor.arm_length, surveyor.eye_height, surveyor.year_joined
395         FROM (
396           SELECT *
397             FROM (
398               SELECT orig_query.*, ROW_NUMBER() OVER( ORDER BY (SELECT(1)) ) AS rno__row__index
399                 FROM (
400                   SELECT me.id, me.surveyor_id, me.survey_site_id, me.year
401                     FROM (
402                       SELECT TOP 100 PERCENT me.id, me.surveyor_id, me.survey_site_id, me.year
403                         FROM surveyors_survey_sites me
404                         JOIN surveyors surveyor ON surveyor.id = me.surveyor_id
405                       ORDER BY surveyor.name
406                     ) me
407                 ) orig_query
408             ) rno_subq
409           WHERE rno__row__index BETWEEN 136 AND 150 
410         ) me
411         JOIN surveyors surveyor ON surveyor.id = me.surveyor_id
412       ORDER BY surveyor.name
413 =cut
414
415   is_same_sql_bind (
416     $limited_rs->as_query,
417     '(
418       SELECT TOP 100 PERCENT [me].[id], [me].[source], [me].[owner], [me].[title], [me].[price], [owner].[id], [owner].[name]
419         FROM (
420           SELECT *
421             FROM (
422               SELECT [me].*, ROW_NUMBER() OVER( ORDER BY (SELECT(1)) ) AS rno__row__index 
423                 FROM (
424                   SELECT [me].[id], [me].[source], [me].[owner], [me].[title], [me].[price]
425                     FROM (
426                       SELECT TOP 100 PERCENT [me].[id], [me].[source], [me].[owner], [me].[title], [me].[price]
427                         FROM [books] [me]
428                         JOIN [owners] [owner] ON [owner].[id] = [me].[owner]
429                       WHERE ( ( [owner].[name] != ? AND [source] = ? ) )
430                       ORDER BY [owner].[name]
431                     ) [me]
432                 ) [me]
433             ) rno_subq
434           WHERE rno__row__index BETWEEN 3 AND 9
435         ) [me]
436         JOIN [owners] [owner] ON [owner].[id] = [me].[owner]
437       WHERE ( ( [owner].[name] != ? AND [source] = ? ) )
438       ORDER BY [owner].[name]
439     )',
440     [ ([ 'owner.name' => 'woggle' ], [ source => 'Library' ]) x 2 ],
441     'Expected SQL executed',
442   );
443 }
444
445 }
446
447 done_testing;
448
449 # clean up our mess
450 END {
451   if (my $dbh = eval { $schema->storage->_dbh }) {
452     eval { $dbh->do("DROP TABLE $_") }
453       for qw/artist money_test Books Owners/;
454   }
455 }
456 # vim:sw=2 sts=2