20efdedba9637c99fbdecaf94aa4e2104d2e2f50
[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_002);
9
10 use Scalar::Util ();
11
12 use DBM::Deep::Engine::DBI ();
13 use DBM::Deep::Engine::File ();
14
15 use overload
16     '""' => sub { overload::StrVal( $_[0] ) },
17     fallback => 1;
18
19 use constant DEBUG => 0;
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 = exists $args->{dbi}
89             ? 'DBM::Deep::Engine::DBI'
90             : 'DBM::Deep::Engine::File';
91
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 { $self->_engine->begin_work( $self, @_ ) };
416     my $e = $@;
417     $self->unlock;
418     die $e if $e;
419     return $rv;
420 }
421
422 sub rollback {
423     my $self = shift->_get_self;
424     $self->lock_exclusive;
425     my $rv = eval { $self->_engine->rollback( $self, @_ ) };
426     my $e = $@;
427     $self->unlock;
428     die $e if $e;
429     return $rv;
430 }
431
432 sub commit {
433     my $self = shift->_get_self;
434     $self->lock_exclusive;
435     my $rv = eval { $self->_engine->commit( $self, @_ ) };
436     my $e = $@;
437     $self->unlock;
438     die $e if $e;
439     return $rv;
440 }
441
442 # Accessor methods
443 sub _engine {
444     my $self = $_[0]->_get_self;
445     return $self->{engine};
446 }
447
448 sub _type {
449     my $self = $_[0]->_get_self;
450     return $self->{type};
451 }
452
453 sub _base_offset {
454     my $self = $_[0]->_get_self;
455     return $self->{base_offset};
456 }
457
458 sub _staleness {
459     my $self = $_[0]->_get_self;
460     return $self->{staleness};
461 }
462
463 # Utility methods
464 sub _throw_error {
465     my $n = 0;
466     while( 1 ) {
467         my @caller = caller( ++$n );
468         next if $caller[0] =~ m/^DBM::Deep/;
469
470         die "DBM::Deep: $_[1] at $0 line $caller[2]\n";
471     }
472 }
473
474 # Store single hash key/value or array element in database.
475 sub STORE {
476     my $self = shift->_get_self;
477     my ($key, $value) = @_;
478     warn "STORE($self, '$key', '@{[defined$value?$value:'undef']}')\n" if DEBUG;
479
480     unless ( $self->_engine->storage->is_writable ) {
481         $self->_throw_error( 'Cannot write to a readonly filehandle' );
482     }
483
484     $self->lock_exclusive;
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->_engine->storage->{filter_store_value} ) {
489         $value = $self->_engine->storage->{filter_store_value}->( $value );
490     }
491
492     eval {
493         $self->_engine->write_value( $self, $key, $value );
494     }; if ( my $e = $@ ) {
495         $self->unlock;
496         die $e;
497     }
498
499     $self->unlock;
500
501     return 1;
502 }
503
504 # Fetch single value or element given plain key or array index
505 sub FETCH {
506     my $self = shift->_get_self;
507     my ($key) = @_;
508     warn "FETCH($self, '$key')\n" if DEBUG;
509
510     $self->lock_shared;
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->_engine->storage->{filter_fetch_value})
519         ? $self->_engine->storage->{filter_fetch_value}->($result)
520         : $result;
521 }
522
523 # Delete single key/value pair or element given plain key or array index
524 sub DELETE {
525     my $self = shift->_get_self;
526     my ($key) = @_;
527     warn "DELETE($self, '$key')\n" if DEBUG;
528
529     unless ( $self->_engine->storage->is_writable ) {
530         $self->_throw_error( 'Cannot write to a readonly filehandle' );
531     }
532
533     $self->lock_exclusive;
534
535     ##
536     # Delete bucket
537     ##
538     my $value = $self->_engine->delete_key( $self, $key);
539
540     if (defined $value && !ref($value) && $self->_engine->storage->{filter_fetch_value}) {
541         $value = $self->_engine->storage->{filter_fetch_value}->($value);
542     }
543
544     $self->unlock;
545
546     return $value;
547 }
548
549 # Check if a single key or element exists given plain key or array index
550 sub EXISTS {
551     my $self = shift->_get_self;
552     my ($key) = @_;
553     warn "EXISTS($self, '$key')\n" if DEBUG;
554
555     $self->lock_shared;
556
557     my $result = $self->_engine->key_exists( $self, $key );
558
559     $self->unlock;
560
561     return $result;
562 }
563
564 # Clear all keys from hash, or all elements from array.
565 sub CLEAR {
566     my $self = shift->_get_self;
567     warn "CLEAR($self)\n" if DEBUG;
568
569     unless ( $self->_engine->storage->is_writable ) {
570         $self->_throw_error( 'Cannot write to a readonly filehandle' );
571     }
572
573     $self->lock_exclusive;
574
575     #XXX Rewrite this dreck to do it in the engine as a tight loop vs.
576     # iterating over keys - such a WASTE - is this required for transactional
577     # clearning?! Surely that can be detected in the engine ...
578     if ( $self->_type eq TYPE_HASH ) {
579         my $key = $self->first_key;
580         while ( $key ) {
581             # Retrieve the key before deleting because we depend on next_key
582             my $next_key = $self->next_key( $key );
583             $self->_engine->delete_key( $self, $key, $key );
584             $key = $next_key;
585         }
586     }
587     else {
588         my $size = $self->FETCHSIZE;
589         for my $key ( 0 .. $size - 1 ) {
590             $self->_engine->delete_key( $self, $key, $key );
591         }
592         $self->STORESIZE( 0 );
593     }
594
595     $self->unlock;
596
597     return 1;
598 }
599
600 # Public method aliases
601 sub put    { (shift)->STORE( @_ )  }
602 sub get    { (shift)->FETCH( @_ )  }
603 sub store  { (shift)->STORE( @_ )  }
604 sub fetch  { (shift)->FETCH( @_ )  }
605 sub delete { (shift)->DELETE( @_ ) }
606 sub exists { (shift)->EXISTS( @_ ) }
607 sub clear  { (shift)->CLEAR( @_ )  }
608
609 sub _dump_file {shift->_get_self->_engine->_dump_file;}
610
611 1;
612 __END__