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