summaryrefslogtreecommitdiffstats
path: root/crawl-ref/source/sqldbm.h
blob: 15123b4945a9ef58f82de3932810989d903501ef (plain) (blame)
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
/*
 *  File:       sqldbm.cc
 *  Summary:    dbm wrapper for SQLite
 *  Written by: Darshan Shaligram
 */

#ifndef SQLDBM_H
#define SQLDBM_H

#ifdef USE_SQLITE_DBM

#include <sys/types.h>
#include <memory>

#define SQLITE_INT64_TYPE int
#define SQLITE_UINT64_TYPE unsigned int

#include <sqlite3.h>
#include <string>

// A string dbm interface for SQLite. Makes no attempt to store arbitrary
// data, only valid C strings.

class sql_datum
{
public:
    sql_datum();
    sql_datum(const std::string &s);
    sql_datum(const sql_datum &other);
    virtual ~sql_datum();

    sql_datum &operator = (const sql_datum &other);

    std::string to_str() const;

public:
    char   *dptr;    // Canonically void*, but we're not a real Berkeley DB.
    size_t dsize;

private:
    bool   need_free;

    void reset();
    void init_from(const sql_datum &other);
};

#define DBM_REPLACE 1

class SQL_DBM
{
public:
    SQL_DBM(const std::string &db = "", bool open = false);
    ~SQL_DBM();

    bool is_open() const;

    int open(const std::string &db = "");
    void close();

    std::auto_ptr<std::string> firstkey();
    std::auto_ptr<std::string> nextkey();

    std::string query(const std::string &key);
    int insert(const std::string &key, const std::string &value);

public:
    std::string error;
    int errc;

private:
    int finalise_query(sqlite3_stmt **query);
    int prepare_query(sqlite3_stmt **query, const char *sql);
    int init_query();
    int init_iterator();
    int init_insert();
    int init_schema();
    int ec(int err);

private:
    sqlite3      *db;
    sqlite3_stmt *s_insert;
    sqlite3_stmt *s_query;
    sqlite3_stmt *s_iterator;
    std::string  dbfile;
};

SQL_DBM  *dbm_open(const char *filename, int open_mode, int permissions);
int   dbm_close(SQL_DBM *db);

sql_datum dbm_fetch(SQL_DBM *db, const sql_datum &key);
sql_datum dbm_firstkey(SQL_DBM *db);
sql_datum dbm_nextkey(SQL_DBM *db);
int dbm_store(SQL_DBM *db, const sql_datum &key,
              const sql_datum &value, int overwrite);

typedef sql_datum datum;
typedef SQL_DBM DBM;

#endif

#endif