Updated Changes
[dbsrgits/DBM-Deep.git] / lib / DBM / Deep.pm
CommitLineData
ffed8b01 1package DBM::Deep;
2
2120a181 3use 5.006_000;
460b1067 4
ffed8b01 5use strict;
460b1067 6use warnings;
8b957036 7
695c88b1 8our $VERSION = q(1.0013);
86867f3a 9
edd45134 10use Data::Dumper ();
2120a181 11use Fcntl qw( :flock );
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
83371fe3 86 $args->{storage} = DBM::Deep::File->new( $args )
87 unless exists $args->{storage};
460b1067 88
89 # locking implicitly enables autoflush
90 if ($args->{locking}) { $args->{autoflush} = 1; }
91
0795f290 92 # These are the defaults to be optionally overridden below
93 my $self = bless {
95967a5e 94 type => TYPE_HASH,
e06824f8 95 base_offset => undef,
2120a181 96 staleness => undef,
359a01ac 97
83371fe3 98 storage => undef,
2120a181 99 engine => undef,
0795f290 100 }, $class;
2120a181 101
102 $args->{engine} = DBM::Deep::Engine->new( { %{$args}, obj => $self } )
103 unless exists $args->{engine};
8db25060 104
fde3db1a 105 # Grab the parameters we want to use
0795f290 106 foreach my $param ( keys %$self ) {
107 next unless exists $args->{$param};
3e9498a1 108 $self->{$param} = $args->{$param};
ffed8b01 109 }
d0b74c17 110
2120a181 111 eval {
112 local $SIG{'__DIE__'};
0795f290 113
2120a181 114 $self->lock;
115 $self->_engine->setup_fh( $self );
116 $self->_storage->set_inode;
117 $self->unlock;
118 }; if ( $@ ) {
119 my $e = $@;
120 eval { local $SIG{'__DIE__'}; $self->unlock; };
121 die $e;
122 }
359a01ac 123
0795f290 124 return $self;
ffed8b01 125}
126
ffed8b01 127sub TIEHASH {
6fe26b29 128 shift;
129 require DBM::Deep::Hash;
130 return DBM::Deep::Hash->TIEHASH( @_ );
ffed8b01 131}
132
133sub TIEARRAY {
6fe26b29 134 shift;
135 require DBM::Deep::Array;
136 return DBM::Deep::Array->TIEARRAY( @_ );
ffed8b01 137}
138
ffed8b01 139sub lock {
994ccd8e 140 my $self = shift->_get_self;
83371fe3 141 return $self->_storage->lock( $self, @_ );
ffed8b01 142}
143
144sub unlock {
994ccd8e 145 my $self = shift->_get_self;
83371fe3 146 return $self->_storage->unlock( $self, @_ );
ffed8b01 147}
148
906c8e01 149sub _copy_value {
150 my $self = shift->_get_self;
151 my ($spot, $value) = @_;
152
153 if ( !ref $value ) {
154 ${$spot} = $value;
155 }
906c8e01 156 else {
edd45134 157 # This assumes hash or array only. This is a bad assumption moving forward.
158 # -RobK, 2008-05-27
906c8e01 159 my $r = Scalar::Util::reftype( $value );
edd45134 160 my $tied;
906c8e01 161 if ( $r eq 'ARRAY' ) {
edd45134 162 $tied = tied(@$value);
906c8e01 163 }
164 else {
edd45134 165 $tied = tied(%$value);
166 }
167
168 if ( eval { local $SIG{__DIE__}; $tied->isa( 'DBM::Deep' ) } ) {
169 ${$spot} = $tied->_repr;
170 $tied->_copy_node( ${$spot} );
171 }
172 else {
173 if ( $r eq 'ARRAY' ) {
174 ${$spot} = [ @{$value} ];
175 }
176 else {
177 ${$spot} = { %{$value} };
178 }
179 }
180
181 my $c = Scalar::Util::blessed( $value );
182 if ( defined $c && !$c->isa( 'DBM::Deep') ) {
183 ${$spot} = bless ${$spot}, $c
906c8e01 184 }
906c8e01 185 }
186
187 return 1;
188}
189
2120a181 190#sub _copy_node {
191# die "Must be implemented in a child class\n";
192#}
193#
194#sub _repr {
195# die "Must be implemented in a child class\n";
196#}
ffed8b01 197
198sub export {
d0b74c17 199 ##
200 # Recursively export into standard Perl hashes and arrays.
201 ##
994ccd8e 202 my $self = shift->_get_self;
d0b74c17 203
f9c33187 204 my $temp = $self->_repr;
d0b74c17 205
206 $self->lock();
207 $self->_copy_node( $temp );
208 $self->unlock();
209
2120a181 210 my $classname = $self->_engine->get_classname( $self );
211 if ( defined $classname ) {
212 bless $temp, $classname;
68f943b3 213 }
214
d0b74c17 215 return $temp;
ffed8b01 216}
217
e00d0eb3 218sub _check_legality {
219 my $self = shift;
220 my ($val) = @_;
221
222 my $r = Scalar::Util::reftype( $val );
223
224 return $r if !defined $r || '' eq $r;
225 return $r if 'HASH' eq $r;
226 return $r if 'ARRAY' eq $r;
227
228 DBM::Deep->_throw_error(
229 "Storage of references of type '$r' is not supported."
230 );
231}
232
ffed8b01 233sub import {
e00d0eb3 234 # Perl calls import() on use -- ignore
235 return if !ref $_[0];
d0b74c17 236
994ccd8e 237 my $self = shift->_get_self;
238 my ($struct) = @_;
d0b74c17 239
e00d0eb3 240 my $type = $self->_check_legality( $struct );
241 if ( !$type ) {
242 DBM::Deep->_throw_error( "Cannot import a scalar" );
d0b74c17 243 }
244
e00d0eb3 245 if ( substr( $type, 0, 1 ) ne $self->_type ) {
246 DBM::Deep->_throw_error(
247 "Cannot import " . ('HASH' eq $type ? 'a hash' : 'an array')
248 . " into " . ('HASH' eq $type ? 'an array' : 'a hash')
249 );
7a960a12 250 }
251
e00d0eb3 252 my %seen;
253 my $recurse;
254 $recurse = sub {
255 my ($db, $val) = @_;
256
257 my $obj = 'HASH' eq Scalar::Util::reftype( $db ) ? tied(%$db) : tied(@$db);
258 $obj ||= $db;
259
260 my $r = $self->_check_legality( $val );
261 if ( 'HASH' eq $r ) {
262 while ( my ($k, $v) = each %$val ) {
263 my $r = $self->_check_legality( $v );
264 if ( $r ) {
265 my $temp = 'HASH' eq $r ? {} : [];
266 if ( my $c = Scalar::Util::blessed( $v ) ) {
267 bless $temp, $c;
268 }
269 $obj->put( $k, $temp );
270 $recurse->( $temp, $v );
271 }
272 else {
273 $obj->put( $k, $v );
274 }
275 }
276 }
277 elsif ( 'ARRAY' eq $r ) {
278 foreach my $k ( 0 .. $#$val ) {
279 my $v = $val->[$k];
280 my $r = $self->_check_legality( $v );
281 if ( $r ) {
282 my $temp = 'HASH' eq $r ? {} : [];
283 if ( my $c = Scalar::Util::blessed( $v ) ) {
284 bless $temp, $c;
285 }
286 $obj->put( $k, $temp );
287 $recurse->( $temp, $v );
288 }
289 else {
290 $obj->put( $k, $v );
291 }
292 }
293 }
294 };
295 $recurse->( $self, $struct );
296
7a960a12 297 return 1;
ffed8b01 298}
299
13ff93d5 300#XXX Need to keep track of who has a fh to this file in order to
301#XXX close them all prior to optimize on Win32/cygwin
ffed8b01 302sub optimize {
d0b74c17 303 ##
304 # Rebuild entire database into new file, then move
305 # it back on top of original.
306 ##
994ccd8e 307 my $self = shift->_get_self;
cc4bef86 308
309#XXX Need to create a new test for this
83371fe3 310# if ($self->_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?
6e6789b0 317 my $temp_filename = $self->_storage->{file} . '.tmp';
d0b74c17 318 my $db_temp = DBM::Deep->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
328 $self->lock();
c57b19c6 329 $self->_engine->clear_cache;
d0b74c17 330 $self->_copy_node( $db_temp );
695c88b1 331 $db_temp->_storage->close;
d0b74c17 332 undef $db_temp;
333
334 ##
335 # Attempt to copy user, group and permissions over to new file
336 ##
6e6789b0 337 $self->_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 ##
347 $self->unlock();
83371fe3 348 $self->_storage->close;
d0b74c17 349 }
350
6e6789b0 351 if (!rename $temp_filename, $self->_storage->{file}) {
352 unlink $temp_filename;
d0b74c17 353 $self->unlock();
1400a48e 354 $self->_throw_error("Optimize failed: Cannot copy temp file over original: $!");
d0b74c17 355 }
356
357 $self->unlock();
83371fe3 358 $self->_storage->close;
2120a181 359
83371fe3 360 $self->_storage->open;
2120a181 361 $self->lock();
72e315ac 362 $self->_engine->setup_fh( $self );
2120a181 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
374 return DBM::Deep->new(
c3aafc14 375 type => $self->_type,
d0b74c17 376 base_offset => $self->_base_offset,
2120a181 377 staleness => $self->_staleness,
83371fe3 378 storage => $self->_storage,
2120a181 379 engine => $self->_engine,
d0b74c17 380 );
ffed8b01 381}
382
2120a181 383#XXX Migrate this to the engine, where it really belongs and go through some
384# API - stop poking in the innards of someone else..
ffed8b01 385{
386 my %is_legal_filter = map {
387 $_ => ~~1,
388 } qw(
389 store_key store_value
390 fetch_key fetch_value
391 );
392
393 sub set_filter {
994ccd8e 394 my $self = shift->_get_self;
395 my $type = lc shift;
396 my $func = shift;
d0b74c17 397
ffed8b01 398 if ( $is_legal_filter{$type} ) {
83371fe3 399 $self->_storage->{"filter_$type"} = $func;
ffed8b01 400 return 1;
401 }
402
403 return;
404 }
888453b9 405
406 sub filter_store_key { $_[0]->set_filter( store_key => $_[1] ); }
407 sub filter_store_value { $_[0]->set_filter( store_value => $_[1] ); }
408 sub filter_fetch_key { $_[0]->set_filter( fetch_key => $_[1] ); }
409 sub filter_fetch_value { $_[0]->set_filter( fetch_value => $_[1] ); }
ffed8b01 410}
411
fee0243f 412sub begin_work {
413 my $self = shift->_get_self;
2120a181 414 return $self->_engine->begin_work( $self, @_ );
fee0243f 415}
416
417sub rollback {
418 my $self = shift->_get_self;
2120a181 419 return $self->_engine->rollback( $self, @_ );
fee0243f 420}
421
359a01ac 422sub commit {
423 my $self = shift->_get_self;
2120a181 424 return $self->_engine->commit( $self, @_ );
359a01ac 425}
fee0243f 426
ffed8b01 427##
428# Accessor methods
429##
430
72e315ac 431sub _engine {
432 my $self = $_[0]->_get_self;
433 return $self->{engine};
434}
435
83371fe3 436sub _storage {
2ac02042 437 my $self = $_[0]->_get_self;
83371fe3 438 return $self->{storage};
ffed8b01 439}
440
4d35d856 441sub _type {
2ac02042 442 my $self = $_[0]->_get_self;
d0b74c17 443 return $self->{type};
ffed8b01 444}
445
4d35d856 446sub _base_offset {
2ac02042 447 my $self = $_[0]->_get_self;
d0b74c17 448 return $self->{base_offset};
ffed8b01 449}
450
2120a181 451sub _staleness {
452 my $self = $_[0]->_get_self;
453 return $self->{staleness};
454}
455
ffed8b01 456##
457# Utility methods
458##
459
261d1296 460sub _throw_error {
807f63a7 461 my $n = 0;
462 while( 1 ) {
463 my @caller = caller( ++$n );
464 next if $caller[0] =~ m/^DBM::Deep/;
465
466 die "DBM::Deep: $_[1] at $0 line $caller[2]\n";
807f63a7 467 }
ffed8b01 468}
469
ffed8b01 470sub STORE {
d0b74c17 471 ##
472 # Store single hash key/value or array element in database.
473 ##
474 my $self = shift->_get_self;
2120a181 475 my ($key, $value) = @_;
6e6789b0 476 warn "STORE($self, $key, $value)\n" if DEBUG;
81d3d316 477
6e6789b0 478 unless ( $self->_storage->is_writable ) {
acd4faf2 479 $self->_throw_error( 'Cannot write to a readonly filehandle' );
480 }
d0b74c17 481
482 ##
483 # Request exclusive lock for writing
484 ##
485 $self->lock( LOCK_EX );
486
0cb639bd 487 # User may be storing a complex value, in which case we do not want it run
488 # through the filtering system.
83371fe3 489 if ( !ref($value) && $self->_storage->{filter_store_value} ) {
490 $value = $self->_storage->{filter_store_value}->( $value );
d0b74c17 491 }
492
2120a181 493 $self->_engine->write_value( $self, $key, $value);
d0b74c17 494
495 $self->unlock();
496
86867f3a 497 return 1;
ffed8b01 498}
499
500sub FETCH {
d0b74c17 501 ##
502 # Fetch single value or element given plain key or array index
503 ##
cb79ec85 504 my $self = shift->_get_self;
2120a181 505 my ($key) = @_;
6e6789b0 506 warn "FETCH($self,$key)\n" if DEBUG;
ffed8b01 507
d0b74c17 508 ##
509 # Request shared lock for reading
510 ##
511 $self->lock( LOCK_SH );
512
2120a181 513 my $result = $self->_engine->read_value( $self, $key);
d0b74c17 514
515 $self->unlock();
516
a86430bd 517 # Filters only apply to scalar values, so the ref check is making
518 # sure the fetched bucket is a scalar, not a child hash or array.
83371fe3 519 return ($result && !ref($result) && $self->_storage->{filter_fetch_value})
520 ? $self->_storage->{filter_fetch_value}->($result)
cb79ec85 521 : $result;
ffed8b01 522}
523
524sub DELETE {
d0b74c17 525 ##
526 # Delete single key/value pair or element given plain key or array index
527 ##
a97c8f67 528 my $self = shift->_get_self;
2120a181 529 my ($key) = @_;
6e6789b0 530 warn "DELETE($self,$key)\n" if DEBUG;
d0b74c17 531
6e6789b0 532 unless ( $self->_storage->is_writable ) {
a86430bd 533 $self->_throw_error( 'Cannot write to a readonly filehandle' );
534 }
d0b74c17 535
536 ##
537 # Request exclusive lock for writing
538 ##
539 $self->lock( LOCK_EX );
540
d0b74c17 541 ##
542 # Delete bucket
543 ##
2120a181 544 my $value = $self->_engine->delete_key( $self, $key);
a86430bd 545
83371fe3 546 if (defined $value && !ref($value) && $self->_storage->{filter_fetch_value}) {
547 $value = $self->_storage->{filter_fetch_value}->($value);
3b6a5056 548 }
549
d0b74c17 550 $self->unlock();
551
552 return $value;
ffed8b01 553}
554
555sub EXISTS {
d0b74c17 556 ##
557 # Check if a single key or element exists given plain key or array index
558 ##
a97c8f67 559 my $self = shift->_get_self;
560 my ($key) = @_;
6e6789b0 561 warn "EXISTS($self,$key)\n" if DEBUG;
d0b74c17 562
d0b74c17 563 ##
564 # Request shared lock for reading
565 ##
566 $self->lock( LOCK_SH );
567
2120a181 568 my $result = $self->_engine->key_exists( $self, $key );
d0b74c17 569
570 $self->unlock();
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
6e6789b0 582 unless ( $self->_storage->is_writable ) {
a86430bd 583 $self->_throw_error( 'Cannot write to a readonly filehandle' );
584 }
585
d0b74c17 586 ##
587 # Request exclusive lock for writing
588 ##
589 $self->lock( LOCK_EX );
590
2120a181 591 #XXX Rewrite this dreck to do it in the engine as a tight loop vs.
592 # iterating over keys - such a WASTE - is this required for transactional
593 # clearning?! Surely that can be detected in the engine ...
f9a320bb 594 if ( $self->_type eq TYPE_HASH ) {
595 my $key = $self->first_key;
596 while ( $key ) {
83c43bb5 597 # Retrieve the key before deleting because we depend on next_key
f9a320bb 598 my $next_key = $self->next_key( $key );
2120a181 599 $self->_engine->delete_key( $self, $key, $key );
f9a320bb 600 $key = $next_key;
601 }
602 }
603 else {
604 my $size = $self->FETCHSIZE;
c3aafc14 605 for my $key ( 0 .. $size - 1 ) {
2120a181 606 $self->_engine->delete_key( $self, $key, $key );
f9a320bb 607 }
608 $self->STORESIZE( 0 );
609 }
d0b74c17 610
611 $self->unlock();
612
613 return 1;
ffed8b01 614}
615
ffed8b01 616##
617# Public method aliases
618##
7f441181 619sub put { (shift)->STORE( @_ ) }
620sub store { (shift)->STORE( @_ ) }
621sub get { (shift)->FETCH( @_ ) }
622sub fetch { (shift)->FETCH( @_ ) }
baa27ab6 623sub delete { (shift)->DELETE( @_ ) }
624sub exists { (shift)->EXISTS( @_ ) }
625sub clear { (shift)->CLEAR( @_ ) }
ffed8b01 626
888453b9 627sub _dump_file {shift->_get_self->_engine->_dump_file;}
628
ffed8b01 6291;
ffed8b01 630__END__