Fix for 30085
[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     undef $db_temp;
332
333     ##
334     # Attempt to copy user, group and permissions over to new file
335     ##
336     $self->_storage->copy_stats( $temp_filename );
337
338     # q.v. perlport for more information on this variable
339     if ( $^O eq 'MSWin32' || $^O eq 'cygwin' ) {
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         ##
346         $self->unlock();
347         $self->_storage->close;
348     }
349
350     if (!rename $temp_filename, $self->_storage->{file}) {
351         unlink $temp_filename;
352         $self->unlock();
353         $self->_throw_error("Optimize failed: Cannot copy temp file over original: $!");
354     }
355
356     $self->unlock();
357     $self->_storage->close;
358
359     $self->_storage->open;
360     $self->lock();
361     $self->_engine->setup_fh( $self );
362     $self->unlock();
363
364     return 1;
365 }
366
367 sub clone {
368     ##
369     # Make copy of object and return
370     ##
371     my $self = shift->_get_self;
372
373     return DBM::Deep->new(
374         type        => $self->_type,
375         base_offset => $self->_base_offset,
376         staleness   => $self->_staleness,
377         storage     => $self->_storage,
378         engine      => $self->_engine,
379     );
380 }
381
382 #XXX Migrate this to the engine, where it really belongs and go through some
383 # API - stop poking in the innards of someone else..
384 {
385     my %is_legal_filter = map {
386         $_ => ~~1,
387     } qw(
388         store_key store_value
389         fetch_key fetch_value
390     );
391
392     sub set_filter {
393         my $self = shift->_get_self;
394         my $type = lc shift;
395         my $func = shift;
396
397         if ( $is_legal_filter{$type} ) {
398             $self->_storage->{"filter_$type"} = $func;
399             return 1;
400         }
401
402         return;
403     }
404
405     sub filter_store_key   { $_[0]->set_filter( store_key   => $_[1] ); }
406     sub filter_store_value { $_[0]->set_filter( store_value => $_[1] ); }
407     sub filter_fetch_key   { $_[0]->set_filter( fetch_key   => $_[1] ); }
408     sub filter_fetch_value { $_[0]->set_filter( fetch_value => $_[1] ); }
409 }
410
411 sub begin_work {
412     my $self = shift->_get_self;
413     return $self->_engine->begin_work( $self, @_ );
414 }
415
416 sub rollback {
417     my $self = shift->_get_self;
418     return $self->_engine->rollback( $self, @_ );
419 }
420
421 sub commit {
422     my $self = shift->_get_self;
423     return $self->_engine->commit( $self, @_ );
424 }
425
426 ##
427 # Accessor methods
428 ##
429
430 sub _engine {
431     my $self = $_[0]->_get_self;
432     return $self->{engine};
433 }
434
435 sub _storage {
436     my $self = $_[0]->_get_self;
437     return $self->{storage};
438 }
439
440 sub _type {
441     my $self = $_[0]->_get_self;
442     return $self->{type};
443 }
444
445 sub _base_offset {
446     my $self = $_[0]->_get_self;
447     return $self->{base_offset};
448 }
449
450 sub _staleness {
451     my $self = $_[0]->_get_self;
452     return $self->{staleness};
453 }
454
455 ##
456 # Utility methods
457 ##
458
459 sub _throw_error {
460     my $n = 0;
461     while( 1 ) {
462         my @caller = caller( ++$n );
463         next if $caller[0] =~ m/^DBM::Deep/;
464
465         die "DBM::Deep: $_[1] at $0 line $caller[2]\n";
466     }
467 }
468
469 sub STORE {
470     ##
471     # Store single hash key/value or array element in database.
472     ##
473     my $self = shift->_get_self;
474     my ($key, $value) = @_;
475     warn "STORE($self, $key, $value)\n" if DEBUG;
476
477     unless ( $self->_storage->is_writable ) {
478         $self->_throw_error( 'Cannot write to a readonly filehandle' );
479     }
480
481     ##
482     # Request exclusive lock for writing
483     ##
484     $self->lock( LOCK_EX );
485
486     # User may be storing a complex value, in which case we do not want it run
487     # through the filtering system.
488     if ( !ref($value) && $self->_storage->{filter_store_value} ) {
489         $value = $self->_storage->{filter_store_value}->( $value );
490     }
491
492     $self->_engine->write_value( $self, $key, $value);
493
494     $self->unlock();
495
496     return 1;
497 }
498
499 sub FETCH {
500     ##
501     # Fetch single value or element given plain key or array index
502     ##
503     my $self = shift->_get_self;
504     my ($key) = @_;
505     warn "FETCH($self,$key)\n" if DEBUG;
506
507     ##
508     # Request shared lock for reading
509     ##
510     $self->lock( LOCK_SH );
511
512     my $result = $self->_engine->read_value( $self, $key);
513
514     $self->unlock();
515
516     # Filters only apply to scalar values, so the ref check is making
517     # sure the fetched bucket is a scalar, not a child hash or array.
518     return ($result && !ref($result) && $self->_storage->{filter_fetch_value})
519         ? $self->_storage->{filter_fetch_value}->($result)
520         : $result;
521 }
522
523 sub DELETE {
524     ##
525     # Delete single key/value pair or element given plain key or array index
526     ##
527     my $self = shift->_get_self;
528     my ($key) = @_;
529     warn "DELETE($self,$key)\n" if DEBUG;
530
531     unless ( $self->_storage->is_writable ) {
532         $self->_throw_error( 'Cannot write to a readonly filehandle' );
533     }
534
535     ##
536     # Request exclusive lock for writing
537     ##
538     $self->lock( LOCK_EX );
539
540     ##
541     # Delete bucket
542     ##
543     my $value = $self->_engine->delete_key( $self, $key);
544
545     if (defined $value && !ref($value) && $self->_storage->{filter_fetch_value}) {
546         $value = $self->_storage->{filter_fetch_value}->($value);
547     }
548
549     $self->unlock();
550
551     return $value;
552 }
553
554 sub EXISTS {
555     ##
556     # Check if a single key or element exists given plain key or array index
557     ##
558     my $self = shift->_get_self;
559     my ($key) = @_;
560     warn "EXISTS($self,$key)\n" if DEBUG;
561
562     ##
563     # Request shared lock for reading
564     ##
565     $self->lock( LOCK_SH );
566
567     my $result = $self->_engine->key_exists( $self, $key );
568
569     $self->unlock();
570
571     return $result;
572 }
573
574 sub CLEAR {
575     ##
576     # Clear all keys from hash, or all elements from array.
577     ##
578     my $self = shift->_get_self;
579     warn "CLEAR($self)\n" if DEBUG;
580
581     unless ( $self->_storage->is_writable ) {
582         $self->_throw_error( 'Cannot write to a readonly filehandle' );
583     }
584
585     ##
586     # Request exclusive lock for writing
587     ##
588     $self->lock( LOCK_EX );
589
590     #XXX Rewrite this dreck to do it in the engine as a tight loop vs.
591     # iterating over keys - such a WASTE - is this required for transactional
592     # clearning?! Surely that can be detected in the engine ...
593     if ( $self->_type eq TYPE_HASH ) {
594         my $key = $self->first_key;
595         while ( $key ) {
596             # Retrieve the key before deleting because we depend on next_key
597             my $next_key = $self->next_key( $key );
598             $self->_engine->delete_key( $self, $key, $key );
599             $key = $next_key;
600         }
601     }
602     else {
603         my $size = $self->FETCHSIZE;
604         for my $key ( 0 .. $size - 1 ) {
605             $self->_engine->delete_key( $self, $key, $key );
606         }
607         $self->STORESIZE( 0 );
608     }
609
610     $self->unlock();
611
612     return 1;
613 }
614
615 ##
616 # Public method aliases
617 ##
618 sub put { (shift)->STORE( @_ ) }
619 sub store { (shift)->STORE( @_ ) }
620 sub get { (shift)->FETCH( @_ ) }
621 sub fetch { (shift)->FETCH( @_ ) }
622 sub delete { (shift)->DELETE( @_ ) }
623 sub exists { (shift)->EXISTS( @_ ) }
624 sub clear { (shift)->CLEAR( @_ ) }
625
626 sub _dump_file {shift->_get_self->_engine->_dump_file;}
627
628 1;
629 __END__