d4e499d7e313e7bb3a98891624087420f2c01d9e
[ccan] / ccan / tdb / test / run-nested-traverse.c
1 #define _XOPEN_SOURCE 500
2 #include "lock-tracking.h"
3 #define fcntl fcntl_with_lockcheck
4 #include <ccan/tdb/tdb.h>
5 #include <ccan/tdb/io.c>
6 #include <ccan/tdb/tdb.c>
7 #include <ccan/tdb/lock.c>
8 #include <ccan/tdb/freelist.c>
9 #include <ccan/tdb/traverse.c>
10 #include <ccan/tdb/transaction.c>
11 #include <ccan/tdb/error.c>
12 #include <ccan/tdb/open.c>
13 #include <ccan/tdb/check.c>
14 #include <ccan/tap/tap.h>
15 #undef fcntl
16 #include <stdlib.h>
17 #include <stdbool.h>
18 #include <err.h>
19 #include "external-agent.h"
20
21 static struct agent *agent;
22
23 static bool correct_key(TDB_DATA key)
24 {
25         return key.dsize == strlen("hi")
26                 && memcmp(key.dptr, "hi", key.dsize) == 0;
27 }
28
29 static bool correct_data(TDB_DATA data)
30 {
31         return data.dsize == strlen("world")
32                 && memcmp(data.dptr, "world", data.dsize) == 0;
33 }
34
35 static int traverse2(struct tdb_context *tdb, TDB_DATA key, TDB_DATA data,
36                      void *p)
37 {
38         ok1(correct_key(key));
39         ok1(correct_data(data));
40         return 0;
41 }
42
43 static int traverse1(struct tdb_context *tdb, TDB_DATA key, TDB_DATA data,
44                      void *p)
45 {
46         ok1(correct_key(key));
47         ok1(correct_data(data));
48         ok1(external_agent_operation(agent, TRANSACTION_START, tdb_name(tdb))
49             == WOULD_HAVE_BLOCKED);
50         tdb_traverse(tdb, traverse2, NULL);
51
52         /* That should *not* release the transaction lock! */
53         ok1(external_agent_operation(agent, TRANSACTION_START, tdb_name(tdb))
54             == WOULD_HAVE_BLOCKED);
55         return 0;
56 }
57
58 int main(int argc, char *argv[])
59 {
60         struct tdb_context *tdb;
61         TDB_DATA key, data;
62
63         plan_tests(17);
64         agent = prepare_external_agent();
65         if (!agent)
66                 err(1, "preparing agent");
67
68         tdb = tdb_open("run-nested-traverse.tdb", 1024, TDB_CLEAR_IF_FIRST,
69                        O_CREAT|O_TRUNC|O_RDWR, 0600);
70         ok1(tdb);
71
72         ok1(external_agent_operation(agent, OPEN, tdb_name(tdb)) == SUCCESS);
73         ok1(external_agent_operation(agent, TRANSACTION_START, tdb_name(tdb))
74             == SUCCESS);
75         ok1(external_agent_operation(agent, TRANSACTION_COMMIT, tdb_name(tdb))
76             == SUCCESS);
77
78         key.dsize = strlen("hi");
79         key.dptr = (void *)"hi";
80         data.dptr = (void *)"world";
81         data.dsize = strlen("world");
82
83         ok1(tdb_store(tdb, key, data, TDB_INSERT) == 0);
84         tdb_traverse(tdb, traverse1, NULL);
85         tdb_traverse_read(tdb, traverse1, NULL);
86         tdb_close(tdb);
87
88         return exit_status();
89 }