in reply to Re: Associated BerkeleyDB table uses wrong compare?
in thread Associated BerkeleyDB table uses wrong compare?

I see that my code example was not sufficiently complete. Here is a full, runnable case:
use strict; use warnings; use BerkeleyDB; my $home = "."; my $tableName = "testDB"; my $dbName = "testDex"; my $table = BerkeleyDB::Btree->new( -Filename => "$home/$tableName/$tableName", -Compare => sub { my($a, $b) = @_; return $a <=> $b; }, # numeric -Flags => DB_CREATE, ) or die "Could not open \'$home/$tableName/$tableName\' ... "; my $db = BerkeleyDB::Btree->new( -Property => DB_DUP, -Flags => DB_CREATE, -Filename => "$home/$tableName/$dbName", -Compare => sub { my($a, $b) = @_; return $a cmp $b; }, # ascii ) or die "Could not open \'$home/$tableName/$dbName\' ... "; sub key_sub { my $pkey = shift; my $pdata = shift; $_[0] = (split /\|/,$pdata)[1]; return 0; } $table->associate($db, \&key_sub); $table->db_put(1,"x|w60"); $table->db_put(2,"y|w61");
The error messages in this case are:
Argument "w60" isn't numeric in numeric comparison (<=>) at hhh.pl lin +e 11. Argument "w61" isn't numeric in numeric comparison (<=>) at hhh.pl lin +e 11. Argument "w60" isn't numeric in numeric comparison (<=>) at hhh.pl lin +e 11. Argument "w61" isn't numeric in numeric comparison (<=>) at hhh.pl lin +e 11.
What I expect to happen is that whenever I do a "db_put" to the primary table, the key_sub will be called to extract a key (e.g. "w60") and that a secondary index will be made using that key.

I expect to be able to specify a "-Compare" function for that secondary table that is appropriate for the ascii keys I am using. But for some reason the "-Compare" function of the first table is being used for the keys of the second table.

I have a work-around for it for now, but I'd still like to find out where the problem is so that it can be fixed in the module. Here's my work-around:

my $digits = qr/^\d+$/; sub eitherComp { my($a, $b) = @_; return $a <=> $b if ($a =~ $digits and $b =~ $digits); return $a cmp $b; }
If I make the "-Compare" function for the first table a reference to eitherComp, the problem goes away.

Update: I think I'm on the track of the bug. In the XS wrapper code for BerkeleyDB, I find the function btree_compare, which uses a global variable called CurrentDB. The comparison function is called as follows:

count = perl_call_sv(CurrentDB->compare, G_SCALAR);
Suppose that CurrentDB was set to the first table, and that it isn't changed when the associated tables are being updated. That would explain the bug I am seeing. I will email Paul Marquess about this.