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