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