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