Apply some changes
[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
8 our $VERSION = q(1.0019_003);
9
10 use Scalar::Util ();
11
12 use overload
13     '""' => sub { overload::StrVal( $_[0] ) },
14     fallback => 1;
15
16 use constant DEBUG => 0;
17
18 use DBM::Deep::Engine;
19
20 sub TYPE_HASH   () { DBM::Deep::Engine->SIG_HASH  }
21 sub TYPE_ARRAY  () { DBM::Deep::Engine->SIG_ARRAY }
22
23 # This is used in all the children of this class in their TIE<type> methods.
24 sub _get_args {
25     my $proto = shift;
26
27     my $args;
28     if (scalar(@_) > 1) {
29         if ( @_ % 2 ) {
30             $proto->_throw_error( "Odd number of parameters to " . (caller(1))[2] );
31         }
32         $args = {@_};
33     }
34     elsif ( ref $_[0] ) {
35         unless ( eval { local $SIG{'__DIE__'}; %{$_[0]} || 1 } ) {
36             $proto->_throw_error( "Not a hashref in args to " . (caller(1))[2] );
37         }
38         $args = $_[0];
39     }
40     else {
41         $args = { file => shift };
42     }
43
44     return $args;
45 }
46
47 # Class constructor method for Perl OO interface.
48 # Calls tie() and returns blessed reference to tied hash or array,
49 # providing a hybrid OO/tie interface.
50 sub new {
51     my $class = shift;
52     my $args = $class->_get_args( @_ );
53     my $self;
54     
55     if (defined($args->{type}) && $args->{type} eq TYPE_ARRAY) {
56         $class = 'DBM::Deep::Array';
57         require DBM::Deep::Array;
58         tie @$self, $class, %$args;
59     }
60     else {
61         $class = 'DBM::Deep::Hash';
62         require DBM::Deep::Hash;
63         tie %$self, $class, %$args;
64     }
65
66     return bless $self, $class;
67 }
68
69 # This initializer is called from the various TIE* methods. new() calls tie(),
70 # which allows for a single point of entry.
71 sub _init {
72     my $class = shift;
73     my ($args) = @_;
74
75     # locking implicitly enables autoflush
76     if ($args->{locking}) { $args->{autoflush} = 1; }
77
78     # These are the defaults to be optionally overridden below
79     my $self = bless {
80         type        => TYPE_HASH,
81         base_offset => undef,
82         staleness   => undef,
83         engine      => undef,
84     }, $class;
85
86     unless ( exists $args->{engine} ) {
87         my $class = exists $args->{dbi}
88             ? 'DBM::Deep::Engine::DBI'
89             : 'DBM::Deep::Engine::File';
90
91         eval "use $class"; die $@ if $@;
92         $args->{engine} = $class->new({
93             %{$args},
94             obj => $self,
95         });
96     }
97
98     # Grab the parameters we want to use
99     foreach my $param ( keys %$self ) {
100         next unless exists $args->{$param};
101         $self->{$param} = $args->{$param};
102     }
103
104     eval {
105         local $SIG{'__DIE__'};
106
107         $self->lock_exclusive;
108         $self->_engine->setup( $self );
109         $self->unlock;
110     }; if ( $@ ) {
111         my $e = $@;
112         eval { local $SIG{'__DIE__'}; $self->unlock; };
113         die $e;
114     }
115
116     return $self;
117 }
118
119 sub TIEHASH {
120     shift;
121     require DBM::Deep::Hash;
122     return DBM::Deep::Hash->TIEHASH( @_ );
123 }
124
125 sub TIEARRAY {
126     shift;
127     require DBM::Deep::Array;
128     return DBM::Deep::Array->TIEARRAY( @_ );
129 }
130
131 sub lock_exclusive {
132     my $self = shift->_get_self;
133     return $self->_engine->lock_exclusive( $self, @_ );
134 }
135 *lock = \&lock_exclusive;
136 sub lock_shared {
137     my $self = shift->_get_self;
138     return $self->_engine->lock_shared( $self, @_ );
139 }
140
141 sub unlock {
142     my $self = shift->_get_self;
143     return $self->_engine->unlock( $self, @_ );
144 }
145
146 sub _copy_value {
147     my $self = shift->_get_self;
148     my ($spot, $value) = @_;
149
150     if ( !ref $value ) {
151         ${$spot} = $value;
152     }
153     else {
154         my $r = Scalar::Util::reftype( $value );
155         my $tied;
156         if ( $r eq 'ARRAY' ) {
157             $tied = tied(@$value);
158         }
159         elsif ( $r eq 'HASH' ) {
160             $tied = tied(%$value);
161         }
162         else {
163             __PACKAGE__->_throw_error( "Unknown type for '$value'" );
164         }
165
166         if ( eval { local $SIG{'__DIE__'}; $tied->isa( __PACKAGE__ ) } ) {
167             ${$spot} = $tied->_repr;
168             $tied->_copy_node( ${$spot} );
169         }
170         else {
171             if ( $r eq 'ARRAY' ) {
172                 ${$spot} = [ @{$value} ];
173             }
174             else {
175                 ${$spot} = { %{$value} };
176             }
177         }
178
179         my $c = Scalar::Util::blessed( $value );
180         if ( defined $c && !$c->isa( __PACKAGE__ ) ) {
181             ${$spot} = bless ${$spot}, $c
182         }
183     }
184
185     return 1;
186 }
187
188 #sub _copy_node {
189 #    die "Must be implemented in a child class\n";
190 #}
191 #
192 #sub _repr {
193 #    die "Must be implemented in a child class\n";
194 #}
195
196 sub export {
197     my $self = shift->_get_self;
198
199     my $temp = $self->_repr;
200
201     $self->lock_exclusive;
202     $self->_copy_node( $temp );
203     $self->unlock;
204
205     my $classname = $self->_engine->get_classname( $self );
206     if ( defined $classname ) {
207       bless $temp, $classname;
208     }
209
210     return $temp;
211 }
212
213 sub _check_legality {
214     my $self = shift;
215     my ($val) = @_;
216
217     my $r = Scalar::Util::reftype( $val );
218
219     return $r if !defined $r || '' eq $r;
220     return $r if 'HASH' eq $r;
221     return $r if 'ARRAY' eq $r;
222
223     __PACKAGE__->_throw_error(
224         "Storage of references of type '$r' is not supported."
225     );
226 }
227
228 sub import {
229     return if !ref $_[0]; # Perl calls import() on use -- ignore
230
231     my $self = shift->_get_self;
232     my ($struct) = @_;
233
234     my $type = $self->_check_legality( $struct );
235     if ( !$type ) {
236         __PACKAGE__->_throw_error( "Cannot import a scalar" );
237     }
238
239     if ( substr( $type, 0, 1 ) ne $self->_type ) {
240         __PACKAGE__->_throw_error(
241             "Cannot import " . ('HASH' eq $type ? 'a hash' : 'an array')
242             . " into " . ('HASH' eq $type ? 'an array' : 'a hash')
243         );
244     }
245
246     my %seen;
247     my $recurse;
248     $recurse = sub {
249         my ($db, $val) = @_;
250
251         my $obj = 'HASH' eq Scalar::Util::reftype( $db ) ? tied(%$db) : tied(@$db);
252         $obj ||= $db;
253
254         my $r = $self->_check_legality( $val );
255         if ( 'HASH' eq $r ) {
256             while ( my ($k, $v) = each %$val ) {
257                 my $r = $self->_check_legality( $v );
258                 if ( $r ) {
259                     my $temp = 'HASH' eq $r ? {} : [];
260                     if ( my $c = Scalar::Util::blessed( $v ) ) {
261                         bless $temp, $c;
262                     }
263                     $obj->put( $k, $temp );
264                     $recurse->( $temp, $v );
265                 }
266                 else {
267                     $obj->put( $k, $v );
268                 }
269             }
270         }
271         elsif ( 'ARRAY' eq $r ) {
272             foreach my $k ( 0 .. $#$val ) {
273                 my $v = $val->[$k];
274                 my $r = $self->_check_legality( $v );
275                 if ( $r ) {
276                     my $temp = 'HASH' eq $r ? {} : [];
277                     if ( my $c = Scalar::Util::blessed( $v ) ) {
278                         bless $temp, $c;
279                     }
280                     $obj->put( $k, $temp );
281                     $recurse->( $temp, $v );
282                 }
283                 else {
284                     $obj->put( $k, $v );
285                 }
286             }
287         }
288     };
289     $recurse->( $self, $struct );
290
291     return 1;
292 }
293
294 #XXX Need to keep track of who has a fh to this file in order to
295 #XXX close them all prior to optimize on Win32/cygwin
296 # Rebuild entire database into new file, then move
297 # it back on top of original.
298 sub optimize {
299     my $self = shift->_get_self;
300
301     # Optimizing is only something we need to do when we're working with our
302     # own file format. Otherwise, let the other guy do the optimizations.
303     return unless $self->_engine->isa( 'DBM::Deep::Engine::File' );
304
305 #XXX Need to create a new test for this
306 #    if ($self->_engine->storage->{links} > 1) {
307 #        $self->_throw_error("Cannot optimize: reference count is greater than 1");
308 #    }
309
310     #XXX Do we have to lock the tempfile?
311
312     #XXX Should we use tempfile() here instead of a hard-coded name?
313     my $temp_filename = $self->_engine->storage->{file} . '.tmp';
314     my $db_temp = __PACKAGE__->new(
315         file => $temp_filename,
316         type => $self->_type,
317
318         # Bring over all the parameters that we need to bring over
319         ( map { $_ => $self->_engine->$_ } qw(
320             byte_size max_buckets data_sector_size num_txns
321         )),
322     );
323
324     $self->lock_exclusive;
325     $self->_engine->clear_cache;
326     $self->_copy_node( $db_temp );
327     $db_temp->_engine->storage->close;
328     undef $db_temp;
329
330     ##
331     # Attempt to copy user, group and permissions over to new file
332     ##
333     $self->_engine->storage->copy_stats( $temp_filename );
334
335     # q.v. perlport for more information on this variable
336     if ( $^O eq 'MSWin32' || $^O eq 'cygwin' ) {
337         ##
338         # Potential race condition when optmizing on Win32 with locking.
339         # The Windows filesystem requires that the filehandle be closed
340         # before it is overwritten with rename().  This could be redone
341         # with a soft copy.
342         ##
343         $self->unlock;
344         $self->_engine->storage->close;
345     }
346
347     if (!rename $temp_filename, $self->_engine->storage->{file}) {
348         unlink $temp_filename;
349         $self->unlock;
350         $self->_throw_error("Optimize failed: Cannot copy temp file over original: $!");
351     }
352
353     $self->unlock;
354     $self->_engine->storage->close;
355
356     $self->_engine->storage->open;
357     $self->lock_exclusive;
358     $self->_engine->setup( $self );
359     $self->unlock;
360
361     return 1;
362 }
363
364 sub clone {
365     ##
366     # Make copy of object and return
367     ##
368     my $self = shift->_get_self;
369
370     return __PACKAGE__->new(
371         type        => $self->_type,
372         base_offset => $self->_base_offset,
373         staleness   => $self->_staleness,
374         engine      => $self->_engine,
375     );
376 }
377
378 sub supports {
379     my $self = shift;
380     return $self->_engine->supports( @_ );
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->_engine->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     $self->lock_exclusive;
415     my $rv = eval {
416         local $SIG{'__DIE__'};
417         $self->_engine->begin_work( $self, @_ );
418     };
419     my $e = $@;
420     $self->unlock;
421     die $e if $e;
422     return $rv;
423 }
424
425 sub rollback {
426     my $self = shift->_get_self;
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
586     $engine->clear;
587
588     $self->unlock;
589
590     return 1;
591 }
592
593 # Public method aliases
594 sub put    { (shift)->STORE( @_ )  }
595 sub get    { (shift)->FETCH( @_ )  }
596 sub store  { (shift)->STORE( @_ )  }
597 sub fetch  { (shift)->FETCH( @_ )  }
598 sub delete { (shift)->DELETE( @_ ) }
599 sub exists { (shift)->EXISTS( @_ ) }
600 sub clear  { (shift)->CLEAR( @_ )  }
601
602 sub _dump_file {shift->_get_self->_engine->_dump_file;}
603
604 1;
605 __END__