Fixed immediate dependence on DBI
[dbsrgits/DBM-Deep.git] / lib / DBM / Deep.pm
CommitLineData
ffed8b01 1package DBM::Deep;
2
2120a181 3use 5.006_000;
460b1067 4
ffed8b01 5use strict;
065b45be 6use warnings FATAL => 'all';
8b957036 7
bac1b5d5 8our $VERSION = q(1.0019_002);
86867f3a 9
ffed8b01 10use Scalar::Util ();
ffed8b01 11
c57b19c6 12use overload
13 '""' => sub { overload::StrVal( $_[0] ) },
14 fallback => 1;
15
6e6789b0 16use constant DEBUG => 0;
17
addbe56a 18use DBM::Deep::Engine;
19
2120a181 20sub TYPE_HASH () { DBM::Deep::Engine->SIG_HASH }
21sub TYPE_ARRAY () { DBM::Deep::Engine->SIG_ARRAY }
ffed8b01 22
2120a181 23# This is used in all the children of this class in their TIE<type> methods.
0ca7ea98 24sub _get_args {
25 my $proto = shift;
26
27 my $args;
28 if (scalar(@_) > 1) {
29 if ( @_ % 2 ) {
30 $proto->_throw_error( "Odd number of parameters to " . (caller(1))[2] );
31 }
32 $args = {@_};
33 }
d0b74c17 34 elsif ( ref $_[0] ) {
4d35d856 35 unless ( eval { local $SIG{'__DIE__'}; %{$_[0]} || 1 } ) {
0ca7ea98 36 $proto->_throw_error( "Not a hashref in args to " . (caller(1))[2] );
37 }
38 $args = $_[0];
39 }
d0b74c17 40 else {
0ca7ea98 41 $args = { file => shift };
42 }
43
44 return $args;
45}
46
d426259c 47# Class constructor method for Perl OO interface.
48# Calls tie() and returns blessed reference to tied hash or array,
49# providing a hybrid OO/tie interface.
ffed8b01 50sub new {
d0b74c17 51 my $class = shift;
52 my $args = $class->_get_args( @_ );
4f0f6fff 53 my $self;
54
d0b74c17 55 if (defined($args->{type}) && $args->{type} eq TYPE_ARRAY) {
6fe26b29 56 $class = 'DBM::Deep::Array';
57 require DBM::Deep::Array;
d0b74c17 58 tie @$self, $class, %$args;
59 }
60 else {
6fe26b29 61 $class = 'DBM::Deep::Hash';
62 require DBM::Deep::Hash;
d0b74c17 63 tie %$self, $class, %$args;
64 }
ffed8b01 65
d0b74c17 66 return bless $self, $class;
ffed8b01 67}
68
96041a25 69# This initializer is called from the various TIE* methods. new() calls tie(),
70# which allows for a single point of entry.
0795f290 71sub _init {
0795f290 72 my $class = shift;
994ccd8e 73 my ($args) = @_;
0795f290 74
460b1067 75 # locking implicitly enables autoflush
76 if ($args->{locking}) { $args->{autoflush} = 1; }
77
0795f290 78 # These are the defaults to be optionally overridden below
79 my $self = bless {
95967a5e 80 type => TYPE_HASH,
e06824f8 81 base_offset => undef,
2120a181 82 staleness => undef,
2120a181 83 engine => undef,
0795f290 84 }, $class;
2120a181 85
2c70efe1 86 unless ( exists $args->{engine} ) {
87 my $class = exists $args->{dbi}
88 ? 'DBM::Deep::Engine::DBI'
89 : 'DBM::Deep::Engine::File';
90
addbe56a 91 eval "use $class"; die $@ if $@;
2c70efe1 92 $args->{engine} = $class->new({
93 %{$args},
94 obj => $self,
95 });
96 }
8db25060 97
fde3db1a 98 # Grab the parameters we want to use
0795f290 99 foreach my $param ( keys %$self ) {
100 next unless exists $args->{$param};
3e9498a1 101 $self->{$param} = $args->{$param};
ffed8b01 102 }
d0b74c17 103
2120a181 104 eval {
2c70efe1 105 local $SIG{'__DIE__'};
0795f290 106
2c70efe1 107 $self->lock_exclusive;
108 $self->_engine->setup( $self );
109 $self->unlock;
2120a181 110 }; if ( $@ ) {
2c70efe1 111 my $e = $@;
112 eval { local $SIG{'__DIE__'}; $self->unlock; };
113 die $e;
2120a181 114 }
359a01ac 115
0795f290 116 return $self;
ffed8b01 117}
118
ffed8b01 119sub TIEHASH {
6fe26b29 120 shift;
121 require DBM::Deep::Hash;
122 return DBM::Deep::Hash->TIEHASH( @_ );
ffed8b01 123}
124
125sub TIEARRAY {
6fe26b29 126 shift;
127 require DBM::Deep::Array;
128 return DBM::Deep::Array->TIEARRAY( @_ );
ffed8b01 129}
130
5c0756fc 131sub lock_exclusive {
994ccd8e 132 my $self = shift->_get_self;
9c87a079 133 return $self->_engine->lock_exclusive( $self, @_ );
5c0756fc 134}
135*lock = \&lock_exclusive;
136sub lock_shared {
137 my $self = shift->_get_self;
9c87a079 138 return $self->_engine->lock_shared( $self, @_ );
ffed8b01 139}
140
141sub unlock {
994ccd8e 142 my $self = shift->_get_self;
9c87a079 143 return $self->_engine->unlock( $self, @_ );
ffed8b01 144}
145
906c8e01 146sub _copy_value {
147 my $self = shift->_get_self;
148 my ($spot, $value) = @_;
149
150 if ( !ref $value ) {
151 ${$spot} = $value;
152 }
906c8e01 153 else {
154 my $r = Scalar::Util::reftype( $value );
edd45134 155 my $tied;
906c8e01 156 if ( $r eq 'ARRAY' ) {
edd45134 157 $tied = tied(@$value);
906c8e01 158 }
2c70efe1 159 elsif ( $r eq 'HASH' ) {
edd45134 160 $tied = tied(%$value);
161 }
2c70efe1 162 else {
163 __PACKAGE__->_throw_error( "Unknown type for '$value'" );
164 }
edd45134 165
2c70efe1 166 if ( eval { local $SIG{__DIE__}; $tied->isa( __PACKAGE__ ) } ) {
edd45134 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 );
2c70efe1 180 if ( defined $c && !$c->isa( __PACKAGE__ ) ) {
edd45134 181 ${$spot} = bless ${$spot}, $c
906c8e01 182 }
906c8e01 183 }
184
185 return 1;
186}
187
2120a181 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#}
ffed8b01 195
196sub export {
994ccd8e 197 my $self = shift->_get_self;
d0b74c17 198
f9c33187 199 my $temp = $self->_repr;
d0b74c17 200
5c0756fc 201 $self->lock_exclusive;
d0b74c17 202 $self->_copy_node( $temp );
5c0756fc 203 $self->unlock;
d0b74c17 204
2120a181 205 my $classname = $self->_engine->get_classname( $self );
206 if ( defined $classname ) {
207 bless $temp, $classname;
68f943b3 208 }
209
d0b74c17 210 return $temp;
ffed8b01 211}
212
e00d0eb3 213sub _check_legality {
214 my $self = shift;
215 my ($val) = @_;
216
217 my $r = Scalar::Util::reftype( $val );
218
219 return $r if !defined $r || '' eq $r;
220 return $r if 'HASH' eq $r;
221 return $r if 'ARRAY' eq $r;
222
2c70efe1 223 __PACKAGE__->_throw_error(
e00d0eb3 224 "Storage of references of type '$r' is not supported."
225 );
226}
227
ffed8b01 228sub import {
d426259c 229 return if !ref $_[0]; # Perl calls import() on use -- ignore
d0b74c17 230
994ccd8e 231 my $self = shift->_get_self;
232 my ($struct) = @_;
d0b74c17 233
e00d0eb3 234 my $type = $self->_check_legality( $struct );
235 if ( !$type ) {
2c70efe1 236 __PACKAGE__->_throw_error( "Cannot import a scalar" );
d0b74c17 237 }
238
e00d0eb3 239 if ( substr( $type, 0, 1 ) ne $self->_type ) {
2c70efe1 240 __PACKAGE__->_throw_error(
e00d0eb3 241 "Cannot import " . ('HASH' eq $type ? 'a hash' : 'an array')
242 . " into " . ('HASH' eq $type ? 'an array' : 'a hash')
243 );
7a960a12 244 }
245
e00d0eb3 246 my %seen;
247 my $recurse;
248 $recurse = sub {
249 my ($db, $val) = @_;
250
251 my $obj = 'HASH' eq Scalar::Util::reftype( $db ) ? tied(%$db) : tied(@$db);
252 $obj ||= $db;
253
254 my $r = $self->_check_legality( $val );
255 if ( 'HASH' eq $r ) {
256 while ( my ($k, $v) = each %$val ) {
257 my $r = $self->_check_legality( $v );
258 if ( $r ) {
259 my $temp = 'HASH' eq $r ? {} : [];
260 if ( my $c = Scalar::Util::blessed( $v ) ) {
261 bless $temp, $c;
262 }
263 $obj->put( $k, $temp );
264 $recurse->( $temp, $v );
265 }
266 else {
267 $obj->put( $k, $v );
268 }
269 }
270 }
271 elsif ( 'ARRAY' eq $r ) {
272 foreach my $k ( 0 .. $#$val ) {
273 my $v = $val->[$k];
274 my $r = $self->_check_legality( $v );
275 if ( $r ) {
276 my $temp = 'HASH' eq $r ? {} : [];
277 if ( my $c = Scalar::Util::blessed( $v ) ) {
278 bless $temp, $c;
279 }
280 $obj->put( $k, $temp );
281 $recurse->( $temp, $v );
282 }
283 else {
284 $obj->put( $k, $v );
285 }
286 }
287 }
288 };
289 $recurse->( $self, $struct );
290
7a960a12 291 return 1;
ffed8b01 292}
293
13ff93d5 294#XXX Need to keep track of who has a fh to this file in order to
295#XXX close them all prior to optimize on Win32/cygwin
d426259c 296# Rebuild entire database into new file, then move
297# it back on top of original.
ffed8b01 298sub optimize {
994ccd8e 299 my $self = shift->_get_self;
cc4bef86 300
d426259c 301 # Optimizing is only something we need to do when we're working with our
302 # own file format. Otherwise, let the other guy do the optimizations.
51e9eee3 303 return unless $self->_engine->isa( 'DBM::Deep::Engine::File' );
d426259c 304
cc4bef86 305#XXX Need to create a new test for this
f1879fdc 306# if ($self->_engine->storage->{links} > 1) {
1400a48e 307# $self->_throw_error("Cannot optimize: reference count is greater than 1");
d0b74c17 308# }
309
7a960a12 310 #XXX Do we have to lock the tempfile?
311
e00d0eb3 312 #XXX Should we use tempfile() here instead of a hard-coded name?
f1879fdc 313 my $temp_filename = $self->_engine->storage->{file} . '.tmp';
2c70efe1 314 my $db_temp = __PACKAGE__->new(
6e6789b0 315 file => $temp_filename,
2120a181 316 type => $self->_type,
317
318 # Bring over all the parameters that we need to bring over
888453b9 319 ( map { $_ => $self->_engine->$_ } qw(
320 byte_size max_buckets data_sector_size num_txns
321 )),
d0b74c17 322 );
d0b74c17 323
5c0756fc 324 $self->lock_exclusive;
c57b19c6 325 $self->_engine->clear_cache;
d0b74c17 326 $self->_copy_node( $db_temp );
f1879fdc 327 $db_temp->_engine->storage->close;
d0b74c17 328 undef $db_temp;
329
330 ##
331 # Attempt to copy user, group and permissions over to new file
332 ##
f1879fdc 333 $self->_engine->storage->copy_stats( $temp_filename );
d0b74c17 334
ffed8b01 335 # q.v. perlport for more information on this variable
90f93b43 336 if ( $^O eq 'MSWin32' || $^O eq 'cygwin' ) {
d0b74c17 337 ##
338 # Potential race condition when optmizing on Win32 with locking.
339 # The Windows filesystem requires that the filehandle be closed
340 # before it is overwritten with rename(). This could be redone
341 # with a soft copy.
342 ##
5c0756fc 343 $self->unlock;
f1879fdc 344 $self->_engine->storage->close;
d0b74c17 345 }
346
f1879fdc 347 if (!rename $temp_filename, $self->_engine->storage->{file}) {
6e6789b0 348 unlink $temp_filename;
5c0756fc 349 $self->unlock;
1400a48e 350 $self->_throw_error("Optimize failed: Cannot copy temp file over original: $!");
d0b74c17 351 }
352
5c0756fc 353 $self->unlock;
f1879fdc 354 $self->_engine->storage->close;
2120a181 355
f1879fdc 356 $self->_engine->storage->open;
5c0756fc 357 $self->lock_exclusive;
f4d0ac97 358 $self->_engine->setup( $self );
5c0756fc 359 $self->unlock;
70b55428 360
d0b74c17 361 return 1;
ffed8b01 362}
363
364sub clone {
d0b74c17 365 ##
366 # Make copy of object and return
367 ##
994ccd8e 368 my $self = shift->_get_self;
d0b74c17 369
2c70efe1 370 return __PACKAGE__->new(
c3aafc14 371 type => $self->_type,
d0b74c17 372 base_offset => $self->_base_offset,
2120a181 373 staleness => $self->_staleness,
2120a181 374 engine => $self->_engine,
d0b74c17 375 );
ffed8b01 376}
377
580e5ee2 378sub supports {
379 my $self = shift;
380 return $self->_engine->supports( @_ );
381}
382
2120a181 383#XXX Migrate this to the engine, where it really belongs and go through some
384# API - stop poking in the innards of someone else..
ffed8b01 385{
386 my %is_legal_filter = map {
387 $_ => ~~1,
388 } qw(
389 store_key store_value
390 fetch_key fetch_value
391 );
392
393 sub set_filter {
994ccd8e 394 my $self = shift->_get_self;
395 my $type = lc shift;
396 my $func = shift;
d0b74c17 397
ffed8b01 398 if ( $is_legal_filter{$type} ) {
f1879fdc 399 $self->_engine->storage->{"filter_$type"} = $func;
ffed8b01 400 return 1;
401 }
402
403 return;
404 }
888453b9 405
406 sub filter_store_key { $_[0]->set_filter( store_key => $_[1] ); }
407 sub filter_store_value { $_[0]->set_filter( store_value => $_[1] ); }
408 sub filter_fetch_key { $_[0]->set_filter( fetch_key => $_[1] ); }
409 sub filter_fetch_value { $_[0]->set_filter( fetch_value => $_[1] ); }
ffed8b01 410}
411
fee0243f 412sub begin_work {
413 my $self = shift->_get_self;
db2eb673 414 $self->lock_exclusive;
c65299b4 415 my $rv = eval { $self->_engine->begin_work( $self, @_ ) };
416 my $e = $@;
db2eb673 417 $self->unlock;
c65299b4 418 die $e if $e;
db2eb673 419 return $rv;
fee0243f 420}
421
422sub rollback {
423 my $self = shift->_get_self;
db2eb673 424 $self->lock_exclusive;
c65299b4 425 my $rv = eval { $self->_engine->rollback( $self, @_ ) };
426 my $e = $@;
db2eb673 427 $self->unlock;
c65299b4 428 die $e if $e;
db2eb673 429 return $rv;
fee0243f 430}
431
359a01ac 432sub commit {
433 my $self = shift->_get_self;
db2eb673 434 $self->lock_exclusive;
c65299b4 435 my $rv = eval { $self->_engine->commit( $self, @_ ) };
436 my $e = $@;
db2eb673 437 $self->unlock;
c65299b4 438 die $e if $e;
db2eb673 439 return $rv;
359a01ac 440}
fee0243f 441
ffed8b01 442# Accessor methods
72e315ac 443sub _engine {
444 my $self = $_[0]->_get_self;
445 return $self->{engine};
446}
447
4d35d856 448sub _type {
2ac02042 449 my $self = $_[0]->_get_self;
d0b74c17 450 return $self->{type};
ffed8b01 451}
452
4d35d856 453sub _base_offset {
2ac02042 454 my $self = $_[0]->_get_self;
d0b74c17 455 return $self->{base_offset};
ffed8b01 456}
457
2120a181 458sub _staleness {
459 my $self = $_[0]->_get_self;
460 return $self->{staleness};
461}
462
ffed8b01 463# Utility methods
261d1296 464sub _throw_error {
807f63a7 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";
807f63a7 471 }
ffed8b01 472}
473
d426259c 474# Store single hash key/value or array element in database.
ffed8b01 475sub STORE {
d0b74c17 476 my $self = shift->_get_self;
2120a181 477 my ($key, $value) = @_;
c803879b 478 warn "STORE($self, '$key', '@{[defined$value?$value:'undef']}')\n" if DEBUG;
81d3d316 479
f1879fdc 480 unless ( $self->_engine->storage->is_writable ) {
acd4faf2 481 $self->_throw_error( 'Cannot write to a readonly filehandle' );
482 }
d0b74c17 483
5c0756fc 484 $self->lock_exclusive;
d0b74c17 485
0cb639bd 486 # User may be storing a complex value, in which case we do not want it run
487 # through the filtering system.
f1879fdc 488 if ( !ref($value) && $self->_engine->storage->{filter_store_value} ) {
489 $value = $self->_engine->storage->{filter_store_value}->( $value );
d0b74c17 490 }
491
7c927437 492 eval {
493 $self->_engine->write_value( $self, $key, $value );
494 }; if ( my $e = $@ ) {
495 $self->unlock;
496 die $e;
497 }
d0b74c17 498
5c0756fc 499 $self->unlock;
d0b74c17 500
86867f3a 501 return 1;
ffed8b01 502}
503
d426259c 504# Fetch single value or element given plain key or array index
ffed8b01 505sub FETCH {
cb79ec85 506 my $self = shift->_get_self;
2120a181 507 my ($key) = @_;
c803879b 508 warn "FETCH($self, '$key')\n" if DEBUG;
ffed8b01 509
5c0756fc 510 $self->lock_shared;
d0b74c17 511
2c70efe1 512 my $result = $self->_engine->read_value( $self, $key );
d0b74c17 513
5c0756fc 514 $self->unlock;
d0b74c17 515
a86430bd 516 # Filters only apply to scalar values, so the ref check is making
517 # sure the fetched bucket is a scalar, not a child hash or array.
f1879fdc 518 return ($result && !ref($result) && $self->_engine->storage->{filter_fetch_value})
519 ? $self->_engine->storage->{filter_fetch_value}->($result)
cb79ec85 520 : $result;
ffed8b01 521}
522
d426259c 523# Delete single key/value pair or element given plain key or array index
ffed8b01 524sub DELETE {
a97c8f67 525 my $self = shift->_get_self;
2120a181 526 my ($key) = @_;
c803879b 527 warn "DELETE($self, '$key')\n" if DEBUG;
d0b74c17 528
f1879fdc 529 unless ( $self->_engine->storage->is_writable ) {
a86430bd 530 $self->_throw_error( 'Cannot write to a readonly filehandle' );
531 }
d0b74c17 532
5c0756fc 533 $self->lock_exclusive;
d0b74c17 534
d0b74c17 535 ##
536 # Delete bucket
537 ##
2120a181 538 my $value = $self->_engine->delete_key( $self, $key);
a86430bd 539
f1879fdc 540 if (defined $value && !ref($value) && $self->_engine->storage->{filter_fetch_value}) {
541 $value = $self->_engine->storage->{filter_fetch_value}->($value);
3b6a5056 542 }
543
5c0756fc 544 $self->unlock;
d0b74c17 545
546 return $value;
ffed8b01 547}
548
d426259c 549# Check if a single key or element exists given plain key or array index
ffed8b01 550sub EXISTS {
a97c8f67 551 my $self = shift->_get_self;
552 my ($key) = @_;
c803879b 553 warn "EXISTS($self, '$key')\n" if DEBUG;
d0b74c17 554
5c0756fc 555 $self->lock_shared;
d0b74c17 556
2120a181 557 my $result = $self->_engine->key_exists( $self, $key );
d0b74c17 558
5c0756fc 559 $self->unlock;
d0b74c17 560
561 return $result;
ffed8b01 562}
563
d426259c 564# Clear all keys from hash, or all elements from array.
ffed8b01 565sub CLEAR {
a97c8f67 566 my $self = shift->_get_self;
6e6789b0 567 warn "CLEAR($self)\n" if DEBUG;
ffed8b01 568
f1879fdc 569 unless ( $self->_engine->storage->is_writable ) {
a86430bd 570 $self->_throw_error( 'Cannot write to a readonly filehandle' );
571 }
572
5c0756fc 573 $self->lock_exclusive;
d0b74c17 574
2120a181 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 ...
f9a320bb 578 if ( $self->_type eq TYPE_HASH ) {
579 my $key = $self->first_key;
580 while ( $key ) {
83c43bb5 581 # Retrieve the key before deleting because we depend on next_key
f9a320bb 582 my $next_key = $self->next_key( $key );
2120a181 583 $self->_engine->delete_key( $self, $key, $key );
f9a320bb 584 $key = $next_key;
585 }
586 }
587 else {
588 my $size = $self->FETCHSIZE;
c3aafc14 589 for my $key ( 0 .. $size - 1 ) {
2120a181 590 $self->_engine->delete_key( $self, $key, $key );
f9a320bb 591 }
592 $self->STORESIZE( 0 );
593 }
d0b74c17 594
5c0756fc 595 $self->unlock;
d0b74c17 596
597 return 1;
ffed8b01 598}
599
ffed8b01 600# Public method aliases
d426259c 601sub put { (shift)->STORE( @_ ) }
602sub get { (shift)->FETCH( @_ ) }
603sub store { (shift)->STORE( @_ ) }
604sub fetch { (shift)->FETCH( @_ ) }
baa27ab6 605sub delete { (shift)->DELETE( @_ ) }
606sub exists { (shift)->EXISTS( @_ ) }
d426259c 607sub clear { (shift)->CLEAR( @_ ) }
ffed8b01 608
888453b9 609sub _dump_file {shift->_get_self->_engine->_dump_file;}
610
ffed8b01 6111;
ffed8b01 612__END__