Conversion is partially complete. Lots of tests are failing, though
[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 # This initializer is called from the various TIE* methods. new() calls tie(),
80 # which allows for a single point of entry.
81 sub _init {
82     my $class = shift;
83     my ($args) = @_;
84
85     # locking implicitly enables autoflush
86     if ($args->{locking}) { $args->{autoflush} = 1; }
87
88     # These are the defaults to be optionally overridden below
89     my $self = bless {
90         type        => TYPE_HASH,
91         base_offset => undef,
92         staleness   => undef,
93         engine      => undef,
94     }, $class;
95
96     $args->{engine} = DBM::Deep::Engine->new( { %{$args}, obj => $self } )
97         unless exists $args->{engine};
98
99     # Grab the parameters we want to use
100     foreach my $param ( keys %$self ) {
101         next unless exists $args->{$param};
102         $self->{$param} = $args->{$param};
103     }
104
105     eval {
106       local $SIG{'__DIE__'};
107
108       $self->lock_exclusive;
109       $self->_engine->setup_fh( $self );
110       $self->unlock;
111     }; if ( $@ ) {
112       my $e = $@;
113       eval { local $SIG{'__DIE__'}; $self->unlock; };
114       die $e;
115     }
116
117     return $self;
118 }
119
120 sub TIEHASH {
121     shift;
122     require DBM::Deep::Hash;
123     return DBM::Deep::Hash->TIEHASH( @_ );
124 }
125
126 sub TIEARRAY {
127     shift;
128     require DBM::Deep::Array;
129     return DBM::Deep::Array->TIEARRAY( @_ );
130 }
131
132 sub lock_exclusive {
133     my $self = shift->_get_self;
134     return $self->_engine->lock_exclusive( $self );
135 }
136 *lock = \&lock_exclusive;
137 sub lock_shared {
138     my $self = shift->_get_self;
139     return $self->_engine->lock_shared( $self );
140 }
141
142 sub unlock {
143     my $self = shift->_get_self;
144     return $self->_engine->unlock( $self );
145 }
146
147 sub _copy_value {
148     my $self = shift->_get_self;
149     my ($spot, $value) = @_;
150
151     if ( !ref $value ) {
152         ${$spot} = $value;
153     }
154     else {
155         # This assumes hash or array only. This is a bad assumption moving forward.
156         # -RobK, 2008-05-27
157         my $r = Scalar::Util::reftype( $value );
158         my $tied;
159         if ( $r eq 'ARRAY' ) {
160             $tied = tied(@$value);
161         }
162         else {
163             $tied = tied(%$value);
164         }
165
166         if ( eval { local $SIG{__DIE__}; $tied->isa( 'DBM::Deep' ) } ) {
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( 'DBM::Deep') ) {
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     ##
198     # Recursively export into standard Perl hashes and arrays.
199     ##
200     my $self = shift->_get_self;
201
202     my $temp = $self->_repr;
203
204     $self->lock_exclusive;
205     $self->_copy_node( $temp );
206     $self->unlock;
207
208     my $classname = $self->_engine->get_classname( $self );
209     if ( defined $classname ) {
210       bless $temp, $classname;
211     }
212
213     return $temp;
214 }
215
216 sub _check_legality {
217     my $self = shift;
218     my ($val) = @_;
219
220     my $r = Scalar::Util::reftype( $val );
221
222     return $r if !defined $r || '' eq $r;
223     return $r if 'HASH' eq $r;
224     return $r if 'ARRAY' eq $r;
225
226     DBM::Deep->_throw_error(
227         "Storage of references of type '$r' is not supported."
228     );
229 }
230
231 sub import {
232     # Perl calls import() on use -- ignore
233     return if !ref $_[0];
234
235     my $self = shift->_get_self;
236     my ($struct) = @_;
237
238     my $type = $self->_check_legality( $struct );
239     if ( !$type ) {
240         DBM::Deep->_throw_error( "Cannot import a scalar" );
241     }
242
243     if ( substr( $type, 0, 1 ) ne $self->_type ) {
244         DBM::Deep->_throw_error(
245             "Cannot import " . ('HASH' eq $type ? 'a hash' : 'an array')
246             . " into " . ('HASH' eq $type ? 'an array' : 'a hash')
247         );
248     }
249
250     my %seen;
251     my $recurse;
252     $recurse = sub {
253         my ($db, $val) = @_;
254
255         my $obj = 'HASH' eq Scalar::Util::reftype( $db ) ? tied(%$db) : tied(@$db);
256         $obj ||= $db;
257
258         my $r = $self->_check_legality( $val );
259         if ( 'HASH' eq $r ) {
260             while ( my ($k, $v) = each %$val ) {
261                 my $r = $self->_check_legality( $v );
262                 if ( $r ) {
263                     my $temp = 'HASH' eq $r ? {} : [];
264                     if ( my $c = Scalar::Util::blessed( $v ) ) {
265                         bless $temp, $c;
266                     }
267                     $obj->put( $k, $temp );
268                     $recurse->( $temp, $v );
269                 }
270                 else {
271                     $obj->put( $k, $v );
272                 }
273             }
274         }
275         elsif ( 'ARRAY' eq $r ) {
276             foreach my $k ( 0 .. $#$val ) {
277                 my $v = $val->[$k];
278                 my $r = $self->_check_legality( $v );
279                 if ( $r ) {
280                     my $temp = 'HASH' eq $r ? {} : [];
281                     if ( my $c = Scalar::Util::blessed( $v ) ) {
282                         bless $temp, $c;
283                     }
284                     $obj->put( $k, $temp );
285                     $recurse->( $temp, $v );
286                 }
287                 else {
288                     $obj->put( $k, $v );
289                 }
290             }
291         }
292     };
293     $recurse->( $self, $struct );
294
295     return 1;
296 }
297
298 #XXX Need to keep track of who has a fh to this file in order to
299 #XXX close them all prior to optimize on Win32/cygwin
300 sub optimize {
301     ##
302     # Rebuild entire database into new file, then move
303     # it back on top of original.
304     ##
305     my $self = shift->_get_self;
306
307 #XXX Need to create a new test for this
308 #    if ($self->_engine->storage->{links} > 1) {
309 #        $self->_throw_error("Cannot optimize: reference count is greater than 1");
310 #    }
311
312     #XXX Do we have to lock the tempfile?
313
314     #XXX Should we use tempfile() here instead of a hard-coded name?
315     my $temp_filename = $self->_engine->storage->{file} . '.tmp';
316     my $db_temp = DBM::Deep->new(
317         file => $temp_filename,
318         type => $self->_type,
319
320         # Bring over all the parameters that we need to bring over
321         ( map { $_ => $self->_engine->$_ } qw(
322             byte_size max_buckets data_sector_size num_txns
323         )),
324     );
325
326     $self->lock_exclusive;
327     $self->_engine->clear_cache;
328     $self->_copy_node( $db_temp );
329     $db_temp->_engine->storage->close;
330     undef $db_temp;
331
332     ##
333     # Attempt to copy user, group and permissions over to new file
334     ##
335     $self->_engine->storage->copy_stats( $temp_filename );
336
337     # q.v. perlport for more information on this variable
338     if ( $^O eq 'MSWin32' || $^O eq 'cygwin' ) {
339         ##
340         # Potential race condition when optmizing on Win32 with locking.
341         # The Windows filesystem requires that the filehandle be closed
342         # before it is overwritten with rename().  This could be redone
343         # with a soft copy.
344         ##
345         $self->unlock;
346         $self->_engine->storage->close;
347     }
348
349     if (!rename $temp_filename, $self->_engine->storage->{file}) {
350         unlink $temp_filename;
351         $self->unlock;
352         $self->_throw_error("Optimize failed: Cannot copy temp file over original: $!");
353     }
354
355     $self->unlock;
356     $self->_engine->storage->close;
357
358     $self->_engine->storage->open;
359     $self->lock_exclusive;
360     $self->_engine->setup_fh( $self );
361     $self->unlock;
362
363     return 1;
364 }
365
366 sub clone {
367     ##
368     # Make copy of object and return
369     ##
370     my $self = shift->_get_self;
371
372     return DBM::Deep->new(
373         type        => $self->_type,
374         base_offset => $self->_base_offset,
375         staleness   => $self->_staleness,
376         engine      => $self->_engine,
377     );
378 }
379
380 #XXX Migrate this to the engine, where it really belongs and go through some
381 # API - stop poking in the innards of someone else..
382 {
383     my %is_legal_filter = map {
384         $_ => ~~1,
385     } qw(
386         store_key store_value
387         fetch_key fetch_value
388     );
389
390     sub set_filter {
391         my $self = shift->_get_self;
392         my $type = lc shift;
393         my $func = shift;
394
395         if ( $is_legal_filter{$type} ) {
396             $self->_engine->storage->{"filter_$type"} = $func;
397             return 1;
398         }
399
400         return;
401     }
402
403     sub filter_store_key   { $_[0]->set_filter( store_key   => $_[1] ); }
404     sub filter_store_value { $_[0]->set_filter( store_value => $_[1] ); }
405     sub filter_fetch_key   { $_[0]->set_filter( fetch_key   => $_[1] ); }
406     sub filter_fetch_value { $_[0]->set_filter( fetch_value => $_[1] ); }
407 }
408
409 sub begin_work {
410     my $self = shift->_get_self;
411     return $self->_engine->begin_work( $self, @_ );
412 }
413
414 sub rollback {
415     my $self = shift->_get_self;
416     return $self->_engine->rollback( $self, @_ );
417 }
418
419 sub commit {
420     my $self = shift->_get_self;
421     return $self->_engine->commit( $self, @_ );
422 }
423
424 ##
425 # Accessor methods
426 ##
427
428 sub _engine {
429     my $self = $_[0]->_get_self;
430     return $self->{engine};
431 }
432
433 sub _type {
434     my $self = $_[0]->_get_self;
435     return $self->{type};
436 }
437
438 sub _base_offset {
439     my $self = $_[0]->_get_self;
440     return $self->{base_offset};
441 }
442
443 sub _staleness {
444     my $self = $_[0]->_get_self;
445     return $self->{staleness};
446 }
447
448 ##
449 # Utility methods
450 ##
451
452 sub _throw_error {
453     my $n = 0;
454     while( 1 ) {
455         my @caller = caller( ++$n );
456         next if $caller[0] =~ m/^DBM::Deep/;
457
458         die "DBM::Deep: $_[1] at $0 line $caller[2]\n";
459     }
460 }
461
462 sub STORE {
463     ##
464     # Store single hash key/value or array element in database.
465     ##
466     my $self = shift->_get_self;
467     my ($key, $value) = @_;
468     warn "STORE($self, $key, @{[defined$value?$value:'undef']})\n" if DEBUG;
469
470     unless ( $self->_engine->storage->is_writable ) {
471         $self->_throw_error( 'Cannot write to a readonly filehandle' );
472     }
473
474     $self->lock_exclusive;
475
476     # User may be storing a complex value, in which case we do not want it run
477     # through the filtering system.
478     if ( !ref($value) && $self->_engine->storage->{filter_store_value} ) {
479         $value = $self->_engine->storage->{filter_store_value}->( $value );
480     }
481
482     $self->_engine->write_value( $self, $key, $value);
483
484     $self->unlock;
485
486     return 1;
487 }
488
489 sub FETCH {
490     ##
491     # Fetch single value or element given plain key or array index
492     ##
493     my $self = shift->_get_self;
494     my ($key) = @_;
495     warn "FETCH($self,$key)\n" if DEBUG;
496
497     $self->lock_shared;
498
499     my $result = $self->_engine->read_value( $self, $key);
500
501     $self->unlock;
502
503     # Filters only apply to scalar values, so the ref check is making
504     # sure the fetched bucket is a scalar, not a child hash or array.
505     return ($result && !ref($result) && $self->_engine->storage->{filter_fetch_value})
506         ? $self->_engine->storage->{filter_fetch_value}->($result)
507         : $result;
508 }
509
510 sub DELETE {
511     ##
512     # Delete single key/value pair or element given plain key or array index
513     ##
514     my $self = shift->_get_self;
515     my ($key) = @_;
516     warn "DELETE($self,$key)\n" if DEBUG;
517
518     unless ( $self->_engine->storage->is_writable ) {
519         $self->_throw_error( 'Cannot write to a readonly filehandle' );
520     }
521
522     $self->lock_exclusive;
523
524     ##
525     # Delete bucket
526     ##
527     my $value = $self->_engine->delete_key( $self, $key);
528
529     if (defined $value && !ref($value) && $self->_engine->storage->{filter_fetch_value}) {
530         $value = $self->_engine->storage->{filter_fetch_value}->($value);
531     }
532
533     $self->unlock;
534
535     return $value;
536 }
537
538 sub EXISTS {
539     ##
540     # Check if a single key or element exists given plain key or array index
541     ##
542     my $self = shift->_get_self;
543     my ($key) = @_;
544     warn "EXISTS($self,$key)\n" if DEBUG;
545
546     $self->lock_shared;
547
548     my $result = $self->_engine->key_exists( $self, $key );
549
550     $self->unlock;
551
552     return $result;
553 }
554
555 sub CLEAR {
556     ##
557     # Clear all keys from hash, or all elements from array.
558     ##
559     my $self = shift->_get_self;
560     warn "CLEAR($self)\n" if DEBUG;
561
562     unless ( $self->_engine->storage->is_writable ) {
563         $self->_throw_error( 'Cannot write to a readonly filehandle' );
564     }
565
566     $self->lock_exclusive;
567
568     #XXX Rewrite this dreck to do it in the engine as a tight loop vs.
569     # iterating over keys - such a WASTE - is this required for transactional
570     # clearning?! Surely that can be detected in the engine ...
571     if ( $self->_type eq TYPE_HASH ) {
572         my $key = $self->first_key;
573         while ( $key ) {
574             # Retrieve the key before deleting because we depend on next_key
575             my $next_key = $self->next_key( $key );
576             $self->_engine->delete_key( $self, $key, $key );
577             $key = $next_key;
578         }
579     }
580     else {
581         my $size = $self->FETCHSIZE;
582         for my $key ( 0 .. $size - 1 ) {
583             $self->_engine->delete_key( $self, $key, $key );
584         }
585         $self->STORESIZE( 0 );
586     }
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__