Resolve $rsrc instance duality on metadata traversal
[dbsrgits/DBIx-Class.git] / t / 74mssql.t
1 BEGIN { do "./t/lib/ANFANG.pm" or die ( $@ || $! ) }
2 use DBIx::Class::Optional::Dependencies -skip_all_without => 'test_rdbms_mssql_sybase';
3
4 use strict;
5 use warnings;
6
7 use Test::More;
8 use Test::Exception;
9 use Scalar::Util 'weaken';
10 use DBIx::Class::_Util 'sigwarn_silencer';
11
12 use DBICTest;
13
14 my ($dsn, $user, $pass) = @ENV{map { "DBICTEST_MSSQL_${_}" } qw/DSN USER PASS/};
15 {
16   my $srv_ver = DBICTest::Schema->connect($dsn, $user, $pass)->storage->_server_info->{dbms_version};
17   ok ($srv_ver, 'Got a test server version on fresh schema: ' . ($srv_ver||'???') );
18 }
19
20 my $schema;
21
22 my $testdb_supports_placeholders = DBICTest::Schema->connect($dsn, $user, $pass)
23                                                     ->storage
24                                                      ->_supports_typeless_placeholders;
25 my @test_storages = (
26   $testdb_supports_placeholders ? 'DBI::Sybase::Microsoft_SQL_Server' : (),
27   'DBI::Sybase::Microsoft_SQL_Server::NoBindVars',
28 );
29
30 for my $storage_type (@test_storages) {
31   $schema = DBICTest::Schema->connect($dsn, $user, $pass);
32
33   if ($storage_type =~ /NoBindVars\z/) {
34     # since we want to use the nobindvar - disable the capability so the
35     # rebless happens to the correct class
36     $schema->storage->_use_typeless_placeholders (0);
37   }
38
39   local $ENV{DBIC_MSSQL_FREETDS_LOWVER_NOWARN} = 1; # disable nobindvars warning
40
41   $schema->storage->ensure_connected;
42
43   if ($storage_type =~ /NoBindVars\z/) {
44     is $schema->storage->disable_sth_caching, 1,
45       'prepare_cached disabled for NoBindVars';
46   }
47
48   isa_ok($schema->storage, "DBIx::Class::Storage::$storage_type");
49
50   SKIP: {
51     skip 'This version of DBD::Sybase segfaults on disconnect', 1 if DBD::Sybase->VERSION < 1.08;
52
53     # start disconnected to test _ping
54     $schema->storage->_dbh->disconnect;
55
56     lives_ok {
57       $schema->storage->dbh_do(sub { $_[1]->do('select 1') })
58     } '_ping works';
59   }
60
61   my $dbh = $schema->storage->dbh;
62
63   $dbh->do("IF OBJECT_ID('artist', 'U') IS NOT NULL
64       DROP TABLE artist");
65   $dbh->do("IF OBJECT_ID('cd', 'U') IS NOT NULL
66       DROP TABLE cd");
67
68   $dbh->do("CREATE TABLE artist (artistid INT IDENTITY PRIMARY KEY, name VARCHAR(100), rank INT DEFAULT '13', charfield CHAR(10) NULL);");
69   $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);");
70 # Just to test compat shim, Auto is in Core
71   $schema->class('Artist')->load_components('PK::Auto::MSSQL');
72
73 # Test PK
74   my $new = $schema->resultset('Artist')->create( { name => 'foo' } );
75   ok($new->artistid, "Auto-PK worked");
76
77 # Test LIMIT
78   for (1..6) {
79       $schema->resultset('Artist')->create( { name => 'Artist ' . $_, rank => $_ } );
80   }
81
82   my $it = $schema->resultset('Artist')->search( { },
83       { rows     => 3,
84         offset   => 2,
85         order_by => 'artistid'
86       }
87   );
88
89 # Test ? in data don't get treated as placeholders
90   my $cd = $schema->resultset('CD')->create( {
91       artist      => 1,
92       title       => 'Does this break things?',
93       year        => 2007,
94   } );
95   ok($cd->id, 'Not treating ? in data as placeholders');
96
97   is( $it->count, 3, "LIMIT count ok" );
98   ok( $it->next->name, "iterator->next ok" );
99   $it->next;
100   $it->next;
101   is( $it->next, undef, "next past end of resultset ok" );
102
103 # test MONEY column support
104   $schema->storage->dbh_do (sub {
105       my ($storage, $dbh) = @_;
106       eval { $dbh->do("DROP TABLE money_test") };
107       $dbh->do(<<'SQL');
108   CREATE TABLE money_test (
109      id INT IDENTITY PRIMARY KEY,
110      amount MONEY NULL
111   )
112 SQL
113    });
114
115   my $rs = $schema->resultset('Money');
116   weaken(my $rs_cp = $rs);  # nested closure refcounting is an utter mess in perl
117
118   my $row;
119   lives_ok {
120     $row = $rs->create({ amount => 100 });
121   } 'inserted a money value';
122
123   cmp_ok $rs->find($row->id)->amount, '==', 100, 'money value round-trip';
124
125   lives_ok {
126     $row->update({ amount => 200 });
127   } 'updated a money value';
128
129   cmp_ok $rs->find($row->id)->amount, '==', 200,
130     'updated money value round-trip';
131
132   lives_ok {
133     $row->update({ amount => undef });
134   } 'updated a money value to NULL';
135
136   is $rs->find($row->id)->amount,
137     undef, 'updated money value to NULL round-trip';
138
139   $rs->delete;
140
141   # test simple transaction with commit
142   lives_ok {
143     $schema->txn_do(sub {
144       $rs_cp->create({ amount => 300 });
145     });
146   } 'simple transaction';
147
148   cmp_ok $rs->first->amount, '==', 300, 'committed';
149
150   $rs->reset;
151   $rs->delete;
152
153   # test rollback
154   throws_ok {
155     $schema->txn_do(sub {
156       $rs_cp->create({ amount => 700 });
157       die 'mtfnpy';
158     });
159   } qr/mtfnpy/, 'simple failed txn';
160
161   is $rs->first, undef, 'rolled back';
162
163   $rs->reset;
164   $rs->delete;
165
166   # test multiple active statements
167   {
168     $rs->create({ amount => 800 + $_ }) for 1..3;
169
170     my @map = (
171       [ 'Artist 1', '801.00' ],
172       [ 'Artist 2', '802.00' ],
173       [ 'Artist 3', '803.00' ]
174     );
175
176     my $artist_rs = $schema->resultset('Artist')->search({
177       name => { -like => 'Artist %' }
178     });;
179
180     my $i = 0;
181
182     while (my $money_row = $rs->next) {
183       my $artist_row = $artist_rs->next;
184
185       is_deeply [ $artist_row->name, $money_row->amount ], $map[$i++],
186         'multiple active statements';
187     }
188     $rs->reset;
189     $rs->delete;
190   }
191
192   my $wrappers = {
193     no_transaction => sub { shift->() },
194     txn_do => sub { my $code = shift; $schema->txn_do(sub { $code->() } ) },
195     txn_begin => sub { $schema->txn_begin; shift->(); $schema->txn_commit },
196     txn_guard => sub { my $g = $schema->txn_scope_guard; shift->(); $g->commit },
197   };
198
199   # test transaction handling on a disconnected handle
200   for my $wrapper (keys %$wrappers) {
201     $rs->delete;
202
203     # a reconnect should trigger on next action
204     $schema->storage->_get_dbh->disconnect;
205
206
207     lives_ok {
208       $wrappers->{$wrapper}->( sub {
209         $rs_cp->create({ amount => 900 + $_ }) for 1..3;
210       });
211       is $rs->count, 3;
212     } "transaction on disconnected handle with $wrapper wrapper";
213   }
214
215   # test transaction handling on a disconnected handle with multiple active
216   # statements
217   for my $wrapper (keys %$wrappers) {
218     $schema->storage->disconnect;
219     $rs->delete;
220     $rs->reset;
221     $rs->create({ amount => 1000 + $_ }) for (1..3);
222
223     my $artist_rs = $schema->resultset('Artist')->search({
224       name => { -like => 'Artist %' }
225     });;
226
227     $rs->next;
228
229     my $map = [ ['Artist 1', '1002.00'], ['Artist 2', '1003.00'] ];
230
231     weaken(my $a_rs_cp = $artist_rs);
232
233     $wrapper ne 'no_transaction'
234       and
235     (
236       local $TODO = 'Transaction handling with multiple active statements will '
237                    .'need eager cursor support.',
238
239       local local $SIG{__WARN__} = sigwarn_silencer qr/disconnect invalidates .+? active statement/
240     );
241
242     lives_ok {
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 }