1/*	$NetBSD: nextid.c,v 1.1.1.3 2010/12/12 15:22:58 adam Exp $	*/
2
3/* init.c - initialize bdb backend */
4/* OpenLDAP: pkg/ldap/servers/slapd/back-bdb/nextid.c,v 1.26.2.6 2010/04/13 20:23:25 kurt Exp */
5/* This work is part of OpenLDAP Software <http://www.openldap.org/>.
6 *
7 * Copyright 2000-2010 The OpenLDAP Foundation.
8 * All rights reserved.
9 *
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted only as authorized by the OpenLDAP
12 * Public License.
13 *
14 * A copy of this license is available in the file LICENSE in the
15 * top-level directory of the distribution or, alternatively, at
16 * <http://www.OpenLDAP.org/license.html>.
17 */
18
19#include "portable.h"
20
21#include <stdio.h>
22#include <ac/string.h>
23
24#include "back-bdb.h"
25
26int bdb_next_id( BackendDB *be, ID *out )
27{
28	struct bdb_info *bdb = (struct bdb_info *) be->be_private;
29
30	ldap_pvt_thread_mutex_lock( &bdb->bi_lastid_mutex );
31	*out = ++bdb->bi_lastid;
32	ldap_pvt_thread_mutex_unlock( &bdb->bi_lastid_mutex );
33
34	return 0;
35}
36
37int bdb_last_id( BackendDB *be, DB_TXN *tid )
38{
39	struct bdb_info *bdb = (struct bdb_info *) be->be_private;
40	int rc;
41	ID id = 0;
42	unsigned char idbuf[sizeof(ID)];
43	DBT key, data;
44	DBC *cursor;
45
46	DBTzero( &key );
47	key.flags = DB_DBT_USERMEM;
48	key.data = (char *) idbuf;
49	key.ulen = sizeof( idbuf );
50
51	DBTzero( &data );
52	data.flags = DB_DBT_USERMEM | DB_DBT_PARTIAL;
53
54	/* Get a read cursor */
55	rc = bdb->bi_id2entry->bdi_db->cursor( bdb->bi_id2entry->bdi_db,
56		tid, &cursor, 0 );
57
58	if (rc == 0) {
59		rc = cursor->c_get(cursor, &key, &data, DB_LAST);
60		cursor->c_close(cursor);
61	}
62
63	switch(rc) {
64	case DB_NOTFOUND:
65		rc = 0;
66		break;
67	case 0:
68		BDB_DISK2ID( idbuf, &id );
69		break;
70
71	default:
72		Debug( LDAP_DEBUG_ANY,
73			"=> bdb_last_id: get failed: %s (%d)\n",
74			db_strerror(rc), rc, 0 );
75		goto done;
76	}
77
78	bdb->bi_lastid = id;
79
80done:
81	return rc;
82}
83