Added supports() and rewrote the tests so that Engine::DBI doesn't run the transactio...
[dbsrgits/DBM-Deep.git] / lib / DBM / Deep.pm
CommitLineData
ffed8b01 1package DBM::Deep;
2
2120a181 3use 5.006_000;
460b1067 4
ffed8b01 5use strict;
065b45be 6use warnings FATAL => 'all';
8b957036 7
d426259c 8our $VERSION = q(1.0015);
86867f3a 9
ffed8b01 10use Scalar::Util ();
ffed8b01 11
a4d36ff6 12use DBM::Deep::Engine::DBI ();
51e9eee3 13use DBM::Deep::Engine::File ();
95967a5e 14
4f0f6fff 15use DBM::Deep::SQL::Util;
16use DBM::Deep::SQL::Array;
17use DBM::Deep::SQL::Hash;
18
c57b19c6 19use overload
20 '""' => sub { overload::StrVal( $_[0] ) },
21 fallback => 1;
22
6e6789b0 23use constant DEBUG => 0;
24
2120a181 25sub TYPE_HASH () { DBM::Deep::Engine->SIG_HASH }
26sub TYPE_ARRAY () { DBM::Deep::Engine->SIG_ARRAY }
ffed8b01 27
2120a181 28# This is used in all the children of this class in their TIE<type> methods.
0ca7ea98 29sub _get_args {
30 my $proto = shift;
31
32 my $args;
33 if (scalar(@_) > 1) {
34 if ( @_ % 2 ) {
35 $proto->_throw_error( "Odd number of parameters to " . (caller(1))[2] );
36 }
37 $args = {@_};
38 }
d0b74c17 39 elsif ( ref $_[0] ) {
4d35d856 40 unless ( eval { local $SIG{'__DIE__'}; %{$_[0]} || 1 } ) {
0ca7ea98 41 $proto->_throw_error( "Not a hashref in args to " . (caller(1))[2] );
42 }
43 $args = $_[0];
44 }
d0b74c17 45 else {
0ca7ea98 46 $args = { file => shift };
47 }
48
49 return $args;
50}
51
d426259c 52# Class constructor method for Perl OO interface.
53# Calls tie() and returns blessed reference to tied hash or array,
54# providing a hybrid OO/tie interface.
ffed8b01 55sub new {
d0b74c17 56 my $class = shift;
57 my $args = $class->_get_args( @_ );
4f0f6fff 58 my $self;
59
d0b74c17 60 if (defined($args->{type}) && $args->{type} eq TYPE_ARRAY) {
6fe26b29 61 $class = 'DBM::Deep::Array';
62 require DBM::Deep::Array;
d0b74c17 63 tie @$self, $class, %$args;
64 }
65 else {
6fe26b29 66 $class = 'DBM::Deep::Hash';
67 require DBM::Deep::Hash;
d0b74c17 68 tie %$self, $class, %$args;
69 }
ffed8b01 70
d0b74c17 71 return bless $self, $class;
ffed8b01 72}
73
96041a25 74# This initializer is called from the various TIE* methods. new() calls tie(),
75# which allows for a single point of entry.
0795f290 76sub _init {
0795f290 77 my $class = shift;
994ccd8e 78 my ($args) = @_;
0795f290 79
460b1067 80 # locking implicitly enables autoflush
81 if ($args->{locking}) { $args->{autoflush} = 1; }
82
0795f290 83 # These are the defaults to be optionally overridden below
84 my $self = bless {
95967a5e 85 type => TYPE_HASH,
e06824f8 86 base_offset => undef,
2120a181 87 staleness => undef,
2120a181 88 engine => undef,
0795f290 89 }, $class;
2120a181 90
2c70efe1 91 unless ( exists $args->{engine} ) {
92 my $class = exists $args->{dbi}
93 ? 'DBM::Deep::Engine::DBI'
94 : 'DBM::Deep::Engine::File';
95
96 $args->{engine} = $class->new({
97 %{$args},
98 obj => $self,
99 });
100 }
8db25060 101
fde3db1a 102 # Grab the parameters we want to use
0795f290 103 foreach my $param ( keys %$self ) {
104 next unless exists $args->{$param};
3e9498a1 105 $self->{$param} = $args->{$param};
ffed8b01 106 }
d0b74c17 107
2120a181 108 eval {
2c70efe1 109 local $SIG{'__DIE__'};
0795f290 110
2c70efe1 111 $self->lock_exclusive;
112 $self->_engine->setup( $self );
113 $self->unlock;
2120a181 114 }; if ( $@ ) {
2c70efe1 115 my $e = $@;
116 eval { local $SIG{'__DIE__'}; $self->unlock; };
117 die $e;
2120a181 118 }
359a01ac 119
0795f290 120 return $self;
ffed8b01 121}
122
ffed8b01 123sub TIEHASH {
6fe26b29 124 shift;
125 require DBM::Deep::Hash;
126 return DBM::Deep::Hash->TIEHASH( @_ );
ffed8b01 127}
128
129sub TIEARRAY {
6fe26b29 130 shift;
131 require DBM::Deep::Array;
132 return DBM::Deep::Array->TIEARRAY( @_ );
ffed8b01 133}
134
5c0756fc 135sub lock_exclusive {
994ccd8e 136 my $self = shift->_get_self;
9c87a079 137 return $self->_engine->lock_exclusive( $self, @_ );
5c0756fc 138}
139*lock = \&lock_exclusive;
140sub lock_shared {
141 my $self = shift->_get_self;
9c87a079 142 return $self->_engine->lock_shared( $self, @_ );
ffed8b01 143}
144
145sub unlock {
994ccd8e 146 my $self = shift->_get_self;
9c87a079 147 return $self->_engine->unlock( $self, @_ );
ffed8b01 148}
149
906c8e01 150sub _copy_value {
151 my $self = shift->_get_self;
152 my ($spot, $value) = @_;
153
154 if ( !ref $value ) {
155 ${$spot} = $value;
156 }
906c8e01 157 else {
158 my $r = Scalar::Util::reftype( $value );
edd45134 159 my $tied;
906c8e01 160 if ( $r eq 'ARRAY' ) {
edd45134 161 $tied = tied(@$value);
906c8e01 162 }
2c70efe1 163 elsif ( $r eq 'HASH' ) {
edd45134 164 $tied = tied(%$value);
165 }
2c70efe1 166 else {
167 __PACKAGE__->_throw_error( "Unknown type for '$value'" );
168 }
edd45134 169
2c70efe1 170 if ( eval { local $SIG{__DIE__}; $tied->isa( __PACKAGE__ ) } ) {
edd45134 171 ${$spot} = $tied->_repr;
172 $tied->_copy_node( ${$spot} );
173 }
174 else {
175 if ( $r eq 'ARRAY' ) {
176 ${$spot} = [ @{$value} ];
177 }
178 else {
179 ${$spot} = { %{$value} };
180 }
181 }
182
183 my $c = Scalar::Util::blessed( $value );
2c70efe1 184 if ( defined $c && !$c->isa( __PACKAGE__ ) ) {
edd45134 185 ${$spot} = bless ${$spot}, $c
906c8e01 186 }
906c8e01 187 }
188
189 return 1;
190}
191
2120a181 192#sub _copy_node {
193# die "Must be implemented in a child class\n";
194#}
195#
196#sub _repr {
197# die "Must be implemented in a child class\n";
198#}
ffed8b01 199
200sub export {
994ccd8e 201 my $self = shift->_get_self;
d0b74c17 202
f9c33187 203 my $temp = $self->_repr;
d0b74c17 204
5c0756fc 205 $self->lock_exclusive;
d0b74c17 206 $self->_copy_node( $temp );
5c0756fc 207 $self->unlock;
d0b74c17 208
2120a181 209 my $classname = $self->_engine->get_classname( $self );
210 if ( defined $classname ) {
211 bless $temp, $classname;
68f943b3 212 }
213
d0b74c17 214 return $temp;
ffed8b01 215}
216
e00d0eb3 217sub _check_legality {
218 my $self = shift;
219 my ($val) = @_;
220
221 my $r = Scalar::Util::reftype( $val );
222
223 return $r if !defined $r || '' eq $r;
224 return $r if 'HASH' eq $r;
225 return $r if 'ARRAY' eq $r;
226
2c70efe1 227 __PACKAGE__->_throw_error(
e00d0eb3 228 "Storage of references of type '$r' is not supported."
229 );
230}
231
ffed8b01 232sub import {
d426259c 233 return if !ref $_[0]; # Perl calls import() on use -- ignore
d0b74c17 234
994ccd8e 235 my $self = shift->_get_self;
236 my ($struct) = @_;
d0b74c17 237
e00d0eb3 238 my $type = $self->_check_legality( $struct );
239 if ( !$type ) {
2c70efe1 240 __PACKAGE__->_throw_error( "Cannot import a scalar" );
d0b74c17 241 }
242
e00d0eb3 243 if ( substr( $type, 0, 1 ) ne $self->_type ) {
2c70efe1 244 __PACKAGE__->_throw_error(
e00d0eb3 245 "Cannot import " . ('HASH' eq $type ? 'a hash' : 'an array')
246 . " into " . ('HASH' eq $type ? 'an array' : 'a hash')
247 );
7a960a12 248 }
249
e00d0eb3 250 my %seen;
251 my $recurse;
252 $recurse = sub {
253 my ($db, $val) = @_;
254
255 my $obj = 'HASH' eq Scalar::Util::reftype( $db ) ? tied(%$db) : tied(@$db);
256 $obj ||= $db;
257
258 my $r = $self->_check_legality( $val );
259 if ( 'HASH' eq $r ) {
260 while ( my ($k, $v) = each %$val ) {
261 my $r = $self->_check_legality( $v );
262 if ( $r ) {
263 my $temp = 'HASH' eq $r ? {} : [];
264 if ( my $c = Scalar::Util::blessed( $v ) ) {
265 bless $temp, $c;
266 }
267 $obj->put( $k, $temp );
268 $recurse->( $temp, $v );
269 }
270 else {
271 $obj->put( $k, $v );
272 }
273 }
274 }
275 elsif ( 'ARRAY' eq $r ) {
276 foreach my $k ( 0 .. $#$val ) {
277 my $v = $val->[$k];
278 my $r = $self->_check_legality( $v );
279 if ( $r ) {
280 my $temp = 'HASH' eq $r ? {} : [];
281 if ( my $c = Scalar::Util::blessed( $v ) ) {
282 bless $temp, $c;
283 }
284 $obj->put( $k, $temp );
285 $recurse->( $temp, $v );
286 }
287 else {
288 $obj->put( $k, $v );
289 }
290 }
291 }
292 };
293 $recurse->( $self, $struct );
294
7a960a12 295 return 1;
ffed8b01 296}
297
13ff93d5 298#XXX Need to keep track of who has a fh to this file in order to
299#XXX close them all prior to optimize on Win32/cygwin
d426259c 300# Rebuild entire database into new file, then move
301# it back on top of original.
ffed8b01 302sub optimize {
994ccd8e 303 my $self = shift->_get_self;
cc4bef86 304
d426259c 305 # Optimizing is only something we need to do when we're working with our
306 # own file format. Otherwise, let the other guy do the optimizations.
51e9eee3 307 return unless $self->_engine->isa( 'DBM::Deep::Engine::File' );
d426259c 308
cc4bef86 309#XXX Need to create a new test for this
f1879fdc 310# if ($self->_engine->storage->{links} > 1) {
1400a48e 311# $self->_throw_error("Cannot optimize: reference count is greater than 1");
d0b74c17 312# }
313
7a960a12 314 #XXX Do we have to lock the tempfile?
315
e00d0eb3 316 #XXX Should we use tempfile() here instead of a hard-coded name?
f1879fdc 317 my $temp_filename = $self->_engine->storage->{file} . '.tmp';
2c70efe1 318 my $db_temp = __PACKAGE__->new(
6e6789b0 319 file => $temp_filename,
2120a181 320 type => $self->_type,
321
322 # Bring over all the parameters that we need to bring over
888453b9 323 ( map { $_ => $self->_engine->$_ } qw(
324 byte_size max_buckets data_sector_size num_txns
325 )),
d0b74c17 326 );
d0b74c17 327
5c0756fc 328 $self->lock_exclusive;
c57b19c6 329 $self->_engine->clear_cache;
d0b74c17 330 $self->_copy_node( $db_temp );
f1879fdc 331 $db_temp->_engine->storage->close;
d0b74c17 332 undef $db_temp;
333
334 ##
335 # Attempt to copy user, group and permissions over to new file
336 ##
f1879fdc 337 $self->_engine->storage->copy_stats( $temp_filename );
d0b74c17 338
ffed8b01 339 # q.v. perlport for more information on this variable
90f93b43 340 if ( $^O eq 'MSWin32' || $^O eq 'cygwin' ) {
d0b74c17 341 ##
342 # Potential race condition when optmizing on Win32 with locking.
343 # The Windows filesystem requires that the filehandle be closed
344 # before it is overwritten with rename(). This could be redone
345 # with a soft copy.
346 ##
5c0756fc 347 $self->unlock;
f1879fdc 348 $self->_engine->storage->close;
d0b74c17 349 }
350
f1879fdc 351 if (!rename $temp_filename, $self->_engine->storage->{file}) {
6e6789b0 352 unlink $temp_filename;
5c0756fc 353 $self->unlock;
1400a48e 354 $self->_throw_error("Optimize failed: Cannot copy temp file over original: $!");
d0b74c17 355 }
356
5c0756fc 357 $self->unlock;
f1879fdc 358 $self->_engine->storage->close;
2120a181 359
f1879fdc 360 $self->_engine->storage->open;
5c0756fc 361 $self->lock_exclusive;
f4d0ac97 362 $self->_engine->setup( $self );
5c0756fc 363 $self->unlock;
70b55428 364
d0b74c17 365 return 1;
ffed8b01 366}
367
368sub clone {
d0b74c17 369 ##
370 # Make copy of object and return
371 ##
994ccd8e 372 my $self = shift->_get_self;
d0b74c17 373
2c70efe1 374 return __PACKAGE__->new(
c3aafc14 375 type => $self->_type,
d0b74c17 376 base_offset => $self->_base_offset,
2120a181 377 staleness => $self->_staleness,
2120a181 378 engine => $self->_engine,
d0b74c17 379 );
ffed8b01 380}
381
580e5ee2 382sub supports {
383 my $self = shift;
384 return $self->_engine->supports( @_ );
385}
386
2120a181 387#XXX Migrate this to the engine, where it really belongs and go through some
388# API - stop poking in the innards of someone else..
ffed8b01 389{
390 my %is_legal_filter = map {
391 $_ => ~~1,
392 } qw(
393 store_key store_value
394 fetch_key fetch_value
395 );
396
397 sub set_filter {
994ccd8e 398 my $self = shift->_get_self;
399 my $type = lc shift;
400 my $func = shift;
d0b74c17 401
ffed8b01 402 if ( $is_legal_filter{$type} ) {
f1879fdc 403 $self->_engine->storage->{"filter_$type"} = $func;
ffed8b01 404 return 1;
405 }
406
407 return;
408 }
888453b9 409
410 sub filter_store_key { $_[0]->set_filter( store_key => $_[1] ); }
411 sub filter_store_value { $_[0]->set_filter( store_value => $_[1] ); }
412 sub filter_fetch_key { $_[0]->set_filter( fetch_key => $_[1] ); }
413 sub filter_fetch_value { $_[0]->set_filter( fetch_value => $_[1] ); }
ffed8b01 414}
415
fee0243f 416sub begin_work {
417 my $self = shift->_get_self;
db2eb673 418 $self->lock_exclusive;
c65299b4 419 my $rv = eval { $self->_engine->begin_work( $self, @_ ) };
420 my $e = $@;
db2eb673 421 $self->unlock;
c65299b4 422 die $e if $e;
db2eb673 423 return $rv;
fee0243f 424}
425
426sub rollback {
427 my $self = shift->_get_self;
db2eb673 428 $self->lock_exclusive;
c65299b4 429 my $rv = eval { $self->_engine->rollback( $self, @_ ) };
430 my $e = $@;
db2eb673 431 $self->unlock;
c65299b4 432 die $e if $e;
db2eb673 433 return $rv;
fee0243f 434}
435
359a01ac 436sub commit {
437 my $self = shift->_get_self;
db2eb673 438 $self->lock_exclusive;
c65299b4 439 my $rv = eval { $self->_engine->commit( $self, @_ ) };
440 my $e = $@;
db2eb673 441 $self->unlock;
c65299b4 442 die $e if $e;
db2eb673 443 return $rv;
359a01ac 444}
fee0243f 445
ffed8b01 446# Accessor methods
72e315ac 447sub _engine {
448 my $self = $_[0]->_get_self;
449 return $self->{engine};
450}
451
4d35d856 452sub _type {
2ac02042 453 my $self = $_[0]->_get_self;
d0b74c17 454 return $self->{type};
ffed8b01 455}
456
4d35d856 457sub _base_offset {
2ac02042 458 my $self = $_[0]->_get_self;
d0b74c17 459 return $self->{base_offset};
ffed8b01 460}
461
2120a181 462sub _staleness {
463 my $self = $_[0]->_get_self;
464 return $self->{staleness};
465}
466
ffed8b01 467# Utility methods
261d1296 468sub _throw_error {
807f63a7 469 my $n = 0;
470 while( 1 ) {
471 my @caller = caller( ++$n );
472 next if $caller[0] =~ m/^DBM::Deep/;
473
474 die "DBM::Deep: $_[1] at $0 line $caller[2]\n";
807f63a7 475 }
ffed8b01 476}
477
d426259c 478# Store single hash key/value or array element in database.
ffed8b01 479sub STORE {
d0b74c17 480 my $self = shift->_get_self;
2120a181 481 my ($key, $value) = @_;
c803879b 482 warn "STORE($self, '$key', '@{[defined$value?$value:'undef']}')\n" if DEBUG;
81d3d316 483
f1879fdc 484 unless ( $self->_engine->storage->is_writable ) {
acd4faf2 485 $self->_throw_error( 'Cannot write to a readonly filehandle' );
486 }
d0b74c17 487
5c0756fc 488 $self->lock_exclusive;
d0b74c17 489
0cb639bd 490 # User may be storing a complex value, in which case we do not want it run
491 # through the filtering system.
f1879fdc 492 if ( !ref($value) && $self->_engine->storage->{filter_store_value} ) {
493 $value = $self->_engine->storage->{filter_store_value}->( $value );
d0b74c17 494 }
495
2c70efe1 496 $self->_engine->write_value( $self, $key, $value );
d0b74c17 497
5c0756fc 498 $self->unlock;
d0b74c17 499
86867f3a 500 return 1;
ffed8b01 501}
502
d426259c 503# Fetch single value or element given plain key or array index
ffed8b01 504sub FETCH {
cb79ec85 505 my $self = shift->_get_self;
2120a181 506 my ($key) = @_;
c803879b 507 warn "FETCH($self, '$key')\n" if DEBUG;
ffed8b01 508
5c0756fc 509 $self->lock_shared;
d0b74c17 510
2c70efe1 511 my $result = $self->_engine->read_value( $self, $key );
d0b74c17 512
5c0756fc 513 $self->unlock;
d0b74c17 514
a86430bd 515 # Filters only apply to scalar values, so the ref check is making
516 # sure the fetched bucket is a scalar, not a child hash or array.
f1879fdc 517 return ($result && !ref($result) && $self->_engine->storage->{filter_fetch_value})
518 ? $self->_engine->storage->{filter_fetch_value}->($result)
cb79ec85 519 : $result;
ffed8b01 520}
521
d426259c 522# Delete single key/value pair or element given plain key or array index
ffed8b01 523sub DELETE {
a97c8f67 524 my $self = shift->_get_self;
2120a181 525 my ($key) = @_;
c803879b 526 warn "DELETE($self, '$key')\n" if DEBUG;
d0b74c17 527
f1879fdc 528 unless ( $self->_engine->storage->is_writable ) {
a86430bd 529 $self->_throw_error( 'Cannot write to a readonly filehandle' );
530 }
d0b74c17 531
5c0756fc 532 $self->lock_exclusive;
d0b74c17 533
d0b74c17 534 ##
535 # Delete bucket
536 ##
2120a181 537 my $value = $self->_engine->delete_key( $self, $key);
a86430bd 538
f1879fdc 539 if (defined $value && !ref($value) && $self->_engine->storage->{filter_fetch_value}) {
540 $value = $self->_engine->storage->{filter_fetch_value}->($value);
3b6a5056 541 }
542
5c0756fc 543 $self->unlock;
d0b74c17 544
545 return $value;
ffed8b01 546}
547
d426259c 548# Check if a single key or element exists given plain key or array index
ffed8b01 549sub EXISTS {
a97c8f67 550 my $self = shift->_get_self;
551 my ($key) = @_;
c803879b 552 warn "EXISTS($self, '$key')\n" if DEBUG;
d0b74c17 553
5c0756fc 554 $self->lock_shared;
d0b74c17 555
2120a181 556 my $result = $self->_engine->key_exists( $self, $key );
d0b74c17 557
5c0756fc 558 $self->unlock;
d0b74c17 559
560 return $result;
ffed8b01 561}
562
d426259c 563# Clear all keys from hash, or all elements from array.
ffed8b01 564sub CLEAR {
a97c8f67 565 my $self = shift->_get_self;
6e6789b0 566 warn "CLEAR($self)\n" if DEBUG;
ffed8b01 567
f1879fdc 568 unless ( $self->_engine->storage->is_writable ) {
a86430bd 569 $self->_throw_error( 'Cannot write to a readonly filehandle' );
570 }
571
5c0756fc 572 $self->lock_exclusive;
d0b74c17 573
2120a181 574 #XXX Rewrite this dreck to do it in the engine as a tight loop vs.
575 # iterating over keys - such a WASTE - is this required for transactional
576 # clearning?! Surely that can be detected in the engine ...
f9a320bb 577 if ( $self->_type eq TYPE_HASH ) {
578 my $key = $self->first_key;
579 while ( $key ) {
83c43bb5 580 # Retrieve the key before deleting because we depend on next_key
f9a320bb 581 my $next_key = $self->next_key( $key );
2120a181 582 $self->_engine->delete_key( $self, $key, $key );
f9a320bb 583 $key = $next_key;
584 }
585 }
586 else {
587 my $size = $self->FETCHSIZE;
c3aafc14 588 for my $key ( 0 .. $size - 1 ) {
2120a181 589 $self->_engine->delete_key( $self, $key, $key );
f9a320bb 590 }
591 $self->STORESIZE( 0 );
592 }
d0b74c17 593
5c0756fc 594 $self->unlock;
d0b74c17 595
596 return 1;
ffed8b01 597}
598
ffed8b01 599# Public method aliases
d426259c 600sub put { (shift)->STORE( @_ ) }
601sub get { (shift)->FETCH( @_ ) }
602sub store { (shift)->STORE( @_ ) }
603sub fetch { (shift)->FETCH( @_ ) }
baa27ab6 604sub delete { (shift)->DELETE( @_ ) }
605sub exists { (shift)->EXISTS( @_ ) }
d426259c 606sub clear { (shift)->CLEAR( @_ ) }
ffed8b01 607
888453b9 608sub _dump_file {shift->_get_self->_engine->_dump_file;}
609
ffed8b01 6101;
ffed8b01 611__END__