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