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