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