ldb: Add MDB support to ldb://
[metze/samba/wip.git] / lib / ldb / ldb_ldb / ldb_ldb.c
1 /*
2  * ldb connection and module initialisation
3  *
4  *  Copyright (C) Andrew Bartlett <abartlet@samba.org> 2018
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 3 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
18  *
19  */
20 #include "ldb_private.h"
21 #include "../ldb_tdb/ldb_tdb.h"
22 #ifdef HAVE_LMDB
23 #include "../ldb_mdb/ldb_mdb.h"
24 #endif /* HAVE_LMDB */
25
26 /*
27   connect to the database
28 */
29 static int lldb_connect(struct ldb_context *ldb,
30                         const char *url,
31                         unsigned int flags,
32                         const char *options[],
33                         struct ldb_module **module)
34 {
35         const char *path;
36         int ret;
37
38         /*
39          * Check and remove the url prefix
40          */
41         if (strchr(url, ':')) {
42                 if (strncmp(url, "ldb://", 6) != 0) {
43                         ldb_debug(ldb, LDB_DEBUG_ERROR,
44                                   "Invalid ldb URL '%s'", url);
45                         return LDB_ERR_OPERATIONS_ERROR;
46                 }
47                 path = url+6;
48         } else {
49                 path = url;
50         }
51
52         /*
53          * Don't create the database if it's not there
54          */
55         flags |= LDB_FLG_DONT_CREATE_DB;
56 #ifdef HAVE_LMDB
57         /*
58          * Try opening the database as an lmdb
59          */
60         ret = lmdb_connect(ldb, path, flags, options, module);
61         if (ret == LDB_SUCCESS) {
62                 return ret;
63         }
64         if (ret != LDB_ERR_UNAVAILABLE) {
65                 return ret;
66         }
67
68         /*
69          * Not mdb so try as tdb
70          */
71 #endif /* HAVE_LMDB */
72         ret = ltdb_connect(ldb, path, flags, options, module);
73         return ret;
74 }
75
76 int ldb_ldb_init(const char *version)
77 {
78         LDB_MODULE_CHECK_VERSION(version);
79         return ldb_register_backend("ldb", lldb_connect, false);
80 }