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