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