Description: Berkeley DB: An embedded database programmatic toolkit.
Keywords: embedded,database,programmatic,toolkit,b+tree,btr ee,hash,hashing,transaction,transactions,locking,logging,access method,access me thods,java,C,C++

### Berkeley DB Reference Guide: Access Methods

# Btree comparison function (bt_compare)

The Btree data structure is a sorted, balanced tree structure storing associated key/data pairs.

The sort order for the Btree can be specified as part of the db_open call to open the database, specifically by setting the bt_compare element of the DB_INFO structure. If no comparison routine is specified, the sort order is lexical, with shorter keys collating before longer keys.

Sort routines are passed pointers to keys as arguments. The keys are represented as DBT structures. The routine must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second argument. The only fields that the routines may examine in the DBT structures are data and size fields.

An example routine that might be used to sort integer keys in the database is as follows:

    compare_int(a, b)
    	const DBT *a, *b;
    {
    	int ai, bi;

    	/*
    	 * Returns:
    	 *	< 0 if a < b
    	 *	= 0 if a = b
    	 *	> 0 if a > b
    	 */
    	memcpy(&ai, a->data, sizeof(int));
    	memcpy(&bi, b->data, sizeof(int));
    	return (ai - bi);
    }

Note that the data must first be copied into memory that is appropriately aligned, as Berkeley DB does not guarantee any kind of alignment of the underlying data, including for comparison routines.

When doing integer comparison routines, it is important to remember that databases created on machines of different architectures may have different integer byte orders, for which your code may need to compensate.

An example routine that might be used to sort keys based on the first five bytes of the key (ignoring any subsequent keys) is as follows:

    compare_dbt(a, b)
    	const DBT *a, *b;
    {
    	u_char *p1, *p2;

    	/*
    	 * Returns:
    	 *	< 0 if a < b
    	 *	= 0 if a = b
    	 *	> 0 if a > b
    	 */
    	for (p1 = a->data, p2 = b->data, len = 5; len--; ++p1, ++p2)
    		if (*p1 != *p2)
    			return ((long)*p1 - (long)*p2);
    	return (0);
    }