Added a comment as to where an allocation error is occurring that crashes perl
[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     return $self->_engine->begin_work( $self, @_ );
423 }
424
425 sub rollback {
426     my $self = shift->_get_self;
427     return $self->_engine->rollback( $self, @_ );
428 }
429
430 sub commit {
431     my $self = shift->_get_self;
432     return $self->_engine->commit( $self, @_ );
433 }
434
435 ##
436 # Accessor methods
437 ##
438
439 sub _engine {
440     my $self = $_[0]->_get_self;
441     return $self->{engine};
442 }
443
444 sub _type {
445     my $self = $_[0]->_get_self;
446     return $self->{type};
447 }
448
449 sub _base_offset {
450     my $self = $_[0]->_get_self;
451     return $self->{base_offset};
452 }
453
454 sub _staleness {
455     my $self = $_[0]->_get_self;
456     return $self->{staleness};
457 }
458
459 ##
460 # Utility methods
461 ##
462
463 sub _throw_error {
464     my $n = 0;
465     while( 1 ) {
466         my @caller = caller( ++$n );
467         next if $caller[0] =~ m/^DBM::Deep/;
468
469         die "DBM::Deep: $_[1] at $0 line $caller[2]\n";
470     }
471 }
472
473 sub STORE {
474     ##
475     # Store single hash key/value or array element in database.
476     ##
477     my $self = shift->_get_self;
478     my ($key, $value) = @_;
479     warn "STORE($self, $key, @{[defined$value?$value:'undef']})\n" if DEBUG;
480
481     unless ( $self->_engine->storage->is_writable ) {
482         $self->_throw_error( 'Cannot write to a readonly filehandle' );
483     }
484
485     $self->lock_exclusive;
486
487     # User may be storing a complex value, in which case we do not want it run
488     # through the filtering system.
489     if ( !ref($value) && $self->_engine->storage->{filter_store_value} ) {
490         $value = $self->_engine->storage->{filter_store_value}->( $value );
491     }
492
493     $self->_engine->write_value( $self, $key, $value);
494
495     $self->unlock;
496
497     return 1;
498 }
499
500 sub FETCH {
501     ##
502     # Fetch single value or element given plain key or array index
503     ##
504     my $self = shift->_get_self;
505     my ($key) = @_;
506     warn "FETCH($self,$key)\n" if DEBUG;
507
508     $self->lock_shared;
509
510     my $result = $self->_engine->read_value( $self, $key);
511
512     $self->unlock;
513
514     # Filters only apply to scalar values, so the ref check is making
515     # sure the fetched bucket is a scalar, not a child hash or array.
516     return ($result && !ref($result) && $self->_engine->storage->{filter_fetch_value})
517         ? $self->_engine->storage->{filter_fetch_value}->($result)
518         : $result;
519 }
520
521 sub DELETE {
522     ##
523     # Delete single key/value pair or element given plain key or array index
524     ##
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 sub EXISTS {
550     ##
551     # Check if a single key or element exists given plain key or array index
552     ##
553     my $self = shift->_get_self;
554     my ($key) = @_;
555     warn "EXISTS($self,$key)\n" if DEBUG;
556
557     $self->lock_shared;
558
559     my $result = $self->_engine->key_exists( $self, $key );
560
561     $self->unlock;
562
563     return $result;
564 }
565
566 sub CLEAR {
567     ##
568     # Clear all keys from hash, or all elements from array.
569     ##
570     my $self = shift->_get_self;
571     warn "CLEAR($self)\n" if DEBUG;
572
573     unless ( $self->_engine->storage->is_writable ) {
574         $self->_throw_error( 'Cannot write to a readonly filehandle' );
575     }
576
577     $self->lock_exclusive;
578
579     #XXX Rewrite this dreck to do it in the engine as a tight loop vs.
580     # iterating over keys - such a WASTE - is this required for transactional
581     # clearning?! Surely that can be detected in the engine ...
582     if ( $self->_type eq TYPE_HASH ) {
583         my $key = $self->first_key;
584         while ( $key ) {
585             # Retrieve the key before deleting because we depend on next_key
586             my $next_key = $self->next_key( $key );
587             $self->_engine->delete_key( $self, $key, $key );
588             $key = $next_key;
589         }
590     }
591     else {
592         my $size = $self->FETCHSIZE;
593         for my $key ( 0 .. $size - 1 ) {
594             $self->_engine->delete_key( $self, $key, $key );
595         }
596         $self->STORESIZE( 0 );
597     }
598
599     $self->unlock;
600
601     return 1;
602 }
603
604 ##
605 # Public method aliases
606 ##
607 sub put { (shift)->STORE( @_ ) }
608 sub store { (shift)->STORE( @_ ) }
609 sub get { (shift)->FETCH( @_ ) }
610 sub fetch { (shift)->FETCH( @_ ) }
611 sub delete { (shift)->DELETE( @_ ) }
612 sub exists { (shift)->EXISTS( @_ ) }
613 sub clear { (shift)->CLEAR( @_ ) }
614
615 sub _dump_file {shift->_get_self->_engine->_dump_file;}
616
617 1;
618 __END__