sq3: show SQLite error messages on stderr by default
[iv.d.git] / lmdb_sample / sample.d
blobbfaff39daf0ce02602cb2b491b01b1e05c825667
1 /* Invisible Vector Library
2 * coded by Ketmar // Invisible Vector <ketmar@ketmar.no-ip.org>
3 * Understanding is not required. Only obedience.
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation, version 3 of the License ONLY.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <http://www.gnu.org/licenses/>.
17 pragma(lib, "lmdb");
18 import iv.lmdb;
21 private void lmdbDo (int rc, string msg) {
22 if (rc) {
23 import core.exception : ExitException;
24 import std.stdio : stderr;
25 import std.string : fromStringz;
26 stderr.writeln("FATAL(", rc, "): ", msg, "() failed: ", mdb_strerror(rc).fromStringz);
27 throw new ExitException();
32 void main () {
33 import std.exception : collectException;
34 import std.file : mkdir;
36 int rc;
37 MDB_envp env;
38 MDB_dbi dbi;
39 MDB_val key, data;
40 MDB_txnp txn;
41 MDB_cursorp cursor;
42 char[32] sval;
45 import std.stdio : writeln;
46 import std.string : fromStringz;
47 int major, minor, patch;
48 auto ver = mdb_version(&major, &minor, &patch);
49 writeln("ver=", ver.fromStringz, "; major=", major, "; minor=", minor, "; patch=", patch);
52 lmdbDo(mdb_env_create(&env), "mdb_env_create");
54 collectException(mkdir("testdb"));
55 lmdbDo(env.mdb_env_open("./testdb", 0, 0o664), "mdb_env_open");
56 scope(exit) env.mdb_env_close();
58 lmdbDo(env.mdb_txn_begin(null, 0, &txn), "mdb_txn_begin");
59 scope(exit) txn.mdb_txn_abort();
61 lmdbDo(txn.mdb_dbi_open(null, 0, &dbi), "mdb_dbi_open");
62 scope(exit) env.mdb_dbi_close(dbi);
64 key.mv_size = int.sizeof;
65 key.mv_data = cast(void *)sval;
66 data.mv_size = sval.sizeof;
67 data.mv_data = cast(void *)sval;
70 import core.stdc.stdio : sprintf;
71 sprintf(cast(char *)sval, "%03x %d foo bar", 32, 3141592);
74 lmdbDo(txn.mdb_put(dbi, &key, &data, 0), "mdb_put");
75 lmdbDo(txn.mdb_txn_commit(), "mdb_txn_commit");
77 lmdbDo(env.mdb_txn_begin(null, MDB_RDONLY, &txn), "mdb_txn_begin");
79 lmdbDo(txn.mdb_cursor_open(dbi, &cursor), "mdb_cursor_open");
80 scope(exit) cursor.mdb_cursor_close();
82 while ((rc = cursor.mdb_cursor_get(&key, &data, MDB_NEXT)) == 0) {
83 import core.stdc.stdio : printf;
84 printf("key: %p %.*s, data: %p %.*s\n",
85 key.mv_data, cast(int) key.mv_size, cast(char *) key.mv_data,
86 data.mv_data, cast(int) data.mv_size, cast(char *) data.mv_data);