Merged with master and am ready to merge back
[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 FATAL => 'all';
7 no warnings 'recursion';
8
9 our $VERSION = q(1.0020);
10
11 use Scalar::Util ();
12
13 use overload
14     '""' => sub { overload::StrVal( $_[0] ) },
15     fallback => 1;
16
17 use constant DEBUG => 0;
18
19 use DBM::Deep::Engine;
20
21 sub TYPE_HASH   () { DBM::Deep::Engine->SIG_HASH  }
22 sub TYPE_ARRAY  () { DBM::Deep::Engine->SIG_ARRAY }
23
24 # This is used in all the children of this class in their TIE<type> methods.
25 sub _get_args {
26     my $proto = shift;
27
28     my $args;
29     if (scalar(@_) > 1) {
30         if ( @_ % 2 ) {
31             $proto->_throw_error( "Odd number of parameters to " . (caller(1))[2] );
32         }
33         $args = {@_};
34     }
35     elsif ( ref $_[0] ) {
36         unless ( eval { local $SIG{'__DIE__'}; %{$_[0]} || 1 } ) {
37             $proto->_throw_error( "Not a hashref in args to " . (caller(1))[2] );
38         }
39         $args = $_[0];
40     }
41     else {
42         $args = { file => shift };
43     }
44
45     return $args;
46 }
47
48 # Class constructor method for Perl OO interface.
49 # Calls tie() and returns blessed reference to tied hash or array,
50 # providing a hybrid OO/tie interface.
51 sub new {
52     my $class = shift;
53     my $args = $class->_get_args( @_ );
54     my $self;
55
56     if (defined($args->{type}) && $args->{type} eq TYPE_ARRAY) {
57         $class = 'DBM::Deep::Array';
58         require DBM::Deep::Array;
59         tie @$self, $class, %$args;
60     }
61     else {
62         $class = 'DBM::Deep::Hash';
63         require DBM::Deep::Hash;
64         tie %$self, $class, %$args;
65     }
66
67     return bless $self, $class;
68 }
69
70 # This initializer is called from the various TIE* methods. new() calls tie(),
71 # which allows for a single point of entry.
72 sub _init {
73     my $class = shift;
74     my ($args) = @_;
75
76     # locking implicitly enables autoflush
77     if ($args->{locking}) { $args->{autoflush} = 1; }
78
79     # These are the defaults to be optionally overridden below
80     my $self = bless {
81         type        => TYPE_HASH,
82         base_offset => undef,
83         staleness   => undef,
84         engine      => undef,
85     }, $class;
86
87     unless ( exists $args->{engine} ) {
88         my $class =
89             exists $args->{dbi}   ? 'DBM::Deep::Engine::DBI'  :
90             exists $args->{_test} ? 'DBM::Deep::Engine::Test' :
91                                     'DBM::Deep::Engine::File' ;
92
93         eval "use $class"; die $@ if $@;
94         $args->{engine} = $class->new({
95             %{$args},
96             obj => $self,
97         });
98     }
99
100     # Grab the parameters we want to use
101     foreach my $param ( keys %$self ) {
102         next unless exists $args->{$param};
103         $self->{$param} = $args->{$param};
104     }
105
106     eval {
107         local $SIG{'__DIE__'};
108
109         $self->lock_exclusive;
110         $self->_engine->setup( $self );
111         $self->unlock;
112     }; if ( $@ ) {
113         my $e = $@;
114         eval { local $SIG{'__DIE__'}; $self->unlock; };
115         die $e;
116     }
117
118     return $self;
119 }
120
121 sub TIEHASH {
122     shift;
123     require DBM::Deep::Hash;
124     return DBM::Deep::Hash->TIEHASH( @_ );
125 }
126
127 sub TIEARRAY {
128     shift;
129     require DBM::Deep::Array;
130     return DBM::Deep::Array->TIEARRAY( @_ );
131 }
132
133 sub lock_exclusive {
134     my $self = shift->_get_self;
135     return $self->_engine->lock_exclusive( $self, @_ );
136 }
137 *lock = \&lock_exclusive;
138
139 sub lock_shared {
140     my $self = shift->_get_self;
141     # cluck() the problem with cached File objects.
142     unless ( $self->_engine ) {
143         require Carp;
144         require Data::Dumper;
145         Carp::cluck( Data::Dumper->Dump( [$self], ['self'] ) );
146     }
147     return $self->_engine->lock_shared( $self, @_ );
148 }
149
150 sub unlock {
151     my $self = shift->_get_self;
152     return $self->_engine->unlock( $self, @_ );
153 }
154
155 sub _copy_value {
156     my $self = shift->_get_self;
157     my ($spot, $value) = @_;
158
159     if ( !ref $value ) {
160         ${$spot} = $value;
161     }
162     else {
163         my $r = Scalar::Util::reftype( $value );
164         my $tied;
165         if ( $r eq 'ARRAY' ) {
166             $tied = tied(@$value);
167         }
168         elsif ( $r eq 'HASH' ) {
169             $tied = tied(%$value);
170         }
171         else {
172             __PACKAGE__->_throw_error( "Unknown type for '$value'" );
173         }
174
175         if ( eval { local $SIG{'__DIE__'}; $tied->isa( __PACKAGE__ ) } ) {
176             ${$spot} = $tied->_repr;
177             $tied->_copy_node( ${$spot} );
178         }
179         else {
180             if ( $r eq 'ARRAY' ) {
181                 ${$spot} = [ @{$value} ];
182             }
183             else {
184                 ${$spot} = { %{$value} };
185             }
186         }
187
188         my $c = Scalar::Util::blessed( $value );
189         if ( defined $c && !$c->isa( __PACKAGE__ ) ) {
190             ${$spot} = bless ${$spot}, $c
191         }
192     }
193
194     return 1;
195 }
196
197 sub export {
198     my $self = shift->_get_self;
199
200     my $temp = $self->_repr;
201
202     $self->lock_exclusive;
203     $self->_copy_node( $temp );
204     $self->unlock;
205
206     my $classname = $self->_engine->get_classname( $self );
207     if ( defined $classname ) {
208       bless $temp, $classname;
209     }
210
211     return $temp;
212 }
213
214 sub _check_legality {
215     my $self = shift;
216     my ($val) = @_;
217
218     my $r = Scalar::Util::reftype( $val );
219
220     return $r if !defined $r || '' eq $r;
221     return $r if 'HASH' eq $r;
222     return $r if 'ARRAY' eq $r;
223
224     __PACKAGE__->_throw_error(
225         "Storage of references of type '$r' is not supported."
226     );
227 }
228
229 sub import {
230     return if !ref $_[0]; # Perl calls import() on use -- ignore
231
232     my $self = shift->_get_self;
233     my ($struct) = @_;
234
235     my $type = $self->_check_legality( $struct );
236     if ( !$type ) {
237         __PACKAGE__->_throw_error( "Cannot import a scalar" );
238     }
239
240     if ( substr( $type, 0, 1 ) ne $self->_type ) {
241         __PACKAGE__->_throw_error(
242             "Cannot import " . ('HASH' eq $type ? 'a hash' : 'an array')
243             . " into " . ('HASH' eq $type ? 'an array' : 'a hash')
244         );
245     }
246
247     my %seen;
248     my $recurse;
249     $recurse = sub {
250         my ($db, $val) = @_;
251
252         my $obj = 'HASH' eq Scalar::Util::reftype( $db ) ? tied(%$db) : tied(@$db);
253         $obj ||= $db;
254
255         my $r = $self->_check_legality( $val );
256         if ( 'HASH' eq $r ) {
257             while ( my ($k, $v) = each %$val ) {
258                 my $r = $self->_check_legality( $v );
259                 if ( $r ) {
260                     my $temp = 'HASH' eq $r ? {} : [];
261                     if ( my $c = Scalar::Util::blessed( $v ) ) {
262                         bless $temp, $c;
263                     }
264                     $obj->put( $k, $temp );
265                     $recurse->( $temp, $v );
266                 }
267                 else {
268                     $obj->put( $k, $v );
269                 }
270             }
271         }
272         elsif ( 'ARRAY' eq $r ) {
273             foreach my $k ( 0 .. $#$val ) {
274                 my $v = $val->[$k];
275                 my $r = $self->_check_legality( $v );
276                 if ( $r ) {
277                     my $temp = 'HASH' eq $r ? {} : [];
278                     if ( my $c = Scalar::Util::blessed( $v ) ) {
279                         bless $temp, $c;
280                     }
281                     $obj->put( $k, $temp );
282                     $recurse->( $temp, $v );
283                 }
284                 else {
285                     $obj->put( $k, $v );
286                 }
287             }
288         }
289     };
290     $recurse->( $self, $struct );
291
292     return 1;
293 }
294
295 #XXX Need to keep track of who has a fh to this file in order to
296 #XXX close them all prior to optimize on Win32/cygwin
297 # Rebuild entire database into new file, then move
298 # it back on top of original.
299 sub optimize {
300     my $self = shift->_get_self;
301
302     # Optimizing is only something we need to do when we're working with our
303     # own file format. Otherwise, let the other guy do the optimizations.
304     return unless $self->_engine->isa( 'DBM::Deep::Engine::File' );
305
306 #XXX Need to create a new test for this
307 #    if ($self->_engine->storage->{links} > 1) {
308 #        $self->_throw_error("Cannot optimize: reference count is greater than 1");
309 #    }
310
311     #XXX Do we have to lock the tempfile?
312
313     #XXX Should we use tempfile() here instead of a hard-coded name?
314     my $temp_filename = $self->_engine->storage->{file} . '.tmp';
315     my $db_temp = __PACKAGE__->new(
316         file => $temp_filename,
317         type => $self->_type,
318
319         # Bring over all the parameters that we need to bring over
320         ( map { $_ => $self->_engine->$_ } qw(
321             byte_size max_buckets data_sector_size num_txns
322         )),
323     );
324
325     $self->lock_exclusive;
326     $self->_engine->clear_cache;
327     $self->_copy_node( $db_temp );
328     $self->unlock;
329     $db_temp->_engine->storage->close;
330     undef $db_temp;
331
332     ##
333     # Attempt to copy user, group and permissions over to new file
334     ##
335     $self->_engine->storage->copy_stats( $temp_filename );
336
337     # q.v. perlport for more information on this variable
338     if ( $^O eq 'MSWin32' || $^O eq 'cygwin' ) {
339         ##
340         # Potential race condition when optmizing on Win32 with locking.
341         # The Windows filesystem requires that the filehandle be closed
342         # before it is overwritten with rename().  This could be redone
343         # with a soft copy.
344         ##
345         $self->unlock;
346         $self->_engine->storage->close;
347     }
348
349     if (!rename $temp_filename, $self->_engine->storage->{file}) {
350         unlink $temp_filename;
351         $self->unlock;
352         $self->_throw_error("Optimize failed: Cannot copy temp file over original: $!");
353     }
354
355     $self->unlock;
356     $self->_engine->storage->close;
357
358     $self->_engine->storage->open;
359     $self->lock_exclusive;
360     $self->_engine->setup( $self );
361     $self->unlock;
362
363     return 1;
364 }
365
366 sub clone {
367     my $self = shift->_get_self;
368
369     return __PACKAGE__->new(
370         type        => $self->_type,
371         base_offset => $self->_base_offset,
372         staleness   => $self->_staleness,
373         engine      => $self->_engine,
374     );
375 }
376
377 sub supports {
378     my $self = shift->_get_self;
379     return $self->_engine->supports( @_ );
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->_engine->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     $self->lock_exclusive;
414     my $rv = eval {
415         local $SIG{'__DIE__'};
416         $self->_engine->begin_work( $self, @_ );
417     };
418     my $e = $@;
419     $self->unlock;
420     die $e if $e;
421     return $rv;
422 }
423
424 sub rollback {
425     my $self = shift->_get_self;
426
427     $self->lock_exclusive;
428     my $rv = eval {
429         local $SIG{'__DIE__'};
430         $self->_engine->rollback( $self, @_ );
431     };
432     my $e = $@;
433     $self->unlock;
434     die $e if $e;
435     return $rv;
436 }
437
438 sub commit {
439     my $self = shift->_get_self;
440     $self->lock_exclusive;
441     my $rv = eval {
442         local $SIG{'__DIE__'};
443         $self->_engine->commit( $self, @_ );
444     };
445     my $e = $@;
446     $self->unlock;
447     die $e if $e;
448     return $rv;
449 }
450
451 # Accessor methods
452 sub _engine {
453     my $self = $_[0]->_get_self;
454     return $self->{engine};
455 }
456
457 sub _type {
458     my $self = $_[0]->_get_self;
459     return $self->{type};
460 }
461
462 sub _base_offset {
463     my $self = $_[0]->_get_self;
464     return $self->{base_offset};
465 }
466
467 sub _staleness {
468     my $self = $_[0]->_get_self;
469     return $self->{staleness};
470 }
471
472 # Utility methods
473 sub _throw_error {
474     my $n = 0;
475     while( 1 ) {
476         my @caller = caller( ++$n );
477         next if $caller[0] =~ m/^DBM::Deep/;
478
479         die "DBM::Deep: $_[1] at $0 line $caller[2]\n";
480     }
481 }
482
483 # Store single hash key/value or array element in database.
484 sub STORE {
485     my $self = shift->_get_self;
486     my ($key, $value) = @_;
487     warn "STORE($self, '$key', '@{[defined$value?$value:'undef']}')\n" if DEBUG;
488
489     unless ( $self->_engine->storage->is_writable ) {
490         $self->_throw_error( 'Cannot write to a readonly filehandle' );
491     }
492
493     $self->lock_exclusive;
494
495     # User may be storing a complex value, in which case we do not want it run
496     # through the filtering system.
497     if ( !ref($value) && $self->_engine->storage->{filter_store_value} ) {
498         $value = $self->_engine->storage->{filter_store_value}->( $value );
499     }
500
501     eval {
502         local $SIG{'__DIE__'};
503         $self->_engine->write_value( $self, $key, $value );
504     }; if ( my $e = $@ ) {
505         $self->unlock;
506         die $e;
507     }
508
509     $self->unlock;
510
511     return 1;
512 }
513
514 # Fetch single value or element given plain key or array index
515 sub FETCH {
516     my $self = shift->_get_self;
517     my ($key) = @_;
518     warn "FETCH($self, '$key')\n" if DEBUG;
519
520     $self->lock_shared;
521
522     my $result = $self->_engine->read_value( $self, $key );
523
524     $self->unlock;
525
526     # Filters only apply to scalar values, so the ref check is making
527     # sure the fetched bucket is a scalar, not a child hash or array.
528     return ($result && !ref($result) && $self->_engine->storage->{filter_fetch_value})
529         ? $self->_engine->storage->{filter_fetch_value}->($result)
530         : $result;
531 }
532
533 # Delete single key/value pair or element given plain key or array index
534 sub DELETE {
535     my $self = shift->_get_self;
536     my ($key) = @_;
537     warn "DELETE($self, '$key')\n" if DEBUG;
538
539     unless ( $self->_engine->storage->is_writable ) {
540         $self->_throw_error( 'Cannot write to a readonly filehandle' );
541     }
542
543     $self->lock_exclusive;
544
545     ##
546     # Delete bucket
547     ##
548     my $value = $self->_engine->delete_key( $self, $key);
549
550     if (defined $value && !ref($value) && $self->_engine->storage->{filter_fetch_value}) {
551         $value = $self->_engine->storage->{filter_fetch_value}->($value);
552     }
553
554     $self->unlock;
555
556     return $value;
557 }
558
559 # Check if a single key or element exists given plain key or array index
560 sub EXISTS {
561     my $self = shift->_get_self;
562     my ($key) = @_;
563     warn "EXISTS($self, '$key')\n" if DEBUG;
564
565     $self->lock_shared;
566
567     my $result = $self->_engine->key_exists( $self, $key );
568
569     $self->unlock;
570
571     return $result;
572 }
573
574 # Clear all keys from hash, or all elements from array.
575 sub CLEAR {
576     my $self = shift->_get_self;
577     warn "CLEAR($self)\n" if DEBUG;
578
579     my $engine = $self->_engine;
580     unless ( $engine->storage->is_writable ) {
581         $self->_throw_error( 'Cannot write to a readonly filehandle' );
582     }
583
584     $self->lock_exclusive;
585     eval {
586         local $SIG{'__DIE__'};
587         $engine->clear( $self );
588     };
589     my $e = $@;
590     warn "$e\n" if $e && DEBUG;
591
592     $self->unlock;
593
594     die $e if $e;
595
596     return 1;
597 }
598
599 # Public method aliases
600 sub put    { (shift)->STORE( @_ )  }
601 sub get    { (shift)->FETCH( @_ )  }
602 sub store  { (shift)->STORE( @_ )  }
603 sub fetch  { (shift)->FETCH( @_ )  }
604 sub delete { (shift)->DELETE( @_ ) }
605 sub exists { (shift)->EXISTS( @_ ) }
606 sub clear  { (shift)->CLEAR( @_ )  }
607
608 sub _dump_file {shift->_get_self->_engine->_dump_file;}
609
610 1;
611 __END__