Rewrite txn_do and dbh_do to use a (hidden for now) blockrunner
[dbsrgits/DBIx-Class.git] / t / 751msaccess.t
CommitLineData
726c8f65 1use strict;
2use warnings;
3
4use Test::More;
5use Test::Exception;
6use Scope::Guard ();
7use Try::Tiny;
199fbc45 8use DBIx::Class::Optional::Dependencies ();
726c8f65 9use lib qw(t/lib);
10use DBICTest;
696ba760 11use DBIC::DebugObj ();
12use DBIC::SqlMakerTest;
726c8f65 13
199fbc45 14my ($dsn, $user, $pass) = @ENV{map { "DBICTEST_MSACCESS_ODBC_${_}" } qw/DSN USER PASS/};
15my ($dsn2, $user2, $pass2) = @ENV{map { "DBICTEST_MSACCESS_ADO_${_}" } qw/DSN USER PASS/};
16
17plan skip_all => 'Test needs ' .
18 (join ' or ', map { $_ ? $_ : () }
19 DBIx::Class::Optional::Dependencies->req_missing_for('test_rdbms_msaccess_odbc'),
20 DBIx::Class::Optional::Dependencies->req_missing_for('test_rdbms_msaccess_ado'))
21 unless
22 $dsn && DBIx::Class::Optional::Dependencies->req_ok_for('test_rdbms_msaccess_odbc')
23 or
24 $dsn2 && DBIx::Class::Optional::Dependencies->req_ok_for('test_rdbms_msaccess_ado')
25 or
26 (not $dsn || $dsn2);
27
726c8f65 28DBICTest::Schema->load_classes('ArtistGUID');
29
30# Example DSNs (32bit only):
31# dbi:ODBC:driver={Microsoft Access Driver (*.mdb, *.accdb)};dbq=C:\Users\rkitover\Documents\access_sample.accdb
32# dbi:ADO:Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\rkitover\Documents\access_sample.accdb
33# dbi:ADO:Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\rkitover\Documents\access_sample.accdb;Persist Security Info=False'
34
726c8f65 35plan skip_all => <<'EOF' unless $dsn || $dsn2;
076bd599 36Set $ENV{DBICTEST_MSACCESS_ODBC_DSN} and/or $ENV{DBICTEST_MSACCESS_ADO_DSN} (and optionally _USER and _PASS) to run these tests.
37Warning: this test drops and creates the tables 'artist', 'cd', 'bindtype_test' and 'artist_guid'.
726c8f65 38EOF
39
726c8f65 40my @info = (
41 [ $dsn, $user || '', $pass || '' ],
42 [ $dsn2, $user2 || '', $pass2 || '' ],
43);
44
45my $schema;
46
47foreach my $info (@info) {
48 my ($dsn, $user, $pass) = @$info;
49
50 next unless $dsn;
51
52# Check that we can connect without any options.
53 $schema = DBICTest::Schema->connect($dsn, $user, $pass);
54 lives_ok {
55 $schema->storage->ensure_connected;
56 } 'connection without any options';
57
58 my %binstr = ( 'small' => join('', map { chr($_) } ( 1 .. 127 )) );
59 $binstr{'large'} = $binstr{'small'} x 1024;
60
61 my $maxloblen = length $binstr{'large'};
62
63 $schema = DBICTest::Schema->connect($dsn, $user, $pass, {
64 quote_names => 1,
65 auto_savepoint => 1,
66 LongReadLen => $maxloblen,
67 });
68
69 my $guard = Scope::Guard->new(\&cleanup);
70
71 my $dbh = $schema->storage->dbh;
72
73 # turn off warnings for OLE exception from ADO about nonexistant table
74 eval { local $^W = 0; $dbh->do("DROP TABLE artist") };
75
76 $dbh->do(<<EOF);
77 CREATE TABLE artist (
78 artistid AUTOINCREMENT PRIMARY KEY,
79 name VARCHAR(255) NULL,
80 charfield CHAR(10) NULL,
81 rank INT NULL
82 )
83EOF
84
85 my $ars = $schema->resultset('Artist');
86 is ( $ars->count, 0, 'No rows at first' );
87
88# test primary key handling
89 my $new = $ars->create({ name => 'foo' });
90 ok($new->artistid, "Auto-PK worked");
91
92 my $first_artistid = $new->artistid;
93
94# test explicit key spec
95 $new = $ars->create ({ name => 'bar', artistid => 66 });
96 is($new->artistid, 66, 'Explicit PK worked');
97 $new->discard_changes;
98 is($new->artistid, 66, 'Explicit PK assigned');
99
100# test joins
101 eval { local $^W = 0; $dbh->do("DROP TABLE cd") };
102
103 $dbh->do(<<EOF);
104 CREATE TABLE cd (
105 cdid AUTOINCREMENT PRIMARY KEY,
106 artist INTEGER NULL,
107 title VARCHAR(255) NULL,
108 [year] CHAR(4) NULL,
109 genreid INTEGER NULL,
110 single_track INTEGER NULL
111 )
112EOF
113
114 $dbh->do(<<EOF);
115 CREATE TABLE track (
116 trackid AUTOINCREMENT PRIMARY KEY,
117 cd INTEGER REFERENCES cd(cdid),
118 [position] INTEGER,
119 title VARCHAR(255),
120 last_updated_on DATETIME,
121 last_updated_at DATETIME
122 )
123EOF
124
125 my $cd = $schema->resultset('CD')->create({
126 artist => $first_artistid,
127 title => 'Some Album',
128 });
129
130# one-step join
131 my $joined_artist = $schema->resultset('Artist')->search({
132 artistid => $first_artistid,
133 }, {
134 join => [ 'cds' ],
135 '+select' => [ 'cds.title' ],
136 '+as' => [ 'cd_title' ],
137 })->next;
138
139 is $joined_artist->get_column('cd_title'), 'Some Album',
140 'one-step join works';
141
142# two-step join
143 my $track = $schema->resultset('Track')->create({
144 cd => $cd->cdid,
145 position => 1,
146 title => 'my track',
147 });
148
696ba760 149 my ($sql, @bind);
150
726c8f65 151 my $joined_track = try {
696ba760 152 local $schema->storage->{debug} = 1;
153 local $schema->storage->{debugobj} = DBIC::DebugObj->new(\$sql, \@bind);
154
726c8f65 155 $schema->resultset('Artist')->search({
156 artistid => $first_artistid,
157 }, {
158 join => [{ cds => 'tracks' }],
159 '+select' => [ 'tracks.title' ],
160 '+as' => [ 'track_title' ],
161 })->next;
162 }
163 catch {
696ba760 164 diag "Could not execute two-step left join: $_";
726c8f65 165 };
166
696ba760 167 s/^'//, s/'\z// for @bind;
168
169 is_same_sql_bind(
170 $sql,
171 \@bind,
172 'SELECT [me].[artistid], [me].[name], [me].[rank], [me].[charfield], [tracks].[title] FROM ( ( [artist] [me] LEFT JOIN cd [cds] ON [cds].[artist] = [me].[artistid] ) LEFT JOIN [track] [tracks] ON [tracks].[cd] = [cds].[cdid] ) WHERE ( [artistid] = ? )',
173 [1],
174 'correct SQL for two-step left join',
175 );
176
726c8f65 177 is try { $joined_track->get_column('track_title') }, 'my track',
696ba760 178 'two-step left join works';
179
180 ($sql, @bind) = ();
181
182 $joined_artist = try {
183 local $schema->storage->{debug} = 1;
184 local $schema->storage->{debugobj} = DBIC::DebugObj->new(\$sql, \@bind);
185
186 $schema->resultset('Track')->search({
187 trackid => $track->trackid,
188 }, {
189 join => [{ cd => 'artist' }],
190 '+select' => [ 'artist.name' ],
191 '+as' => [ 'artist_name' ],
192 })->next;
193 }
194 catch {
195 diag "Could not execute two-step inner join: $_";
196 };
197
198 s/^'//, s/'\z// for @bind;
199
200 is_same_sql_bind(
201 $sql,
202 \@bind,
203 'SELECT [me].[trackid], [me].[cd], [me].[position], [me].[title], [me].[last_updated_on], [me].[last_updated_at], [artist].[name] FROM ( ( [track] [me] INNER JOIN cd [cd] ON [cd].[cdid] = [me].[cd] ) INNER JOIN [artist] [artist] ON [artist].[artistid] = [cd].[artist] ) WHERE ( [trackid] = ? )',
204 [$track->trackid],
205 'correct SQL for two-step inner join',
206 );
207
208 is try { $joined_artist->get_column('artist_name') }, 'foo',
209 'two-step inner join works';
726c8f65 210
211# test basic transactions
212 $schema->txn_do(sub {
213 $ars->create({ name => 'transaction_commit' });
214 });
215 ok($ars->search({ name => 'transaction_commit' })->first,
216 'transaction committed');
217 $ars->search({ name => 'transaction_commit' })->delete,
218 throws_ok {
219 $schema->txn_do(sub {
220 $ars->create({ name => 'transaction_rollback' });
221 die 'rolling back';
222 });
223 } qr/rolling back/, 'rollback executed';
224 is $ars->search({ name => 'transaction_rollback' })->first, undef,
225 'transaction rolled back';
226
227# test two-phase commit and inner transaction rollback from nested transactions
228 $schema->txn_do(sub {
229 $ars->create({ name => 'in_outer_transaction' });
230 $schema->txn_do(sub {
231 $ars->create({ name => 'in_inner_transaction' });
232 });
233 ok($ars->search({ name => 'in_inner_transaction' })->first,
234 'commit from inner transaction visible in outer transaction');
235 throws_ok {
236 $schema->txn_do(sub {
237 $ars->create({ name => 'in_inner_transaction_rolling_back' });
238 die 'rolling back inner transaction';
239 });
240 } qr/rolling back inner transaction/, 'inner transaction rollback executed';
241 });
242 ok($ars->search({ name => 'in_outer_transaction' })->first,
243 'commit from outer transaction');
244 ok($ars->search({ name => 'in_inner_transaction' })->first,
245 'commit from inner transaction');
246 is $ars->search({ name => 'in_inner_transaction_rolling_back' })->first,
247 undef,
248 'rollback from inner transaction';
249 $ars->search({ name => 'in_outer_transaction' })->delete;
250 $ars->search({ name => 'in_inner_transaction' })->delete;
251
252# test populate
253 lives_ok (sub {
254 my @pop;
255 for (1..2) {
256 push @pop, { name => "Artist_$_" };
257 }
258 $ars->populate (\@pop);
259 });
260
261# test populate with explicit key
262 lives_ok (sub {
263 my @pop;
264 for (1..2) {
265 push @pop, { name => "Artist_expkey_$_", artistid => 100 + $_ };
266 }
267 $ars->populate (\@pop);
268 });
269
270# count what we did so far
271 is ($ars->count, 6, 'Simple count works');
272
273# test LIMIT support
274# not testing offset because access only supports TOP
275 my $lim = $ars->search( {},
276 {
277 rows => 2,
278 offset => 0,
279 order_by => 'artistid'
280 }
281 );
282 is( $lim->count, 2, 'ROWS+OFFSET count ok' );
283 is( $lim->all, 2, 'Number of ->all objects matches count' );
284
285# test iterator
286 $lim->reset;
287 is( $lim->next->artistid, 1, "iterator->next ok" );
288 is( $lim->next->artistid, 66, "iterator->next ok" );
289 is( $lim->next, undef, "next past end of resultset ok" );
290
291# test empty insert
292 my $current_artistid = $ars->search({}, {
293 select => [ { max => 'artistid' } ], as => ['artistid']
294 })->first->artistid;
295
296 my $row;
297 lives_ok { $row = $ars->create({}) }
298 'empty insert works';
299
300 $row->discard_changes;
301
302 is $row->artistid, $current_artistid+1,
303 'empty insert generated correct PK';
304
305# test that autoinc column still works after empty insert
306 $row = $ars->create({ name => 'after_empty_insert' });
307
308 is $row->artistid, $current_artistid+2,
309 'autoincrement column functional aftear empty insert';
310
311# test blobs (stolen from 73oracle.t)
312
313# turn off horrendous binary DBIC_TRACE output
314 {
315 local $schema->storage->{debug} = 0;
316
317 eval { local $^W = 0; $dbh->do('DROP TABLE bindtype_test') };
318 $dbh->do(qq[
319 CREATE TABLE bindtype_test
320 (
321 id INT NOT NULL PRIMARY KEY,
322 bytea INT NULL,
323 blob IMAGE NULL,
324 clob TEXT NULL,
325 a_memo MEMO NULL
326 )
327 ],{ RaiseError => 1, PrintError => 1 });
328
329 my $rs = $schema->resultset('BindType');
330 my $id = 0;
331
332 foreach my $type (qw( blob clob a_memo )) {
333 foreach my $size (qw( small large )) {
334 SKIP: {
335 skip 'TEXT columns not cast to MEMO over ODBC', 2
336 if $type eq 'clob' && $size eq 'large' && $dsn =~ /:ODBC:/;
337
338 $id++;
339
340 lives_ok { $rs->create( { 'id' => $id, $type => $binstr{$size} } ) }
341 "inserted $size $type without dying" or next;
342
343 my $from_db = eval { $rs->find($id)->$type } || '';
344 diag $@ if $@;
345
346 ok($from_db eq $binstr{$size}, "verified inserted $size $type" )
347 or do {
348 my $hexdump = sub {
349 join '', map sprintf('%02X', ord), split //, shift
350 };
351 diag 'Got: ', "\n", substr($hexdump->($from_db),0,255), '...',
352 substr($hexdump->($from_db),-255);
353 diag 'Size: ', length($from_db);
354 diag 'Expected Size: ', length($binstr{$size});
355 diag 'Expected: ', "\n",
356 substr($hexdump->($binstr{$size}), 0, 255),
357 "...", substr($hexdump->($binstr{$size}),-255);
358 };
359 }
360 }
361 }
362# test IMAGE update
363 lives_ok {
364 $rs->search({ id => 0 })->update({ blob => $binstr{small} });
365 } 'updated IMAGE to small binstr without dying';
366
367 lives_ok {
368 $rs->search({ id => 0 })->update({ blob => $binstr{large} });
369 } 'updated IMAGE to large binstr without dying';
370 }
371
372# test GUIDs (and the cursor GUID fixup stuff for ADO)
373
374 require Data::GUID;
375 $schema->storage->new_guid(sub { Data::GUID->new->as_string });
376
377 local $schema->source('ArtistGUID')->column_info('artistid')->{data_type}
378 = 'guid';
379
380 local $schema->source('ArtistGUID')->column_info('a_guid')->{data_type}
381 = 'guid';
382
383 $schema->storage->dbh_do (sub {
384 my ($storage, $dbh) = @_;
385 eval { local $^W = 0; $dbh->do("DROP TABLE artist_guid") };
386 $dbh->do(<<"SQL");
387CREATE TABLE artist_guid (
388 artistid GUID NOT NULL,
389 name VARCHAR(100),
390 rank INT NULL,
391 charfield CHAR(10) NULL,
392 a_guid GUID,
393 primary key(artistid)
394)
395SQL
396 });
397
398 lives_ok {
399 $row = $schema->resultset('ArtistGUID')->create({ name => 'mtfnpy' })
400 } 'created a row with a GUID';
401
402 ok(
403 eval { $row->artistid },
404 'row has GUID PK col populated',
405 );
406 diag $@ if $@;
407
408 ok(
409 eval { $row->a_guid },
410 'row has a GUID col with auto_nextval populated',
411 );
412 diag $@ if $@;
413
414 my $row_from_db = $schema->resultset('ArtistGUID')
415 ->search({ name => 'mtfnpy' })->first;
416
417 is $row_from_db->artistid, $row->artistid,
418 'PK GUID round trip (via ->search->next)';
419
420 is $row_from_db->a_guid, $row->a_guid,
421 'NON-PK GUID round trip (via ->search->next)';
422
423 $row_from_db = $schema->resultset('ArtistGUID')
424 ->find($row->artistid);
425
426 is $row_from_db->artistid, $row->artistid,
427 'PK GUID round trip (via ->find)';
428
429 is $row_from_db->a_guid, $row->a_guid,
430 'NON-PK GUID round trip (via ->find)';
431
432 ($row_from_db) = $schema->resultset('ArtistGUID')
433 ->search({ name => 'mtfnpy' })->all;
434
435 is $row_from_db->artistid, $row->artistid,
436 'PK GUID round trip (via ->search->all)';
437
438 is $row_from_db->a_guid, $row->a_guid,
439 'NON-PK GUID round trip (via ->search->all)';
440}
441
442done_testing;
443
444sub cleanup {
445 if (my $storage = eval { $schema->storage }) {
446 # cannot drop a table if it has been used, have to reconnect first
447 $schema->storage->disconnect;
448 local $^W = 0; # for ADO OLE exceptions
449 $schema->storage->dbh->do("DROP TABLE $_")
450 for qw/artist track cd bindtype_test artist_guid/;
451 }
452}
453
454# vim:sts=2 sw=2: