summaryrefslogtreecommitdiff
path: root/examples/cxx/BulkExample.cpp
blob: 0cd79f645968d9eec45a001e8409e680c54f24b8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
/*-
 * See the file LICENSE for redistribution information.
 *
 * Copyright (c) 2012, 2015 Oracle and/or its affiliates.  All rights reserved.
 *
 * $Id$
 */
#include <errno.h>
#include <iostream>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <time.h>

#include <db_cxx.h>

#define	DATABASE	"excxx_bulk.db"                   /* Database name */
#define	DATALEN		20                           /* The length of data */
#define	NS_PER_MS	1000000            /* Nanoseconds in a millisecond */
#define	NS_PER_US	1000               /* Nanoseconds in a microsecond */
#define	STRLEN		DATALEN - sizeof(int)      /* The length of string */
#define	UPDATES_PER_BULK_PUT	100

#ifdef _WIN32
#include <sys/timeb.h>
extern "C" {
	int getopt(int, char * const *, const char *);
	char *optarg;
}
/* Implement a basic high res timer with a POSIX interface for Windows. */
struct timeval {
	time_t tv_sec;
	long tv_usec;
};
int gettimeofday(struct timeval *tv, struct timezone *tz)
{
	struct _timeb now;
	_ftime(&now);
	tv->tv_sec = now.time;
	tv->tv_usec = now.millitm * NS_PER_US;
	return (0);
}
#define CLEANUP_CMD "rmdir EXCXX_BULK /q/s"
#else
#include <sys/time.h>
#include <unistd.h>
#define CLEANUP_CMD "rm -rf EXCXX_BULK"
#endif

int	compare_int(Db *, const Dbt *, const Dbt *, size_t *);
int	get_first_str(Db *, const Dbt *, const Dbt *, Dbt *);
int	get_string(const char *, char *, int);
static void	usage();

const char	*progname = "BulkExample";
const char	tstring[STRLEN] = "0123456789abcde";

struct data {
	int	id;
	char	str[STRLEN];
};

using std::cin;
using std::cout;
using std::cerr;
using std::endl;

class BulkExample
{
public:
	BulkExample();
	~BulkExample();
	void bulkDelete(
	    int num, int dups, int *countp, int *iterp, int verbose);
	void bulkRead(int num, int dups, int iter, int *countp, int verbose);
	void bulkSecondaryDelete(
	    int num, int pair, int *countp, int *iterp, int verbose);
	void bulkUpdate(
	    int num, int dups, int *countp, int *iterp, int verbose);
	void initDb(int, int, int);
	void initDbenv(const char *, u_int);
	void run(int, char *[]);
	void throwException(DbEnv *, DbTxn *, int, const char *);
private:
	DbEnv *dbenv;
	Db *dbp, *sdbp;
	struct data *data_val;
	void *dbuf, *kbuf;
	u_int32_t dlen, klen;
};

void BulkExample::throwException(
    DbEnv *dbenvp, DbTxn *txn, int ret, const char *msg)
{
	if (txn != NULL) {
		(void)txn->abort();
		txn = NULL;
	}
	if (dbenvp != NULL && msg != NULL)
		dbenvp->err(ret, msg);
	throw DbException(ret);
}

void BulkExample::run(int argc, char *argv[])
{
	struct timeval start_time, end_time;
	double secs;
	int biter, ch, count, dflag, dups, init, iter, num, pair;
	int rflag, sflag, verbose;
	u_int32_t cachesize, pagesize;

	dflag = dups = init = rflag = sflag = verbose = 0;
	iter = num = 1000000;
	pagesize = 65536;
	cachesize = 1000 * pagesize;

	while ((ch = getopt(argc, argv, "c:Dd:Ii:n:p:RSv")) != EOF)
		switch (ch) {
		case 'c':
			cachesize = (u_int32_t)atoi(optarg);
			break;
		case 'D':
			dflag = 1;
			break;
		case 'd':
			dups = atoi(optarg);
			if (dups < 0)
				usage();
			break;
		case 'I':
			init = 1;
			break;
		case 'i':
			iter = atoi(optarg);
			break;
		case 'n':
			num = atoi(optarg);
			break;
		case 'p':
			pagesize = (u_int32_t)atoi(optarg);
			break;
		case 'R':
			rflag = 1;
			break;
		case 'S':
			sflag = 1;
			break;
		case 'v':
			verbose = 1;
			break;
		case '?':
		default:
			usage();
		}

	/* Remove the previous environment and database(s). */
	if (!rflag) {
		system(CLEANUP_CMD);
		system("mkdir EXCXX_BULK");
	}

	initDbenv("EXCXX_BULK", cachesize);

	if (init)
		return;

	initDb(dups, sflag, pagesize);

	srand((int)time(NULL));
	if (rflag) {
		/* Time the get loop. */
		(void)gettimeofday(&start_time, NULL);
		bulkRead(num, dups, iter, &count, verbose);
		(void)gettimeofday(&end_time, NULL);
		secs =
		    (((double)end_time.tv_sec * 1000000 + 
		    end_time.tv_usec) -
		    ((double)start_time.tv_sec * 1000000 + 
		    start_time.tv_usec)) / 1000000;
		printf("[STAT] Read %d records read using %d batches",
		    count, iter);
		printf(" in %.2f seconds: ", secs);
		printf("%.0f records/second\n", (double)count / secs);
	} else {
		/* Time the fill loop. */
		(void)gettimeofday(&start_time, NULL);
		bulkUpdate(num, dups, &count, &biter, verbose);
		(void)gettimeofday(&end_time, NULL);
		secs = (((double)end_time.tv_sec * 1000000 + 
		    end_time.tv_usec) -
		    ((double)start_time.tv_sec * 1000000 +
		    start_time.tv_usec)) / 1000000;
		printf("[STAT] Insert %d records using %d batches",
		    count, biter);
		printf(" in %.2f seconds: ", secs);
		printf("%.0f records/second\n", (double)count / secs);
		if (dflag) {
			if (sflag) {
				pair = rand() % 2;
				/* Time the delete loop in secondary db */
				(void)gettimeofday(&start_time, NULL);
				bulkSecondaryDelete(num,
				    pair, &count, &iter, verbose);
				(void)gettimeofday(&end_time, NULL);
				secs = (((double)end_time.tv_sec * 1000000 + 
				    end_time.tv_usec) -
				    ((double)start_time.tv_sec * 1000000 + 
				    start_time.tv_usec)) / 1000000;
				printf("[STAT] Delete %d %s using %d batches",
				    count, (pair) ? "records" : "keys", iter);
				printf(" in %.2f seconds: ", secs);
				printf("%.0f records/second\n", 
				    (double)count / secs);
			} else {
				/* Time the delete loop in primary db */
				(void)gettimeofday(&start_time, NULL);
				bulkDelete(num, dups, &count, &iter, verbose);
				(void)gettimeofday(&end_time, NULL);
				secs = (((double)end_time.tv_sec * 1000000 + 
				    end_time.tv_usec) -
				    ((double)start_time.tv_sec * 1000000 + 
				    start_time.tv_usec)) / 1000000;
				printf(
"[STAT] Delete %d records using %d batches",
				    count, iter);
				printf(" in %.2f seconds: ",  secs);
				printf("%.0f records/second\n",  
				    (double)count / secs);
			}
		}
	}
}

/* Bulk delete from a database. */
void BulkExample::bulkDelete(
    int num, int dups, int *countp, int *iterp, int verbose)
{
	Dbt key;
	DbTxn *txnp;
	DbMultipleDataBuilder *ptrd;
	DbMultipleKeyDataBuilder *ptrkd;
	u_int32_t flag;
	int count, i, j, iter, ret;

	txnp = NULL;
	count = flag = iter = ret = 0;
	memset(&key, 0, sizeof(Dbt));

	j = rand() % num;

	/*
	 * The buffer must be at least as large as the page size of the
	 * underlying database and aligned for unsigned integer access.
	 * Its size must be a multiple of 1024 bytes.
	 */
	if (klen != (u_int32_t)UPDATES_PER_BULK_PUT *
	    (sizeof(u_int32_t) + DATALEN) * 1024) {
		klen = (u_int32_t)UPDATES_PER_BULK_PUT *
		    (sizeof(u_int32_t) + DATALEN) * 1024;
		kbuf = realloc(kbuf, klen);
	}
	memset(kbuf, 0, klen);
	key.set_ulen(klen);
	key.set_flags(DB_DBT_USERMEM | DB_DBT_BULK);
	key.set_data(kbuf);
	if (data_val == NULL)
		data_val = (data *)malloc(DATALEN);
	memset(data_val, 0, DATALEN);

	/*
	 * Bulk delete all records of a specific set of keys which includes all
	 * non-negative integers smaller than the random key. The random key is
	 * a random non-negative integer smaller than "num".
	 * If DB_MULTIPLE, construct the key Dbt by the DbMultipleDataBuilder
	 * with the specific set of keys. If DB_MULTIPLE_KEY, construct the key
	 * Dbt by the DbMultipleKeyDataBuilder with all key/data pairs of the
	 * specific set of keys.
	 */
	flag |= (dups) ? DB_MULTIPLE_KEY : DB_MULTIPLE;
	if (dups)
		ptrkd = new DbMultipleKeyDataBuilder(key);
	else
		ptrd = new DbMultipleDataBuilder(key);
	try {
		for (i = 0; i < j; i++) {
			if (i % UPDATES_PER_BULK_PUT == 0) {
				if (txnp != NULL) {
					ret = txnp->commit(0);
					txnp = NULL;
					if (ret != 0)
						throwException(dbenv, NULL,
						    ret, "DB_TXN->commit");
				}
				if ((ret = dbenv->txn_begin(NULL,
				    &txnp, 0)) != 0)
					throwException(dbenv, NULL,
					    ret, "DB_ENV->txn_begin");
			}

			if (dups) {
				data_val->id = 0;
				get_string(tstring, data_val->str, i);
				do {
					if(ptrkd->append(&i,sizeof(i),
					    data_val, DATALEN) == false)
						throwException(dbenv,
						    txnp, EXIT_FAILURE,
"DbMultipleKeyDataBuilder->append");
					count++;
					if (verbose)
						printf(
"Delete key: %d, \tdata: (id %d, str %s)\n",
						    i, data_val->id,
						    data_val->str);
				} while (data_val->id++ < dups);
			} else {
				if(ptrd->append(&i,sizeof(i)) == false)
					throwException(dbenv, txnp, ret,
					    "DbMultipleDataBuilder->append");
				count++;
				if (verbose)
					printf("Delete key: %d\n", i);
			}

			if ((i + 1) % UPDATES_PER_BULK_PUT == 0) {
				if ((ret = dbp->del(txnp, &key, flag)) != 0)
					throwException(dbenv,
					    txnp, ret, "Bulk DB->del");
				iter++;
				if (dups)
					ptrkd = new
					    DbMultipleKeyDataBuilder(key);
				else
					ptrd = new DbMultipleDataBuilder(key);
			}
		}
		if ((j % UPDATES_PER_BULK_PUT) != 0) {
			if ((ret = dbp->del(txnp, &key, flag)) != 0)
				throwException(dbenv,
				    txnp, ret, "Bulk DB->del");
			iter++;
		}

		ret = txnp->commit(0);
		txnp = NULL;
		if (ret != 0)
			throwException(dbenv, NULL, ret, "DB_TXN->commit");

		*countp = count;
		*iterp = iter;
	} catch (DbException &dbe) {
		cerr << "bulkDelete " << dbe.what() << endl;
		if (txnp != NULL)
			(void)txnp->abort();
		throw dbe;
	}
}

/* Bulk delete from a secondary db. */
void BulkExample::bulkSecondaryDelete(
    int num, int pair, int *countp, int *iterp, int verbose)
{
	Dbt key;
	DbTxn *txnp;
	DbMultipleDataBuilder *ptrd;
	DbMultipleKeyDataBuilder *ptrkd;
	u_int32_t flag;
	int count, i, iter, j, k, rc, ret;
	char ch;

	memset(&key, 0, sizeof(Dbt));
	txnp = NULL;
	count = flag = iter = ret = 0;
	rc = rand() % (STRLEN - 1);

	/*
	 * The buffer must be at least as large as the page size of the
	 * underlying database and aligned for unsigned integer access.
	 * Its size must be a multiple of 1024 bytes.
	 */
	if (klen != (u_int32_t)UPDATES_PER_BULK_PUT *
	    (sizeof(u_int32_t) + DATALEN) * 1024) {
		klen = (u_int32_t)UPDATES_PER_BULK_PUT *
		    (sizeof(u_int32_t) + DATALEN) * 1024;
		kbuf = realloc(kbuf, klen);
	}
	memset(kbuf, 0, klen);
	key.set_ulen(klen);
	key.set_flags(DB_DBT_USERMEM | DB_DBT_BULK);
	key.set_data(kbuf);

	/*
	 * Bulk delete all records of a specific set of keys which includes all
	 * characters before the random key in the tstring. The random key is
	 * one of the characters in the tstring.
	 * If DB_MULTIPLE, construct the key Dbt by the DbMultipleDataBuilder
	 * with the specific set of keys. If DB_MULTIPLE_KEY, construct the key
	 * Dbt by the DbMultipleKeyDataBuilder with all key/data pairs of the
	 * specific set of keys.
	 */
	flag |= (pair) ? DB_MULTIPLE_KEY : DB_MULTIPLE;
	if (pair)
		ptrkd = new DbMultipleKeyDataBuilder(key);
	else
		ptrd = new DbMultipleDataBuilder(key);
	try {
		for (i = 0; i <= rc; i++) {
			if (i % UPDATES_PER_BULK_PUT == 0) {
				if (txnp != NULL) {
					ret = txnp->commit(0);
					txnp = NULL;
					if (ret != 0)
						throwException(dbenv, NULL,
						    ret, "DB_TXN->commit");
				}
				if ((ret = dbenv->txn_begin(NULL,
				    &txnp, 0)) != 0)
					throwException(dbenv,
					    NULL, ret, "DB_ENV->txn_begin");
			}

			ch = tstring[i];
			if (!pair) {
				if (ptrd->append(&ch, sizeof(ch)) == false)
					throwException(dbenv,
					    txnp, EXIT_FAILURE,
					    "DbMultipleDataBuilder->append");
				count++;
				if (verbose)
					printf("Delete key: %c\n", ch);
			} else {
				j = 0;
				do {
					k = j * (STRLEN - 1) + i;
					if (ptrkd->append(&ch, sizeof(ch),
					    &k, sizeof(k)) == false)
						throwException(dbenv,
						    txnp, EXIT_FAILURE,
"DbMultipleKeyDataBuilder->append");
					count++;
					if (verbose)
						printf(
"Delete secondary key: %c, \tdata: %d\n", 
						    ch, k);
				} while (++j < (int)(num / (STRLEN - 1)));
			}

			if ((i + 1) % UPDATES_PER_BULK_PUT == 0) {
				if ((ret = sdbp->del(txnp, &key, flag)) != 0)
					throwException(dbenv,
					    txnp, ret, "Bulk DB->del");
				iter++;
				if (pair)
					ptrkd = new
					    DbMultipleKeyDataBuilder(key);
				else
					ptrd = new DbMultipleDataBuilder(key);
			}
		}
		if ((rc % UPDATES_PER_BULK_PUT) != 0) {
			if ((ret = sdbp->del(txnp, &key, flag)) != 0)
				throwException(dbenv,
				    txnp, ret, "Bulk DB->del");
			iter++;
		}

		ret = txnp->commit(0);
		txnp = NULL;
		if (ret != 0)
			throwException(dbenv, NULL, ret, "DB_TXN->commit");

		*countp = count;
		*iterp = iter;
	} catch (DbException &dbe) {
		cerr << "bulkSecondaryDelete " << dbe.what() << endl;
		if (txnp != NULL)
			(void)txnp->abort();
		throw dbe;
	}
}

/* Bulk fill a database. */
void BulkExample::bulkUpdate(
    int num, int dups, int *countp, int *iterp, int verbose)
{
	Dbt key, data;
	u_int32_t flag;
	DbTxn *txnp;
	int count, i, iter, ret;
	DbMultipleDataBuilder *ptrd, *ptrk;
	DbMultipleKeyDataBuilder *ptrkd;

	txnp = NULL;
	count = flag = iter = ret = 0;
	ptrk = ptrd = NULL;
	if (data_val == NULL)
		data_val = (struct data *)malloc(DATALEN);
	memset(data_val, 0, DATALEN);
	memset(&key, 0, sizeof(Dbt));
	memset(&data, 0, sizeof(Dbt));

	/* 
	 * The buffer must be at least as large as the page size of
	 * the underlying database and aligned for unsigned integer
	 * access. Its size must be a multiple of 1024 bytes.
	 */
	if (klen != (u_int32_t) UPDATES_PER_BULK_PUT *
	    (sizeof(u_int32_t) + DATALEN) * 1024) {
		klen = (u_int32_t) UPDATES_PER_BULK_PUT *
		    (sizeof(u_int32_t) + DATALEN) * 1024;
		kbuf = realloc(kbuf, klen);
	}
	memset(kbuf, 0, klen);
	key.set_ulen(klen);
	key.set_flags(DB_DBT_USERMEM | DB_DBT_BULK);
	key.set_data(kbuf);

	if (dlen != (u_int32_t) UPDATES_PER_BULK_PUT *
	    (sizeof(u_int32_t) + DATALEN) * 1024) {
		dlen = (u_int32_t) UPDATES_PER_BULK_PUT *
		    (sizeof(u_int32_t) + DATALEN) * 1024;
		dbuf = realloc(dbuf, dlen);
	}
	memset(dbuf, 0, dlen);
	data.set_ulen(dlen);
	data.set_flags(DB_DBT_USERMEM | DB_DBT_BULK);
	data.set_data(dbuf);

	/*
	 * Bulk insert with either DB_MULTIPLE in two buffers or
	 * DB_MULTIPLE_KEY in a single buffer. With DB_MULTIPLE, all keys are
	 * constructed in the key Dbt, and all data is constructed in the data
	 * Dbt. With DB_MULTIPLE_KEY, all key/data pairs are constructed in the
	 * key Dbt. We use DB_MULTIPLE mode when there are duplicate records.
	 */
	flag |= (dups) ? DB_MULTIPLE : DB_MULTIPLE_KEY;
	if (dups) {
		ptrk = new DbMultipleDataBuilder(key);
		ptrd = new DbMultipleDataBuilder(data);
	} else
		ptrkd = new DbMultipleKeyDataBuilder(key);

	try {
		for (i = 0; i < num; i++) {
			if (i % UPDATES_PER_BULK_PUT == 0) {
				if (txnp != NULL) {
					ret = txnp->commit(0);
					txnp = NULL;
					if (ret != 0)
						throwException(dbenv, NULL,
						    ret, "DB_TXN->commit");
				}
				if ((ret = dbenv->txn_begin(NULL,
				    &txnp, 0)) != 0)
					throwException(dbenv,
					    NULL, ret, "DB_ENV->txn_begin");
			}
			data_val->id = 0;
			get_string(tstring, data_val->str, i);
			do {
				if (dups) {
					if (ptrk->append(&i,
					    sizeof(i)) == false)
						throwException(dbenv,
						    txnp, EXIT_FAILURE,
"DbMultipleDataBuilder->append");
					if (ptrd->append(data_val,
					    DATALEN) == false)
						throwException(dbenv,
						    txnp, EXIT_FAILURE,
"DbMultipleDataBuilder->append");
				} else {
					if (ptrkd->append(&i, sizeof(i),
					    data_val, DATALEN) == false)
						throwException(dbenv,
						    txnp, EXIT_FAILURE,
"DbMultipleKeyDataBuilder->append");
				}
				if (verbose)
					printf(
"Insert key: %d, \t data: (id %d, str %s)\n",
					    i, data_val->id, data_val->str);
				count++;
			} while (data_val->id++ < dups);
			if ((i + 1) % UPDATES_PER_BULK_PUT == 0) {
				if ((ret = dbp->put(txnp,
					    &key, &data, flag)) != 0)
					throwException(dbenv,
					    txnp, ret, "Bulk DB->put");
				iter++;
				if (dups) {
					ptrk = new DbMultipleDataBuilder(key);
					ptrd = new DbMultipleDataBuilder(data);
				} else
					ptrkd = new
					    DbMultipleKeyDataBuilder(key);
			}
		} 
		if ((num % UPDATES_PER_BULK_PUT) != 0) {
			if ((ret = dbp->put(txnp, &key, &data, flag)) != 0)
				throwException(dbenv,
				    txnp, ret, "Bulk DB->put");
			iter++;
		}

		ret = txnp->commit(0);
		txnp = NULL;
		if (ret != 0)
			throwException(dbenv, NULL, ret, "DB_TXN->commit");

		*countp = count;
		*iterp = iter;
	} catch (DbException &dbe) {
		cerr << "bulkUpdate " << dbe.what() << endl;
		if (txnp != NULL)
			(void)txnp->abort();
		throw dbe;
	}
}

/* Loop get batches of records. */
void BulkExample::bulkRead(
    int num, int dups, int iter, int *countp, int verbose)
{
	Dbc *dbcp;
	Dbt data, dp, key, kp;
	DbTxn *txnp;
	DbMultipleDataIterator *ptrd;
	DbMultipleKeyDataIterator *ptrkd;
	u_int32_t flags;
	int count, i, j, ret;

	count = klen = ret = 0;
	dbcp = NULL;
	txnp = NULL;

	/* Initialize key Dbt and data Dbt, malloc bulk buffer. */
	memset(&key, 0, sizeof(key));
	memset(&data, 0, sizeof(data));
	key.set_size(sizeof(j));
	if (dlen != DATALEN * 16 * 1024) {
		dlen = DATALEN * 16 * 1024;
		dbuf = realloc(dbuf, dlen);
	}
	memset(dbuf, 0, dlen);
	data.set_flags(DB_DBT_USERMEM);
	data.set_data(dbuf);
	data.set_ulen(dlen);
	data.set_size(dlen);

	flags = DB_SET;
	flags |= (dups) ? DB_MULTIPLE: DB_MULTIPLE_KEY;
	try {
		for (i = 0; i < iter; i++) {
			if ((ret =
			    dbenv->txn_begin(NULL, &txnp, 0)) != 0)
				throwException(dbenv, NULL,
				    ret, "DB_ENV->txn_begin");
			if ((ret = dbp->cursor(txnp, &dbcp, 0)) != 0)
				throwException(dbenv, txnp,
				    ret, "DB->cursor");

			/*
			 * Bulk retrieve by a random key which is a random
			 * non-negative integer smaller than "num".
			 * If there are duplicates in the database, retrieve
			 * with DB_MULTIPLE and use the DbMultipleDataIterator
			 * to iterate the data of the random key in the data
			 * Dbt. Otherwise retrieve with DB_MULTIPLE_KEY and use
			 * the DbMultipleKeyDataIterator to iterate the
			 * key/data pairs of the specific set of keys which
			 * includes all integers >= the random key and < "num".
			 */
			j = rand() % num;
			key.set_data(&j);
			if ((ret = dbcp->get(&key, &data, flags)) != 0) 
				throwException(dbenv, NULL, ret, "DBC->get");

			if (dups) {
				ptrd = new DbMultipleDataIterator(data);
				while (ptrd->next(dp) == true) {
					count++;
					if (verbose)
						printf(
"Retrieve key: %d, \tdata: (id %d, str %s)\n", j, ((struct data *)(
						   dp.get_data()))->id,
						   (char *)((struct data *)(
						   dp.get_data()))->str);
				}
			} else {
				ptrkd = new DbMultipleKeyDataIterator(data);
				while (ptrkd->next(kp, dp) == true) {
					count++;
					if (verbose)
						printf(
"Retrieve key: %d, \tdata: (id %d, str %s)\n", *((int *)kp.get_data()),
						    ((struct data *)(
						    dp.get_data()))->id,
						    (char *)((struct data *)(
						    dp.get_data()))->str);
				}
			}

			ret = dbcp->close();
			dbcp = NULL;
			if (ret != 0)
				throwException(dbenv, txnp, ret, "DBC->close");

			ret = txnp->commit(0);
			txnp = NULL;
			if (ret != 0)
				throwException(dbenv, NULL,
				    ret, "DB_TXN->commit");
		} 

		*countp = count;
	} catch (DbException &dbe) {
		cerr << "bulkRead " << dbe.what() << endl;
		if (dbcp != NULL)
			(void)dbcp->close();
		if (txnp != NULL)
			(void)txnp->abort();
		throw dbe;
	}
}

/* Initialize the database. */
void BulkExample::initDb(int dups, int sflag, int pagesize) {

	DbTxn *txnp;
	int ret;

	txnp = NULL;
	ret = 0;

	dbp = new Db(dbenv, 0);

	dbp->set_error_stream(&cerr);
	dbp->set_errpfx(progname);

	try{
		if ((ret = dbp->set_bt_compare(compare_int)) != 0)
			throwException(dbenv, NULL, ret, "DB->set_bt_compare");

		if ((ret = dbp->set_pagesize(pagesize)) != 0)
			throwException(dbenv, NULL, ret, "DB->set_pagesize");

		if (dups && (ret = dbp->set_flags(DB_DUP)) != 0)
			throwException(dbenv, NULL, ret, "DB->set_flags");

		if ((ret = dbenv->txn_begin(NULL, &txnp, 0)) != 0)
			throwException(dbenv, NULL, ret, "DB_ENV->txn_begin");

		if ((ret = dbp->open(txnp, DATABASE, "primary", DB_BTREE,
		    DB_CREATE, 0664)) != 0)
			throwException(dbenv, txnp, ret, "DB->open");

		if (sflag) {
			sdbp = new Db(dbenv, 0);

			if ((ret = sdbp->set_flags(DB_DUPSORT)) != 0)
				throwException(dbenv, txnp,
				    ret, "DB->set_flags");

			if ((ret = sdbp->open(txnp, DATABASE, "secondary",
			    DB_BTREE, DB_CREATE, 0664)) != 0)
				throwException(dbenv, txnp, ret, "DB->open");

			if ((ret =  dbp->associate(
			    txnp, sdbp, get_first_str, 0)) != 0)
				throwException(dbenv, txnp,
				    ret, "DB->associate");
		}

		ret = txnp->commit(0);
		txnp = NULL;
		if (ret != 0)
			throwException(dbenv, NULL, ret, "DB_TXN->commit");
	} catch(DbException &dbe) {
		cerr << "initDb " << dbe.what() << endl;
		if (txnp != NULL)
			(void)txnp->abort();
		throw dbe;
	}
}

/* Initialize the environment. */
void BulkExample::initDbenv(const char *home, u_int32_t cachesize)
{
	int ret;

	ret = 0;

	dbenv = new DbEnv(0);

	dbenv->set_error_stream(&cerr);
	dbenv->set_errpfx(progname);

	try {
		if ((ret = dbenv->set_cachesize(0, cachesize, 0)) != 0)
			throwException(dbenv,
			    NULL, ret, "DB_ENV->set_cachesize");

		/* Open the environment with full transactional support. */
		if ((ret = dbenv->open(home, DB_CREATE | DB_INIT_LOCK |
		    DB_INIT_LOG | DB_INIT_MPOOL | DB_INIT_TXN, 0)) != 0)
			throwException(dbenv, NULL, ret, "DB_ENV->open");
	} catch (DbException &dbe) {
		cerr << "initDbenv " << dbe.what() << endl;
		throw dbe;
	}
}

BulkExample::BulkExample() : dbenv(NULL), dbp(NULL), sdbp(NULL),
     data_val(NULL), dbuf(NULL), kbuf(NULL), dlen(0), klen(0) {}

BulkExample::~BulkExample()
{
	if (sdbp != NULL) {
		sdbp->close(0);
		delete sdbp;
	}
	if (dbp != NULL) {
		dbp->close(0);
		delete dbp;
	}
	if (dbenv != NULL) {
		dbenv->close(0);
		delete dbenv;
	}
	if (dbuf != NULL)
		free(dbuf);
	if (kbuf != NULL)
		free(kbuf);
	if (data_val != NULL)
		free(data_val);
}

int
compare_int(Db *dbp, const Dbt *a, const Dbt *b, size_t *locp)
{
	int ai, bi;

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

int
get_first_str(Db *sdbp, const Dbt *key, const Dbt *data, Dbt *skey)
{
	memset(skey, 0, sizeof(Dbt));
	skey->set_data(((struct data *)(data->get_data()))->str);
	skey->set_size(sizeof(char));
	return (0);
}

int
get_string(const char *src, char *des, int off)
{
	int i;

	for (i = 0; i < (int)(STRLEN - 1); i++) 
		des[i] = src[(off + i) % (STRLEN - 1)];
	des[STRLEN - 1] = '\0';
	return (0);
}

static void
usage()
{
	cerr << "Usage: BulkExample \n"
	     << "-c	cachesize [1000 * pagesize] \n"
	     << "-D	perform bulk delete \n"
	     << "-d	number of duplicates [none] \n"
	     << "-I	just initialize the environment \n"
	     << "-i	number of read iterations [1000000] \n"
	     << "-n	number of keys [1000000] \n"
	     << "-p	pagesize [65536] \n"
	     << "-R	perform bulk read \n"
	     << "-S	perform bulk operation in secondary database \n"
	     << "-v	verbose output \n";
	exit(EXIT_FAILURE);
}

int
main(int argc, char *argv[])
{
	/*
	 * Use a try block just to report any errors.
	 * An alternate approach to using exceptions is to
	 * use error models (see DbEnv::set_error_model()) so
	 * that error codes are returned for all Berkeley DB methods.
	 */
	try {
		BulkExample app;
		app.run(argc, argv);
		return (EXIT_SUCCESS);
	} catch (DbException &dbe) {
		cerr << "BulkExample: " << dbe.what() << endl;
		return (EXIT_FAILURE);
	}
}