check database driver dependencies for tests
[dbsrgits/DBIx-Class.git] / t / 74mssql.t
1 use strict;
2 use warnings;
3
4 # use this if you keep a copy of DBD::Sybase linked to FreeTDS somewhere else
5 BEGIN {
6   if (my $lib_dirs = $ENV{DBICTEST_MSSQL_PERL5LIB}) {
7     unshift @INC, $_ for split /:/, $lib_dirs;
8   }
9 }
10
11 use Test::More;
12 use Test::Exception;
13 use DBIx::Class::Optional::Dependencies ();
14 use lib qw(t/lib);
15 use DBICTest;
16
17 plan skip_all => 'Test needs ' . DBIx::Class::Optional::Dependencies->req_missing_for ('test_rdbms_mssql_sybase')
18   unless DBIx::Class::Optional::Dependencies->req_ok_for ('test_rdbms_mssql_sybase');
19
20 my ($dsn, $user, $pass) = @ENV{map { "DBICTEST_MSSQL_${_}" } qw/DSN USER PASS/};
21
22 plan skip_all => 'Set $ENV{DBICTEST_MSSQL_DSN}, _USER and _PASS to run this test'
23   unless ($dsn);
24
25 {
26   my $srv_ver = DBICTest::Schema->connect($dsn, $user, $pass)->storage->_server_info->{dbms_version};
27   ok ($srv_ver, 'Got a test server version on fresh schema: ' . ($srv_ver||'???') );
28 }
29
30 my $schema;
31
32 my $testdb_supports_placeholders = DBICTest::Schema->connect($dsn, $user, $pass)
33                                                     ->storage
34                                                      ->_supports_typeless_placeholders;
35 my @test_storages = (
36   $testdb_supports_placeholders ? 'DBI::Sybase::Microsoft_SQL_Server' : (),
37   'DBI::Sybase::Microsoft_SQL_Server::NoBindVars',
38 );
39
40 for my $storage_type (@test_storages) {
41   $schema = DBICTest::Schema->connect($dsn, $user, $pass);
42
43   if ($storage_type =~ /NoBindVars\z/) {
44     # since we want to use the nobindvar - disable the capability so the
45     # rebless happens to the correct class
46     $schema->storage->_use_typeless_placeholders (0);
47   }
48
49   local $ENV{DBIC_MSSQL_FREETDS_LOWVER_NOWARN} = 1; # disable nobindvars warning
50
51   $schema->storage->ensure_connected;
52
53   if ($storage_type =~ /NoBindVars\z/) {
54     is $schema->storage->disable_sth_caching, 1,
55       'prepare_cached disabled for NoBindVars';
56   }
57
58   isa_ok($schema->storage, "DBIx::Class::Storage::$storage_type");
59
60   SKIP: {
61     skip 'This version of DBD::Sybase segfaults on disconnect', 1 if DBD::Sybase->VERSION < 1.08;
62
63     # start disconnected to test _ping
64     $schema->storage->_dbh->disconnect;
65
66     lives_ok {
67       $schema->storage->dbh_do(sub { $_[1]->do('select 1') })
68     } '_ping works';
69   }
70
71   my $dbh = $schema->storage->dbh;
72
73   $dbh->do("IF OBJECT_ID('artist', 'U') IS NOT NULL
74       DROP TABLE artist");
75   $dbh->do("IF OBJECT_ID('cd', 'U') IS NOT NULL
76       DROP TABLE cd");
77
78   $dbh->do("CREATE TABLE artist (artistid INT IDENTITY PRIMARY KEY, name VARCHAR(100), rank INT DEFAULT '13', charfield CHAR(10) NULL);");
79   $dbh->do("CREATE TABLE cd (cdid INT IDENTITY PRIMARY KEY, artist INT,  title VARCHAR(100), year VARCHAR(100), genreid INT NULL, single_track INT NULL);");
80 # Just to test compat shim, Auto is in Core
81   $schema->class('Artist')->load_components('PK::Auto::MSSQL');
82
83 # Test PK
84   my $new = $schema->resultset('Artist')->create( { name => 'foo' } );
85   ok($new->artistid, "Auto-PK worked");
86
87 # Test LIMIT
88   for (1..6) {
89       $schema->resultset('Artist')->create( { name => 'Artist ' . $_, rank => $_ } );
90   }
91
92   my $it = $schema->resultset('Artist')->search( { },
93       { rows     => 3,
94         offset   => 2,
95         order_by => 'artistid'
96       }
97   );
98
99 # Test ? in data don't get treated as placeholders
100   my $cd = $schema->resultset('CD')->create( {
101       artist      => 1,
102       title       => 'Does this break things?',
103       year        => 2007,
104   } );
105   ok($cd->id, 'Not treating ? in data as placeholders');
106
107   is( $it->count, 3, "LIMIT count ok" );
108   ok( $it->next->name, "iterator->next ok" );
109   $it->next;
110   $it->next;
111   is( $it->next, undef, "next past end of resultset ok" );
112
113 # test MONEY column support
114   $schema->storage->dbh_do (sub {
115       my ($storage, $dbh) = @_;
116       eval { $dbh->do("DROP TABLE money_test") };
117       $dbh->do(<<'SQL');
118   CREATE TABLE money_test (
119      id INT IDENTITY PRIMARY KEY,
120      amount MONEY NULL
121   )
122 SQL
123    });
124
125    my $rs = $schema->resultset('Money');
126
127   my $row;
128   lives_ok {
129     $row = $rs->create({ amount => 100 });
130   } 'inserted a money value';
131
132   cmp_ok $rs->find($row->id)->amount, '==', 100, 'money value round-trip';
133
134   lives_ok {
135     $row->update({ amount => 200 });
136   } 'updated a money value';
137
138   cmp_ok $rs->find($row->id)->amount, '==', 200,
139     'updated money value round-trip';
140
141   lives_ok {
142     $row->update({ amount => undef });
143   } 'updated a money value to NULL';
144
145   is $rs->find($row->id)->amount,
146     undef, 'updated money value to NULL round-trip';
147
148   $rs->delete;
149
150   # test simple transaction with commit
151   lives_ok {
152     $schema->txn_do(sub {
153       $rs->create({ amount => 300 });
154     });
155   } 'simple transaction';
156
157   cmp_ok $rs->first->amount, '==', 300, 'committed';
158
159   $rs->reset;
160   $rs->delete;
161
162   # test rollback
163   throws_ok {
164     $schema->txn_do(sub {
165       $rs->create({ amount => 700 });
166       die 'mtfnpy';
167     });
168   } qr/mtfnpy/, 'simple failed txn';
169
170   is $rs->first, undef, 'rolled back';
171
172   $rs->reset;
173   $rs->delete;
174
175   # test multiple active statements
176   {
177     $rs->create({ amount => 800 + $_ }) for 1..3;
178
179     my @map = (
180       [ 'Artist 1', '801.00' ],
181       [ 'Artist 2', '802.00' ],
182       [ 'Artist 3', '803.00' ]
183     );
184
185     my $artist_rs = $schema->resultset('Artist')->search({
186       name => { -like => 'Artist %' }
187     });;
188
189     my $i = 0;
190
191     while (my $money_row = $rs->next) {
192       my $artist_row = $artist_rs->next;
193
194       is_deeply [ $artist_row->name, $money_row->amount ], $map[$i++],
195         'multiple active statements';
196     }
197     $rs->reset;
198     $rs->delete;
199   }
200
201   # test transaction handling on a disconnected handle
202   my $wrappers = {
203     no_transaction => sub { shift->() },
204     txn_do => sub { my $code = shift; $schema->txn_do(sub { $code->() } ) },
205     txn_begin => sub { $schema->txn_begin; shift->(); $schema->txn_commit },
206     txn_guard => sub { my $g = $schema->txn_scope_guard; shift->(); $g->commit },
207   };
208   for my $wrapper (keys %$wrappers) {
209     $rs->delete;
210
211     # a reconnect should trigger on next action
212     $schema->storage->_get_dbh->disconnect;
213
214     lives_and {
215       $wrappers->{$wrapper}->( sub {
216         $rs->create({ amount => 900 + $_ }) for 1..3;
217       });
218       is $rs->count, 3;
219     } "transaction on disconnected handle with $wrapper wrapper";
220   }
221
222   TODO: {
223     local $TODO = 'Transaction handling with multiple active statements will '
224                  .'need eager cursor support.';
225
226     # test transaction handling on a disconnected handle with multiple active
227     # statements
228     my $wrappers = {
229       no_transaction => sub { shift->() },
230       txn_do => sub { my $code = shift; $schema->txn_do(sub { $code->() } ) },
231       txn_begin => sub { $schema->txn_begin; shift->(); $schema->txn_commit },
232       txn_guard => sub { my $g = $schema->txn_scope_guard; shift->(); $g->commit },
233     };
234     for my $wrapper (keys %$wrappers) {
235       $rs->reset;
236       $rs->delete;
237       $rs->create({ amount => 1000 + $_ }) for (1..3);
238
239       my $artist_rs = $schema->resultset('Artist')->search({
240         name => { -like => 'Artist %' }
241       });;
242
243       $rs->next;
244
245       my $map = [ ['Artist 1', '1002.00'], ['Artist 2', '1003.00'] ];
246
247       lives_and {
248         my @results;
249
250         $wrappers->{$wrapper}->( sub {
251           while (my $money = $rs->next) {
252             my $artist = $artist_rs->next;
253             push @results, [ $artist->name, $money->amount ];
254           };
255         });
256
257         is_deeply \@results, $map;
258       } "transactions with multiple active statement with $wrapper wrapper";
259     }
260   }
261
262   # test RNO detection when version detection fails
263   SKIP: {
264     my $storage = $schema->storage;
265     my $version = $storage->_server_info->{normalized_dbms_version};
266
267     skip 'could not detect SQL Server version', 1 if not defined $version;
268
269     my $have_rno = $version >= 9 ? 1 : 0;
270
271     local $storage->{_dbh_details}{info} = {}; # delete cache
272
273     my $rno_detected =
274       ($storage->sql_limit_dialect eq 'RowNumberOver') ? 1 : 0;
275
276     ok (($have_rno == $rno_detected),
277       'row_number() over support detected correctly');
278   }
279
280   {
281     my $schema = DBICTest::Schema->clone;
282     $schema->connection($dsn, $user, $pass);
283
284     like $schema->storage->sql_maker->{limit_dialect},
285       qr/^(?:Top|RowNumberOver)\z/,
286       'sql_maker is correct on unconnected schema';
287   }
288 }
289
290 # test op-induced autoconnect
291 lives_ok (sub {
292
293   my $schema =  DBICTest::Schema->clone;
294   $schema->connection($dsn, $user, $pass);
295
296   my $artist = $schema->resultset ('Artist')->search ({}, { order_by => 'artistid' })->next;
297   is ($artist->id, 1, 'Artist retrieved successfully');
298 }, 'Query-induced autoconnect works');
299
300 # test AutoCommit=0
301 {
302   local $ENV{DBIC_UNSAFE_AUTOCOMMIT_OK} = 1;
303   my $schema2 = DBICTest::Schema->connect($dsn, $user, $pass, { AutoCommit => 0 });
304
305   my $rs = $schema2->resultset('Money');
306
307   $rs->delete;
308   $schema2->txn_commit;
309
310   is $rs->count, 0, 'initially empty'
311     || diag ('Found row with amount ' . $_->amount) for $rs->all;
312
313   $rs->create({ amount => 3000 });
314   $schema2->txn_rollback;
315
316   is $rs->count, 0, 'rolled back in AutoCommit=0'
317     || diag ('Found row with amount ' . $_->amount) for $rs->all;
318
319   $rs->create({ amount => 4000 });
320   $schema2->txn_commit;
321
322   cmp_ok $rs->first->amount, '==', 4000, 'committed in AutoCommit=0';
323 }
324
325 done_testing;
326
327 # clean up our mess
328 END {
329   if (my $dbh = eval { $schema->storage->dbh }) {
330     $dbh->do("IF OBJECT_ID('artist', 'U') IS NOT NULL DROP TABLE artist");
331     $dbh->do("IF OBJECT_ID('cd', 'U') IS NOT NULL DROP TABLE cd");
332     $dbh->do("IF OBJECT_ID('money_test', 'U') IS NOT NULL DROP TABLE money_test");
333   }
334 }