Set version to 1.0016
[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.0016);
10
11 use Data::Dumper ();
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     # locking implicitly enables autoflush
87     if ($args->{locking}) { $args->{autoflush} = 1; }
88
89     # These are the defaults to be optionally overridden below
90     my $self = bless {
91         type        => TYPE_HASH,
92         base_offset => undef,
93         staleness   => undef,
94         engine      => undef,
95     }, $class;
96
97     $args->{engine} = DBM::Deep::Engine->new( { %{$args}, obj => $self } )
98         unless exists $args->{engine};
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_fh( $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 sub lock_shared {
139     my $self = shift->_get_self;
140     return $self->_engine->lock_shared( $self, @_ );
141 }
142
143 sub unlock {
144     my $self = shift->_get_self;
145     return $self->_engine->unlock( $self, @_ );
146 }
147
148 sub _copy_value {
149     my $self = shift->_get_self;
150     my ($spot, $value) = @_;
151
152     if ( !ref $value ) {
153         ${$spot} = $value;
154     }
155     else {
156         # This assumes hash or array only. This is a bad assumption moving forward.
157         # -RobK, 2008-05-27
158         my $r = Scalar::Util::reftype( $value );
159         my $tied;
160         if ( $r eq 'ARRAY' ) {
161             $tied = tied(@$value);
162         }
163         else {
164             $tied = tied(%$value);
165         }
166
167         if ( eval { local $SIG{__DIE__}; $tied->isa( 'DBM::Deep' ) } ) {
168             ${$spot} = $tied->_repr;
169             $tied->_copy_node( ${$spot} );
170         }
171         else {
172             if ( $r eq 'ARRAY' ) {
173                 ${$spot} = [ @{$value} ];
174             }
175             else {
176                 ${$spot} = { %{$value} };
177             }
178         }
179
180         my $c = Scalar::Util::blessed( $value );
181         if ( defined $c && !$c->isa( 'DBM::Deep') ) {
182             ${$spot} = bless ${$spot}, $c
183         }
184     }
185
186     return 1;
187 }
188
189 #sub _copy_node {
190 #    die "Must be implemented in a child class\n";
191 #}
192 #
193 #sub _repr {
194 #    die "Must be implemented in a child class\n";
195 #}
196
197 sub export {
198     ##
199     # Recursively export into standard Perl hashes and arrays.
200     ##
201     my $self = shift->_get_self;
202
203     my $temp = $self->_repr;
204
205     $self->lock_exclusive;
206     $self->_copy_node( $temp );
207     $self->unlock;
208
209     my $classname = $self->_engine->get_classname( $self );
210     if ( defined $classname ) {
211       bless $temp, $classname;
212     }
213
214     return $temp;
215 }
216
217 sub _check_legality {
218     my $self = shift;
219     my ($val) = @_;
220
221     my $r = Scalar::Util::reftype( $val );
222
223     return $r if !defined $r || '' eq $r;
224     return $r if 'HASH' eq $r;
225     return $r if 'ARRAY' eq $r;
226
227     DBM::Deep->_throw_error(
228         "Storage of references of type '$r' is not supported."
229     );
230 }
231
232 sub import {
233     # Perl calls import() on use -- ignore
234     return if !ref $_[0];
235
236     my $self = shift->_get_self;
237     my ($struct) = @_;
238
239     my $type = $self->_check_legality( $struct );
240     if ( !$type ) {
241         DBM::Deep->_throw_error( "Cannot import a scalar" );
242     }
243
244     if ( substr( $type, 0, 1 ) ne $self->_type ) {
245         DBM::Deep->_throw_error(
246             "Cannot import " . ('HASH' eq $type ? 'a hash' : 'an array')
247             . " into " . ('HASH' eq $type ? 'an array' : 'a hash')
248         );
249     }
250
251     my %seen;
252     my $recurse;
253     $recurse = sub {
254         my ($db, $val) = @_;
255
256         my $obj = 'HASH' eq Scalar::Util::reftype( $db ) ? tied(%$db) : tied(@$db);
257         $obj ||= $db;
258
259         my $r = $self->_check_legality( $val );
260         if ( 'HASH' eq $r ) {
261             while ( my ($k, $v) = each %$val ) {
262                 my $r = $self->_check_legality( $v );
263                 if ( $r ) {
264                     my $temp = 'HASH' eq $r ? {} : [];
265                     if ( my $c = Scalar::Util::blessed( $v ) ) {
266                         bless $temp, $c;
267                     }
268                     $obj->put( $k, $temp );
269                     $recurse->( $temp, $v );
270                 }
271                 else {
272                     $obj->put( $k, $v );
273                 }
274             }
275         }
276         elsif ( 'ARRAY' eq $r ) {
277             foreach my $k ( 0 .. $#$val ) {
278                 my $v = $val->[$k];
279                 my $r = $self->_check_legality( $v );
280                 if ( $r ) {
281                     my $temp = 'HASH' eq $r ? {} : [];
282                     if ( my $c = Scalar::Util::blessed( $v ) ) {
283                         bless $temp, $c;
284                     }
285                     $obj->put( $k, $temp );
286                     $recurse->( $temp, $v );
287                 }
288                 else {
289                     $obj->put( $k, $v );
290                 }
291             }
292         }
293     };
294     $recurse->( $self, $struct );
295
296     return 1;
297 }
298
299 #XXX Need to keep track of who has a fh to this file in order to
300 #XXX close them all prior to optimize on Win32/cygwin
301 sub optimize {
302     ##
303     # Rebuild entire database into new file, then move
304     # it back on top of original.
305     ##
306     my $self = shift->_get_self;
307
308 #XXX Need to create a new test for this
309 #    if ($self->_engine->storage->{links} > 1) {
310 #        $self->_throw_error("Cannot optimize: reference count is greater than 1");
311 #    }
312
313     #XXX Do we have to lock the tempfile?
314
315     #XXX Should we use tempfile() here instead of a hard-coded name?
316     my $temp_filename = $self->_engine->storage->{file} . '.tmp';
317     my $db_temp = DBM::Deep->new(
318         file => $temp_filename,
319         type => $self->_type,
320
321         # Bring over all the parameters that we need to bring over
322         ( map { $_ => $self->_engine->$_ } qw(
323             byte_size max_buckets data_sector_size num_txns
324         )),
325     );
326
327     $self->lock_exclusive;
328     $self->_engine->clear_cache;
329     $self->_copy_node( $db_temp );
330     $db_temp->_engine->storage->close;
331     undef $db_temp;
332
333     ##
334     # Attempt to copy user, group and permissions over to new file
335     ##
336     $self->_engine->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->_engine->storage->close;
348     }
349
350     if (!rename $temp_filename, $self->_engine->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->_engine->storage->close;
358
359     $self->_engine->storage->open;
360     $self->lock_exclusive;
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         engine      => $self->_engine,
378     );
379 }
380
381 #XXX Migrate this to the engine, where it really belongs and go through some
382 # API - stop poking in the innards of someone else..
383 {
384     my %is_legal_filter = map {
385         $_ => ~~1,
386     } qw(
387         store_key store_value
388         fetch_key fetch_value
389     );
390
391     sub set_filter {
392         my $self = shift->_get_self;
393         my $type = lc shift;
394         my $func = shift;
395
396         if ( $is_legal_filter{$type} ) {
397             $self->_engine->storage->{"filter_$type"} = $func;
398             return 1;
399         }
400
401         return;
402     }
403
404     sub filter_store_key   { $_[0]->set_filter( store_key   => $_[1] ); }
405     sub filter_store_value { $_[0]->set_filter( store_value => $_[1] ); }
406     sub filter_fetch_key   { $_[0]->set_filter( fetch_key   => $_[1] ); }
407     sub filter_fetch_value { $_[0]->set_filter( fetch_value => $_[1] ); }
408 }
409
410 sub begin_work {
411     my $self = shift->_get_self;
412     $self->lock_exclusive;
413     my $rv = eval { $self->_engine->begin_work( $self, @_ ) };
414     my $e = $@;
415     $self->unlock;
416     die $e if $e;
417     return $rv;
418 }
419
420 sub rollback {
421     my $self = shift->_get_self;
422     $self->lock_exclusive;
423     my $rv = eval { $self->_engine->rollback( $self, @_ ) };
424     my $e = $@;
425     $self->unlock;
426     die $e if $e;
427     return $rv;
428 }
429
430 sub commit {
431     my $self = shift->_get_self;
432     $self->lock_exclusive;
433     my $rv = eval { $self->_engine->commit( $self, @_ ) };
434     my $e = $@;
435     $self->unlock;
436     die $e if $e;
437     return $rv;
438 }
439
440 ##
441 # Accessor methods
442 ##
443
444 sub _engine {
445     my $self = $_[0]->_get_self;
446     return $self->{engine};
447 }
448
449 sub _type {
450     my $self = $_[0]->_get_self;
451     return $self->{type};
452 }
453
454 sub _base_offset {
455     my $self = $_[0]->_get_self;
456     return $self->{base_offset};
457 }
458
459 sub _staleness {
460     my $self = $_[0]->_get_self;
461     return $self->{staleness};
462 }
463
464 ##
465 # Utility methods
466 ##
467
468 sub _throw_error {
469     my $n = 0;
470     while( 1 ) {
471         my @caller = caller( ++$n );
472         next if $caller[0] =~ m/^DBM::Deep/;
473
474         die "DBM::Deep: $_[1] at $0 line $caller[2]\n";
475     }
476 }
477
478 sub STORE {
479     ##
480     # Store single hash key/value or array element in database.
481     ##
482     my $self = shift->_get_self;
483     my ($key, $value) = @_;
484     warn "STORE($self, '$key', '@{[defined$value?$value:'undef']}')\n" if DEBUG;
485
486     unless ( $self->_engine->storage->is_writable ) {
487         $self->_throw_error( 'Cannot write to a readonly filehandle' );
488     }
489
490     $self->lock_exclusive;
491
492     # User may be storing a complex value, in which case we do not want it run
493     # through the filtering system.
494     if ( !ref($value) && $self->_engine->storage->{filter_store_value} ) {
495         $value = $self->_engine->storage->{filter_store_value}->( $value );
496     }
497
498     my $x = $self->_engine->write_value( $self, $key, $value);
499
500     $self->unlock;
501
502     return 1;
503 }
504
505 sub FETCH {
506     ##
507     # Fetch single value or element given plain key or array index
508     ##
509     my $self = shift->_get_self;
510     my ($key) = @_;
511     warn "FETCH($self, '$key')\n" if DEBUG;
512
513     $self->lock_shared;
514
515     my $result = $self->_engine->read_value( $self, $key);
516
517     $self->unlock;
518
519     # Filters only apply to scalar values, so the ref check is making
520     # sure the fetched bucket is a scalar, not a child hash or array.
521     return ($result && !ref($result) && $self->_engine->storage->{filter_fetch_value})
522         ? $self->_engine->storage->{filter_fetch_value}->($result)
523         : $result;
524 }
525
526 sub DELETE {
527     ##
528     # Delete single key/value pair or element given plain key or array index
529     ##
530     my $self = shift->_get_self;
531     my ($key) = @_;
532     warn "DELETE($self, '$key')\n" if DEBUG;
533
534     unless ( $self->_engine->storage->is_writable ) {
535         $self->_throw_error( 'Cannot write to a readonly filehandle' );
536     }
537
538     $self->lock_exclusive;
539
540     ##
541     # Delete bucket
542     ##
543     my $value = $self->_engine->delete_key( $self, $key);
544
545     if (defined $value && !ref($value) && $self->_engine->storage->{filter_fetch_value}) {
546         $value = $self->_engine->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     $self->lock_shared;
563
564     my $result = $self->_engine->key_exists( $self, $key );
565
566     $self->unlock;
567
568     return $result;
569 }
570
571 sub CLEAR {
572     ##
573     # Clear all keys from hash, or all elements from array.
574     ##
575     my $self = shift->_get_self;
576     warn "CLEAR($self)\n" if DEBUG;
577
578     my $engine = $self->_engine;
579     unless ( $engine->storage->is_writable ) {
580         $self->_throw_error( 'Cannot write to a readonly filehandle' );
581     }
582
583     $self->lock_exclusive;
584
585     # Dispatch to the specific clearing functionality.
586     $engine->clear($self);
587
588     $self->unlock;
589
590     return 1;
591 }
592
593 ##
594 # Public method aliases
595 ##
596 sub put { (shift)->STORE( @_ ) }
597 sub store { (shift)->STORE( @_ ) }
598 sub get { (shift)->FETCH( @_ ) }
599 sub fetch { (shift)->FETCH( @_ ) }
600 sub delete { (shift)->DELETE( @_ ) }
601 sub exists { (shift)->EXISTS( @_ ) }
602 sub clear { (shift)->CLEAR( @_ ) }
603
604 sub _dump_file {shift->_get_self->_engine->_dump_file;}
605
606 1;
607 __END__