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