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