Checkin fixing RT#30144
[dbsrgits/DBM-Deep.git] / lib / DBM / Deep.pm
1 package DBM::Deep;
2
3 use 5.006_000;
4
5 use strict;
6 use warnings;
7
8 our $VERSION = q(1.0012);
9
10 use Data::Dumper ();
11 use Fcntl qw( :flock );
12 use Scalar::Util ();
13
14 use DBM::Deep::Engine;
15 use DBM::Deep::File;
16
17 use overload
18     '""' => sub { overload::StrVal( $_[0] ) },
19     fallback => 1;
20
21 use constant DEBUG => 0;
22
23 ##
24 # Setup constants for users to pass to new()
25 ##
26 sub TYPE_HASH   () { DBM::Deep::Engine->SIG_HASH  }
27 sub TYPE_ARRAY  () { DBM::Deep::Engine->SIG_ARRAY }
28
29 # This is used in all the children of this class in their TIE<type> methods.
30 sub _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     }
40     elsif ( ref $_[0] ) {
41         unless ( eval { local $SIG{'__DIE__'}; %{$_[0]} || 1 } ) {
42             $proto->_throw_error( "Not a hashref in args to " . (caller(1))[2] );
43         }
44         $args = $_[0];
45     }
46     else {
47         $args = { file => shift };
48     }
49
50     return $args;
51 }
52
53 sub new {
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) {
67         $class = 'DBM::Deep::Array';
68         require DBM::Deep::Array;
69         tie @$self, $class, %$args;
70     }
71     else {
72         $class = 'DBM::Deep::Hash';
73         require DBM::Deep::Hash;
74         tie %$self, $class, %$args;
75     }
76
77     return bless $self, $class;
78 }
79
80 # This initializer is called from the various TIE* methods. new() calls tie(),
81 # which allows for a single point of entry.
82 sub _init {
83     my $class = shift;
84     my ($args) = @_;
85
86     $args->{storage} = DBM::Deep::File->new( $args )
87         unless exists $args->{storage};
88
89     # locking implicitly enables autoflush
90     if ($args->{locking}) { $args->{autoflush} = 1; }
91
92     # These are the defaults to be optionally overridden below
93     my $self = bless {
94         type        => TYPE_HASH,
95         base_offset => undef,
96         staleness   => undef,
97
98         storage     => undef,
99         engine      => undef,
100     }, $class;
101
102     $args->{engine} = DBM::Deep::Engine->new( { %{$args}, obj => $self } )
103         unless exists $args->{engine};
104
105     # Grab the parameters we want to use
106     foreach my $param ( keys %$self ) {
107         next unless exists $args->{$param};
108         $self->{$param} = $args->{$param};
109     }
110
111     eval {
112       local $SIG{'__DIE__'};
113
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     }
123
124     return $self;
125 }
126
127 sub TIEHASH {
128     shift;
129     require DBM::Deep::Hash;
130     return DBM::Deep::Hash->TIEHASH( @_ );
131 }
132
133 sub TIEARRAY {
134     shift;
135     require DBM::Deep::Array;
136     return DBM::Deep::Array->TIEARRAY( @_ );
137 }
138
139 sub lock {
140     my $self = shift->_get_self;
141     return $self->_storage->lock( $self, @_ );
142 }
143
144 sub unlock {
145     my $self = shift->_get_self;
146     return $self->_storage->unlock( $self, @_ );
147 }
148
149 sub _copy_value {
150     my $self = shift->_get_self;
151     my ($spot, $value) = @_;
152
153     if ( !ref $value ) {
154         ${$spot} = $value;
155     }
156     else {
157         # This assumes hash or array only. This is a bad assumption moving forward.
158         # -RobK, 2008-05-27
159         my $r = Scalar::Util::reftype( $value );
160         my $tied;
161         if ( $r eq 'ARRAY' ) {
162             $tied = tied(@$value);
163         }
164         else {
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
184         }
185     }
186
187     return 1;
188 }
189
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 #}
197
198 sub export {
199     ##
200     # Recursively export into standard Perl hashes and arrays.
201     ##
202     my $self = shift->_get_self;
203
204     my $temp = $self->_repr;
205
206     $self->lock();
207     $self->_copy_node( $temp );
208     $self->unlock();
209
210     my $classname = $self->_engine->get_classname( $self );
211     if ( defined $classname ) {
212       bless $temp, $classname;
213     }
214
215     return $temp;
216 }
217
218 sub _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
233 sub import {
234     # Perl calls import() on use -- ignore
235     return if !ref $_[0];
236
237     my $self = shift->_get_self;
238     my ($struct) = @_;
239
240     my $type = $self->_check_legality( $struct );
241     if ( !$type ) {
242         DBM::Deep->_throw_error( "Cannot import a scalar" );
243     }
244
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         );
250     }
251
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
297     return 1;
298 }
299
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
302 sub optimize {
303     ##
304     # Rebuild entire database into new file, then move
305     # it back on top of original.
306     ##
307     my $self = shift->_get_self;
308
309 #XXX Need to create a new test for this
310 #    if ($self->_storage->{links} > 1) {
311 #        $self->_throw_error("Cannot optimize: reference count is greater than 1");
312 #    }
313
314     #XXX Do we have to lock the tempfile?
315
316     #XXX Should we use tempfile() here instead of a hard-coded name?
317     my $temp_filename = $self->_storage->{file} . '.tmp';
318     my $db_temp = DBM::Deep->new(
319         file => $temp_filename,
320         type => $self->_type,
321
322         # Bring over all the parameters that we need to bring over
323         ( map { $_ => $self->_engine->$_ } qw(
324             byte_size max_buckets data_sector_size num_txns
325         )),
326     );
327
328     $self->lock();
329     $self->_engine->clear_cache;
330     $self->_copy_node( $db_temp );
331     $dbtemp->_storage->close;
332     undef $db_temp;
333
334     ##
335     # Attempt to copy user, group and permissions over to new file
336     ##
337     $self->_storage->copy_stats( $temp_filename );
338
339     # q.v. perlport for more information on this variable
340     if ( $^O eq 'MSWin32' || $^O eq 'cygwin' ) {
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();
348         $self->_storage->close;
349     }
350
351     if (!rename $temp_filename, $self->_storage->{file}) {
352         unlink $temp_filename;
353         $self->unlock();
354         $self->_throw_error("Optimize failed: Cannot copy temp file over original: $!");
355     }
356
357     $self->unlock();
358     $self->_storage->close;
359
360     $self->_storage->open;
361     $self->lock();
362     $self->_engine->setup_fh( $self );
363     $self->unlock();
364
365     return 1;
366 }
367
368 sub clone {
369     ##
370     # Make copy of object and return
371     ##
372     my $self = shift->_get_self;
373
374     return DBM::Deep->new(
375         type        => $self->_type,
376         base_offset => $self->_base_offset,
377         staleness   => $self->_staleness,
378         storage     => $self->_storage,
379         engine      => $self->_engine,
380     );
381 }
382
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..
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 {
394         my $self = shift->_get_self;
395         my $type = lc shift;
396         my $func = shift;
397
398         if ( $is_legal_filter{$type} ) {
399             $self->_storage->{"filter_$type"} = $func;
400             return 1;
401         }
402
403         return;
404     }
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] ); }
410 }
411
412 sub begin_work {
413     my $self = shift->_get_self;
414     return $self->_engine->begin_work( $self, @_ );
415 }
416
417 sub rollback {
418     my $self = shift->_get_self;
419     return $self->_engine->rollback( $self, @_ );
420 }
421
422 sub commit {
423     my $self = shift->_get_self;
424     return $self->_engine->commit( $self, @_ );
425 }
426
427 ##
428 # Accessor methods
429 ##
430
431 sub _engine {
432     my $self = $_[0]->_get_self;
433     return $self->{engine};
434 }
435
436 sub _storage {
437     my $self = $_[0]->_get_self;
438     return $self->{storage};
439 }
440
441 sub _type {
442     my $self = $_[0]->_get_self;
443     return $self->{type};
444 }
445
446 sub _base_offset {
447     my $self = $_[0]->_get_self;
448     return $self->{base_offset};
449 }
450
451 sub _staleness {
452     my $self = $_[0]->_get_self;
453     return $self->{staleness};
454 }
455
456 ##
457 # Utility methods
458 ##
459
460 sub _throw_error {
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";
467     }
468 }
469
470 sub STORE {
471     ##
472     # Store single hash key/value or array element in database.
473     ##
474     my $self = shift->_get_self;
475     my ($key, $value) = @_;
476     warn "STORE($self, $key, $value)\n" if DEBUG;
477
478     unless ( $self->_storage->is_writable ) {
479         $self->_throw_error( 'Cannot write to a readonly filehandle' );
480     }
481
482     ##
483     # Request exclusive lock for writing
484     ##
485     $self->lock( LOCK_EX );
486
487     # User may be storing a complex value, in which case we do not want it run
488     # through the filtering system.
489     if ( !ref($value) && $self->_storage->{filter_store_value} ) {
490         $value = $self->_storage->{filter_store_value}->( $value );
491     }
492
493     $self->_engine->write_value( $self, $key, $value);
494
495     $self->unlock();
496
497     return 1;
498 }
499
500 sub FETCH {
501     ##
502     # Fetch single value or element given plain key or array index
503     ##
504     my $self = shift->_get_self;
505     my ($key) = @_;
506     warn "FETCH($self,$key)\n" if DEBUG;
507
508     ##
509     # Request shared lock for reading
510     ##
511     $self->lock( LOCK_SH );
512
513     my $result = $self->_engine->read_value( $self, $key);
514
515     $self->unlock();
516
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.
519     return ($result && !ref($result) && $self->_storage->{filter_fetch_value})
520         ? $self->_storage->{filter_fetch_value}->($result)
521         : $result;
522 }
523
524 sub DELETE {
525     ##
526     # Delete single key/value pair or element given plain key or array index
527     ##
528     my $self = shift->_get_self;
529     my ($key) = @_;
530     warn "DELETE($self,$key)\n" if DEBUG;
531
532     unless ( $self->_storage->is_writable ) {
533         $self->_throw_error( 'Cannot write to a readonly filehandle' );
534     }
535
536     ##
537     # Request exclusive lock for writing
538     ##
539     $self->lock( LOCK_EX );
540
541     ##
542     # Delete bucket
543     ##
544     my $value = $self->_engine->delete_key( $self, $key);
545
546     if (defined $value && !ref($value) && $self->_storage->{filter_fetch_value}) {
547         $value = $self->_storage->{filter_fetch_value}->($value);
548     }
549
550     $self->unlock();
551
552     return $value;
553 }
554
555 sub EXISTS {
556     ##
557     # Check if a single key or element exists given plain key or array index
558     ##
559     my $self = shift->_get_self;
560     my ($key) = @_;
561     warn "EXISTS($self,$key)\n" if DEBUG;
562
563     ##
564     # Request shared lock for reading
565     ##
566     $self->lock( LOCK_SH );
567
568     my $result = $self->_engine->key_exists( $self, $key );
569
570     $self->unlock();
571
572     return $result;
573 }
574
575 sub CLEAR {
576     ##
577     # Clear all keys from hash, or all elements from array.
578     ##
579     my $self = shift->_get_self;
580     warn "CLEAR($self)\n" if DEBUG;
581
582     unless ( $self->_storage->is_writable ) {
583         $self->_throw_error( 'Cannot write to a readonly filehandle' );
584     }
585
586     ##
587     # Request exclusive lock for writing
588     ##
589     $self->lock( LOCK_EX );
590
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 ...
594     if ( $self->_type eq TYPE_HASH ) {
595         my $key = $self->first_key;
596         while ( $key ) {
597             # Retrieve the key before deleting because we depend on next_key
598             my $next_key = $self->next_key( $key );
599             $self->_engine->delete_key( $self, $key, $key );
600             $key = $next_key;
601         }
602     }
603     else {
604         my $size = $self->FETCHSIZE;
605         for my $key ( 0 .. $size - 1 ) {
606             $self->_engine->delete_key( $self, $key, $key );
607         }
608         $self->STORESIZE( 0 );
609     }
610
611     $self->unlock();
612
613     return 1;
614 }
615
616 ##
617 # Public method aliases
618 ##
619 sub put { (shift)->STORE( @_ ) }
620 sub store { (shift)->STORE( @_ ) }
621 sub get { (shift)->FETCH( @_ ) }
622 sub fetch { (shift)->FETCH( @_ ) }
623 sub delete { (shift)->DELETE( @_ ) }
624 sub exists { (shift)->EXISTS( @_ ) }
625 sub clear { (shift)->CLEAR( @_ ) }
626
627 sub _dump_file {shift->_get_self->_engine->_dump_file;}
628
629 1;
630 __END__