4 Copyright (C) Derrell Lipman 2005
5 Copyright (C) Simo Sorce 2005-2006
7 ** NOTE! The following LGPL license applies to the ldb
8 ** library. This does NOT imply that all of Samba is released
11 This library is free software; you can redistribute it and/or
12 modify it under the terms of the GNU Lesser General Public
13 License as published by the Free Software Foundation; either
14 version 3 of the License, or (at your option) any later version.
16 This library is distributed in the hope that it will be useful,
17 but WITHOUT ANY WARRANTY; without even the implied warranty of
18 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
19 Lesser General Public License for more details.
21 You should have received a copy of the GNU Lesser General Public
22 License along with this library; if not, see <http://www.gnu.org/licenses/>.
28 * Component: ldb sqlite3 backend
30 * Description: core files for SQLITE3 backend
32 * Author: Derrell Lipman (based on Andrew Tridgell's LDAP backend)
35 #include "ldb_includes.h"
39 struct lsqlite3_private {
46 struct ldb_module *module;
49 long long current_eid;
50 const char * const * attrs;
51 struct ldb_reply *ares;
55 int (*callback)(struct ldb_context *, void *, struct ldb_reply *);
58 static struct ldb_handle *init_handle(struct lsqlite3_private *lsqlite3,
59 struct ldb_module *module,
60 struct ldb_request *req)
62 struct lsql_context *ac;
65 h = talloc_zero(lsqlite3, struct ldb_handle);
67 ldb_set_errstring(module->ldb, "Out of Memory");
73 ac = talloc(h, struct lsql_context);
75 ldb_set_errstring(module->ldb, "Out of Memory");
80 h->private_data = (void *)ac;
82 h->state = LDB_ASYNC_INIT;
83 h->status = LDB_SUCCESS;
86 ac->context = req->context;
87 ac->callback = req->callback;
93 * Macros used throughout
98 # define TRUE (! FALSE)
101 #define RESULT_ATTR_TABLE "temp_result_attrs"
103 //#define TEMPTAB /* for testing, create non-temporary table */
104 #define TEMPTAB "TEMPORARY"
109 sqlite3_stmt * stmtGetEID = NULL;
111 static char *lsqlite3_tprintf(TALLOC_CTX *mem_ctx, const char *fmt, ...)
117 str = sqlite3_vmprintf(fmt, ap);
120 if (str == NULL) return NULL;
122 ret = talloc_strdup(mem_ctx, str);
132 static char base160tab[161] = {
133 48 ,49 ,50 ,51 ,52 ,53 ,54 ,55 ,56 ,57 , /* 0-9 */
134 58 ,59 ,65 ,66 ,67 ,68 ,69 ,70 ,71 ,72 , /* : ; A-H */
135 73 ,74 ,75 ,76 ,77 ,78 ,79 ,80 ,81 ,82 , /* I-R */
136 83 ,84 ,85 ,86 ,87 ,88 ,89 ,90 ,97 ,98 , /* S-Z , a-b */
137 99 ,100,101,102,103,104,105,106,107,108, /* c-l */
138 109,110,111,112,113,114,115,116,117,118, /* m-v */
139 119,120,121,122,160,161,162,163,164,165, /* w-z, latin1 */
140 166,167,168,169,170,171,172,173,174,175, /* latin1 */
141 176,177,178,179,180,181,182,183,184,185, /* latin1 */
142 186,187,188,189,190,191,192,193,194,195, /* latin1 */
143 196,197,198,199,200,201,202,203,204,205, /* latin1 */
144 206,207,208,209,210,211,212,213,214,215, /* latin1 */
145 216,217,218,219,220,221,222,223,224,225, /* latin1 */
146 226,227,228,229,230,231,232,233,234,235, /* latin1 */
147 236,237,238,239,240,241,242,243,244,245, /* latin1 */
148 246,247,248,249,250,251,252,253,254,255, /* latin1 */
156 * Convert an unsigned long integer into a base160 representation of the
161 * value to be converted
164 * character array, 5 bytes long, into which the base160 representation
165 * will be placed. The result will be a four-digit representation of the
166 * number (with leading zeros prepended as necessary), and null
173 base160_sql(sqlite3_context * hContext,
175 sqlite3_value ** argv)
181 val = sqlite3_value_int64(argv[0]);
183 for (i = 3; i >= 0; i--) {
185 result[i] = base160tab[val % 160];
191 sqlite3_result_text(hContext, result, -1, SQLITE_TRANSIENT);
198 * This function enhances sqlite by adding a "base160_next()" function which is
199 * accessible via queries.
201 * Retrieve the next-greater number in the base160 sequence for the terminal
202 * tree node (the last four digits). Only one tree level (four digits) is
206 * A character string: either an empty string (in which case no operation is
207 * performed), or a string of base160 digits with a length of a multiple of
211 * Upon return, the trailing four digits (one tree level) will have been
215 base160next_sql(sqlite3_context * hContext,
217 sqlite3_value ** argv)
222 char * pBase160 = strdup((const char *)sqlite3_value_text(argv[0]));
223 char * pStart = pBase160;
226 * We need a minimum of four digits, and we will always get a multiple
229 if (pBase160 != NULL &&
230 (len = strlen(pBase160)) >= 4 &&
233 if (pBase160 == NULL) {
235 sqlite3_result_null(hContext);
239 pBase160 += strlen(pBase160) - 1;
241 /* We only carry through four digits: one level in the tree */
242 for (i = 0; i < 4; i++) {
244 /* What base160 value does this digit have? */
245 pTab = strchr(base160tab, *pBase160);
247 /* Is there a carry? */
248 if (pTab < base160tab + sizeof(base160tab) - 1) {
251 * Nope. Just increment this value and we're
259 * There's a carry. This value gets
260 * base160tab[0], we decrement the buffer
261 * pointer to get the next higher-order digit,
262 * and continue in the loop.
264 *pBase160-- = base160tab[0];
268 sqlite3_result_text(hContext,
273 sqlite3_result_value(hContext, argv[0]);
274 if (pBase160 != NULL) {
280 static char *parsetree_to_sql(struct ldb_module *module,
282 const struct ldb_parse_tree *t)
284 const struct ldb_schema_attribute *a;
285 struct ldb_val value, subval;
286 char *wild_card_string;
293 switch(t->operation) {
296 tmp = parsetree_to_sql(module, mem_ctx, t->u.list.elements[0]);
297 if (tmp == NULL) return NULL;
299 for (i = 1; i < t->u.list.num_elements; i++) {
301 child = parsetree_to_sql(module, mem_ctx, t->u.list.elements[i]);
302 if (child == NULL) return NULL;
304 tmp = talloc_asprintf_append(tmp, " INTERSECT %s ", child);
305 if (tmp == NULL) return NULL;
308 ret = talloc_asprintf(mem_ctx, "SELECT * FROM ( %s )\n", tmp);
314 tmp = parsetree_to_sql(module, mem_ctx, t->u.list.elements[0]);
315 if (tmp == NULL) return NULL;
317 for (i = 1; i < t->u.list.num_elements; i++) {
319 child = parsetree_to_sql(module, mem_ctx, t->u.list.elements[i]);
320 if (child == NULL) return NULL;
322 tmp = talloc_asprintf_append(tmp, " UNION %s ", child);
323 if (tmp == NULL) return NULL;
326 return talloc_asprintf(mem_ctx, "SELECT * FROM ( %s ) ", tmp);
330 child = parsetree_to_sql(module, mem_ctx, t->u.isnot.child);
331 if (child == NULL) return NULL;
333 return talloc_asprintf(mem_ctx,
334 "SELECT eid FROM ldb_entry "
335 "WHERE eid NOT IN ( %s ) ", child);
337 case LDB_OP_EQUALITY:
339 * For simple searches, we want to retrieve the list of EIDs that
340 * match the criteria.
342 attr = ldb_attr_casefold(mem_ctx, t->u.equality.attr);
343 if (attr == NULL) return NULL;
344 a = ldb_schema_attribute_by_name(module->ldb, attr);
346 /* Get a canonicalised copy of the data */
347 a->syntax->canonicalise_fn(module->ldb, mem_ctx, &(t->u.equality.value), &value);
348 if (value.data == NULL) {
352 if (strcasecmp(t->u.equality.attr, "dn") == 0) {
353 /* DN query is a special ldb case */
354 const char *cdn = ldb_dn_get_casefold(
355 ldb_dn_new(mem_ctx, module->ldb,
356 (const char *)value.data));
358 return lsqlite3_tprintf(mem_ctx,
359 "SELECT eid FROM ldb_entry "
360 "WHERE norm_dn = '%q'", cdn);
363 /* A normal query. */
364 return lsqlite3_tprintf(mem_ctx,
365 "SELECT eid FROM ldb_attribute_values "
366 "WHERE norm_attr_name = '%q' "
367 "AND norm_attr_value = '%q'",
373 case LDB_OP_SUBSTRING:
375 wild_card_string = talloc_strdup(mem_ctx,
376 (t->u.substring.start_with_wildcard)?"*":"");
377 if (wild_card_string == NULL) return NULL;
379 for (i = 0; t->u.substring.chunks[i]; i++) {
380 wild_card_string = talloc_asprintf_append(wild_card_string, "%s*",
381 t->u.substring.chunks[i]->data);
382 if (wild_card_string == NULL) return NULL;
385 if ( ! t->u.substring.end_with_wildcard ) {
386 /* remove last wildcard */
387 wild_card_string[strlen(wild_card_string) - 1] = '\0';
390 attr = ldb_attr_casefold(mem_ctx, t->u.substring.attr);
391 if (attr == NULL) return NULL;
392 a = ldb_schema_attribute_by_name(module->ldb, attr);
394 subval.data = (void *)wild_card_string;
395 subval.length = strlen(wild_card_string) + 1;
397 /* Get a canonicalised copy of the data */
398 a->syntax->canonicalise_fn(module->ldb, mem_ctx, &(subval), &value);
399 if (value.data == NULL) {
403 return lsqlite3_tprintf(mem_ctx,
404 "SELECT eid FROM ldb_attribute_values "
405 "WHERE norm_attr_name = '%q' "
406 "AND norm_attr_value GLOB '%q'",
411 attr = ldb_attr_casefold(mem_ctx, t->u.equality.attr);
412 if (attr == NULL) return NULL;
413 a = ldb_schema_attribute_by_name(module->ldb, attr);
415 /* Get a canonicalised copy of the data */
416 a->syntax->canonicalise_fn(module->ldb, mem_ctx, &(t->u.equality.value), &value);
417 if (value.data == NULL) {
421 return lsqlite3_tprintf(mem_ctx,
422 "SELECT eid FROM ldb_attribute_values "
423 "WHERE norm_attr_name = '%q' "
424 "AND ldap_compare(norm_attr_value, '>=', '%q', '%q') ",
430 attr = ldb_attr_casefold(mem_ctx, t->u.equality.attr);
431 if (attr == NULL) return NULL;
432 a = ldb_schema_attribute_by_name(module->ldb, attr);
434 /* Get a canonicalised copy of the data */
435 a->syntax->canonicalise_fn(module->ldb, mem_ctx, &(t->u.equality.value), &value);
436 if (value.data == NULL) {
440 return lsqlite3_tprintf(mem_ctx,
441 "SELECT eid FROM ldb_attribute_values "
442 "WHERE norm_attr_name = '%q' "
443 "AND ldap_compare(norm_attr_value, '<=', '%q', '%q') ",
449 if (strcasecmp(t->u.present.attr, "dn") == 0) {
450 return talloc_strdup(mem_ctx, "SELECT eid FROM ldb_entry");
453 attr = ldb_attr_casefold(mem_ctx, t->u.present.attr);
454 if (attr == NULL) return NULL;
456 return lsqlite3_tprintf(mem_ctx,
457 "SELECT eid FROM ldb_attribute_values "
458 "WHERE norm_attr_name = '%q' ",
462 attr = ldb_attr_casefold(mem_ctx, t->u.equality.attr);
463 if (attr == NULL) return NULL;
464 a = ldb_schema_attribute_by_name(module->ldb, attr);
466 /* Get a canonicalised copy of the data */
467 a->syntax->canonicalise_fn(module->ldb, mem_ctx, &(t->u.equality.value), &value);
468 if (value.data == NULL) {
472 return lsqlite3_tprintf(mem_ctx,
473 "SELECT eid FROM ldb_attribute_values "
474 "WHERE norm_attr_name = '%q' "
475 "AND ldap_compare(norm_attr_value, '~%', 'q', '%q') ",
480 case LDB_OP_EXTENDED:
481 #warning "work out how to handle bitops"
488 /* should never occur */
496 * This function is used for the common case of queries that return a single
499 * NOTE: If more than one value is returned by the query, all but the first
500 * one will be ignored.
503 query_int(const struct lsqlite3_private * lsqlite3,
511 sqlite3_stmt * pStmt;
514 /* Begin access to variable argument list */
515 va_start(args, pSql);
517 /* Format the query */
518 if ((p = sqlite3_vmprintf(pSql, args)) == NULL) {
523 * Prepare and execute the SQL statement. Loop allows retrying on
524 * certain errors, e.g. SQLITE_SCHEMA occurs if the schema changes,
525 * requiring retrying the operation.
527 for (bLoop = TRUE; bLoop; ) {
529 /* Compile the SQL statement into sqlite virtual machine */
530 if ((ret = sqlite3_prepare(lsqlite3->sqlite,
534 NULL)) == SQLITE_SCHEMA) {
535 if (stmtGetEID != NULL) {
536 sqlite3_finalize(stmtGetEID);
540 } else if (ret != SQLITE_OK) {
544 /* One row expected */
545 if ((ret = sqlite3_step(pStmt)) == SQLITE_SCHEMA) {
546 if (stmtGetEID != NULL) {
547 sqlite3_finalize(stmtGetEID);
550 (void) sqlite3_finalize(pStmt);
552 } else if (ret != SQLITE_ROW) {
553 (void) sqlite3_finalize(pStmt);
557 /* Get the value to be returned */
558 *pRet = sqlite3_column_int64(pStmt, 0);
560 /* Free the virtual machine */
561 if ((ret = sqlite3_finalize(pStmt)) == SQLITE_SCHEMA) {
562 if (stmtGetEID != NULL) {
563 sqlite3_finalize(stmtGetEID);
567 } else if (ret != SQLITE_OK) {
568 (void) sqlite3_finalize(pStmt);
573 * Normal condition is only one time through loop. Loop is
574 * rerun in error conditions, via "continue", above.
579 /* All done with variable argument list */
583 /* Free the memory we allocated for our query string */
590 * This is a bad hack to support ldap style comparisons whithin sqlite.
591 * val is the attribute in the row currently under test
592 * func is the desired test "<=" ">=" "~" ":"
593 * cmp is the value to compare against (eg: "test")
594 * attr is the attribute name the value of which we want to test
597 static void lsqlite3_compare(sqlite3_context *ctx, int argc,
598 sqlite3_value **argv)
600 struct ldb_context *ldb = (struct ldb_context *)sqlite3_user_data(ctx);
601 const char *val = (const char *)sqlite3_value_text(argv[0]);
602 const char *func = (const char *)sqlite3_value_text(argv[1]);
603 const char *cmp = (const char *)sqlite3_value_text(argv[2]);
604 const char *attr = (const char *)sqlite3_value_text(argv[3]);
605 const struct ldb_schema_attribute *a;
613 a = ldb_schema_attribute_by_name(ldb, attr);
614 valX.data = (void *)cmp;
615 valX.length = strlen(cmp);
616 valY.data = (void *)val;
617 valY.length = strlen(val);
618 ret = a->syntax->comparison_fn(ldb, ldb, &valY, &valX);
620 sqlite3_result_int(ctx, 1);
622 sqlite3_result_int(ctx, 0);
627 a = ldb_schema_attribute_by_name(ldb, attr);
628 valX.data = (void *)cmp;
629 valX.length = strlen(cmp);
630 valY.data = (void *)val;
631 valY.length = strlen(val);
632 ret = a->syntax->comparison_fn(ldb, ldb, &valY, &valX);
634 sqlite3_result_int(ctx, 1);
636 sqlite3_result_int(ctx, 0);
642 sqlite3_result_int(ctx, 0);
648 sqlite3_result_int(ctx, 0);
655 sqlite3_result_error(ctx, "Value must start with a special operation char (<>~:)!", -1);
660 /* rename a record */
661 static int lsqlite3_safe_rollback(sqlite3 *sqlite)
667 ret = sqlite3_exec(sqlite, "ROLLBACK;", NULL, NULL, &errmsg);
668 if (ret != SQLITE_OK) {
670 printf("lsqlite3_safe_rollback: Error: %s\n", errmsg);
679 /* return an eid as result */
680 static int lsqlite3_eid_callback(void *result, int col_num, char **cols, char **names)
682 long long *eid = (long long *)result;
684 if (col_num != 1) return SQLITE_ABORT;
685 if (strcasecmp(names[0], "eid") != 0) return SQLITE_ABORT;
687 *eid = atoll(cols[0]);
692 * add a single set of ldap message values to a ldb_message
694 static int lsqlite3_search_callback(void *result, int col_num, char **cols, char **names)
696 struct ldb_handle *handle = talloc_get_type(result, struct ldb_handle);
697 struct lsql_context *ac = talloc_get_type(handle->private_data, struct lsql_context);
698 struct ldb_message *msg;
702 /* eid, dn, attr_name, attr_value */
706 eid = atoll(cols[0]);
708 if (eid != ac->current_eid) { /* here begin a new entry */
710 /* call the async callback for the last entry
711 * except the first time */
712 if (ac->current_eid != 0) {
713 ac->ares->message = ldb_msg_canonicalize(ac->module->ldb, ac->ares->message);
714 if (ac->ares->message == NULL)
717 handle->status = ac->callback(ac->module->ldb, ac->context, ac->ares);
718 if (handle->status != LDB_SUCCESS)
723 ac->ares = talloc_zero(ac, struct ldb_reply);
727 ac->ares->message = ldb_msg_new(ac->ares);
728 if (!ac->ares->message)
731 ac->ares->type = LDB_REPLY_ENTRY;
732 ac->current_eid = eid;
735 msg = ac->ares->message;
737 if (msg->dn == NULL) {
738 msg->dn = ldb_dn_new(msg, ac->module->ldb, cols[1]);
745 for (i = 0; ac->attrs[i]; i++) {
746 if (strcasecmp(cols[2], ac->attrs[i]) == 0) {
751 if (!found) return SQLITE_OK;
754 if (ldb_msg_add_string(msg, cols[2], cols[3]) != 0) {
764 * lsqlite3_get_eid_ndn()
766 * These functions are used for the very common case of retrieving an EID value
767 * given a (normalized) DN.
770 static long long lsqlite3_get_eid_ndn(sqlite3 *sqlite, void *mem_ctx, const char *norm_dn)
778 query = lsqlite3_tprintf(mem_ctx, "SELECT eid "
780 "WHERE norm_dn = '%q';", norm_dn);
781 if (query == NULL) return -1;
783 ret = sqlite3_exec(sqlite, query, lsqlite3_eid_callback, &eid, &errmsg);
784 if (ret != SQLITE_OK) {
786 printf("lsqlite3_get_eid: Fatal Error: %s\n", errmsg);
795 static long long lsqlite3_get_eid(struct ldb_module *module, struct ldb_dn *dn)
797 TALLOC_CTX *local_ctx;
798 struct lsqlite3_private *lsqlite3 = module->private_data;
802 /* ignore ltdb specials */
803 if (ldb_dn_is_special(dn)) {
807 /* create a local ctx */
808 local_ctx = talloc_named(lsqlite3, 0, "lsqlite3_get_eid local context");
809 if (local_ctx == NULL) {
813 cdn = ldb_dn_alloc_casefold(local_ctx, dn);
816 eid = lsqlite3_get_eid_ndn(lsqlite3->sqlite, local_ctx, cdn);
819 talloc_free(local_ctx);
824 * Interface functions referenced by lsqlite3_ops
827 /* search for matching records, by tree */
828 int lsql_search(struct ldb_module *module, struct ldb_request *req)
830 struct lsqlite3_private *lsqlite3 = talloc_get_type(module->private_data, struct lsqlite3_private);
831 struct lsql_context *lsql_ac;
838 req->handle = init_handle(lsqlite3, module, req);
839 if (req->handle == NULL) {
840 return LDB_ERR_OPERATIONS_ERROR;
843 lsql_ac = talloc_get_type(req->handle->private_data, struct lsql_context);
845 if ((( ! ldb_dn_is_valid(req->op.search.base)) || ldb_dn_is_null(req->op.search.base)) &&
846 (req->op.search.scope == LDB_SCOPE_BASE || req->op.search.scope == LDB_SCOPE_ONELEVEL))
847 return LDB_ERR_OPERATIONS_ERROR;
849 if (req->op.search.base) {
850 norm_basedn = ldb_dn_alloc_casefold(lsql_ac, req->op.search.base);
851 if (norm_basedn == NULL) {
852 ret = LDB_ERR_INVALID_DN_SYNTAX;
855 } else norm_basedn = talloc_strdup(lsql_ac, "");
857 /* Convert filter into a series of SQL conditions (constraints) */
858 sqlfilter = parsetree_to_sql(module, lsql_ac, req->op.search.tree);
860 switch(req->op.search.scope) {
861 case LDB_SCOPE_DEFAULT:
862 case LDB_SCOPE_SUBTREE:
863 if (*norm_basedn != '\0') {
864 query = lsqlite3_tprintf(lsql_ac,
865 "SELECT entry.eid,\n"
869 " FROM ldb_entry AS entry\n"
871 " LEFT OUTER JOIN ldb_attribute_values AS av\n"
872 " ON av.eid = entry.eid\n"
874 " WHERE entry.eid IN\n"
875 " (SELECT DISTINCT ldb_entry.eid\n"
877 " WHERE (ldb_entry.norm_dn GLOB('*,%q')\n"
878 " OR ldb_entry.norm_dn = '%q')\n"
879 " AND ldb_entry.eid IN\n"
883 " ORDER BY entry.eid ASC;",
888 query = lsqlite3_tprintf(lsql_ac,
889 "SELECT entry.eid,\n"
893 " FROM ldb_entry AS entry\n"
895 " LEFT OUTER JOIN ldb_attribute_values AS av\n"
896 " ON av.eid = entry.eid\n"
898 " WHERE entry.eid IN\n"
899 " (SELECT DISTINCT ldb_entry.eid\n"
901 " WHERE ldb_entry.eid IN\n"
905 " ORDER BY entry.eid ASC;",
912 query = lsqlite3_tprintf(lsql_ac,
913 "SELECT entry.eid,\n"
917 " FROM ldb_entry AS entry\n"
919 " LEFT OUTER JOIN ldb_attribute_values AS av\n"
920 " ON av.eid = entry.eid\n"
922 " WHERE entry.eid IN\n"
923 " (SELECT DISTINCT ldb_entry.eid\n"
925 " WHERE ldb_entry.norm_dn = '%q'\n"
926 " AND ldb_entry.eid IN\n"
930 " ORDER BY entry.eid ASC;",
935 case LDB_SCOPE_ONELEVEL:
936 query = lsqlite3_tprintf(lsql_ac,
937 "SELECT entry.eid,\n"
941 " FROM ldb_entry AS entry\n"
943 " LEFT OUTER JOIN ldb_attribute_values AS av\n"
944 " ON av.eid = entry.eid\n"
946 " WHERE entry.eid IN\n"
947 " (SELECT DISTINCT ldb_entry.eid\n"
949 " WHERE norm_dn GLOB('*,%q')\n"
950 " AND NOT norm_dn GLOB('*,*,%q')\n"
951 " AND ldb_entry.eid IN\n(%s)\n"
954 " ORDER BY entry.eid ASC;",
966 printf ("%s\n", query);
969 lsql_ac->current_eid = 0;
970 lsql_ac->attrs = req->op.search.attrs;
971 lsql_ac->ares = NULL;
973 req->handle->state = LDB_ASYNC_PENDING;
975 ret = sqlite3_exec(lsqlite3->sqlite, query, lsqlite3_search_callback, req->handle, &errmsg);
976 if (ret != SQLITE_OK) {
978 ldb_set_errstring(module->ldb, errmsg);
984 /* complete the last message if any */
986 lsql_ac->ares->message = ldb_msg_canonicalize(module->ldb, lsql_ac->ares->message);
987 if (lsql_ac->ares->message == NULL)
990 req->handle->status = lsql_ac->callback(module->ldb, lsql_ac->context, lsql_ac->ares);
991 if (req->handle->status != LDB_SUCCESS)
995 req->handle->state = LDB_ASYNC_DONE;
1000 return LDB_ERR_OPERATIONS_ERROR;
1004 static int lsql_add(struct ldb_module *module, struct ldb_request *req)
1006 struct lsqlite3_private *lsqlite3 = talloc_get_type(module->private_data, struct lsqlite3_private);
1007 struct lsql_context *lsql_ac;
1008 struct ldb_message *msg = req->op.add.message;
1014 int ret = LDB_SUCCESS;
1016 req->handle = init_handle(lsqlite3, module, req);
1017 if (req->handle == NULL) {
1018 return LDB_ERR_OPERATIONS_ERROR;
1020 lsql_ac = talloc_get_type(req->handle->private_data, struct lsql_context);
1021 req->handle->state = LDB_ASYNC_DONE;
1022 req->handle->status = LDB_SUCCESS;
1024 /* See if this is an ltdb special */
1025 if (ldb_dn_is_special(msg->dn)) {
1028 c = ldb_dn_new(local_ctx, module->ldb, "@INDEXLIST");
1029 if (ldb_dn_compare(module->ldb, msg->dn, c) == 0) {
1030 #warning "should we handle indexes somehow ?"
1031 ret = LDB_ERR_UNWILLING_TO_PERFORM;
1035 /* Others return an error */
1036 ret = LDB_ERR_UNWILLING_TO_PERFORM;
1040 /* create linearized and normalized dns */
1041 dn = ldb_dn_alloc_linearized(lsql_ac, msg->dn);
1042 ndn = ldb_dn_alloc_casefold(lsql_ac, msg->dn);
1043 if (dn == NULL || ndn == NULL) {
1044 ret = LDB_ERR_OTHER;
1048 query = lsqlite3_tprintf(lsql_ac,
1050 "INSERT OR ABORT INTO ldb_entry "
1051 "('dn', 'norm_dn') "
1052 "VALUES ('%q', '%q');",
1054 if (query == NULL) {
1055 ret = LDB_ERR_OTHER;
1059 ret = sqlite3_exec(lsqlite3->sqlite, query, NULL, NULL, &errmsg);
1060 if (ret != SQLITE_OK) {
1062 ldb_set_errstring(module->ldb, errmsg);
1065 ret = LDB_ERR_OTHER;
1069 eid = lsqlite3_get_eid_ndn(lsqlite3->sqlite, lsql_ac, ndn);
1071 ret = LDB_ERR_OTHER;
1075 for (i = 0; i < msg->num_elements; i++) {
1076 const struct ldb_message_element *el = &msg->elements[i];
1077 const struct ldb_schema_attribute *a;
1081 /* Get a case-folded copy of the attribute name */
1082 attr = ldb_attr_casefold(lsql_ac, el->name);
1084 ret = LDB_ERR_OTHER;
1088 a = ldb_schema_attribute_by_name(module->ldb, el->name);
1090 /* For each value of the specified attribute name... */
1091 for (j = 0; j < el->num_values; j++) {
1092 struct ldb_val value;
1095 /* Get a canonicalised copy of the data */
1096 a->syntax->canonicalise_fn(module->ldb, lsql_ac, &(el->values[j]), &value);
1097 if (value.data == NULL) {
1098 ret = LDB_ERR_OTHER;
1102 insert = lsqlite3_tprintf(lsql_ac,
1103 "INSERT OR ROLLBACK INTO ldb_attribute_values "
1104 "('eid', 'attr_name', 'norm_attr_name',"
1105 " 'attr_value', 'norm_attr_value') "
1106 "VALUES ('%lld', '%q', '%q', '%q', '%q');",
1107 eid, el->name, attr,
1108 el->values[j].data, value.data);
1109 if (insert == NULL) {
1110 ret = LDB_ERR_OTHER;
1114 ret = sqlite3_exec(lsqlite3->sqlite, insert, NULL, NULL, &errmsg);
1115 if (ret != SQLITE_OK) {
1117 ldb_set_errstring(module->ldb, errmsg);
1120 ret = LDB_ERR_OTHER;
1126 if (lsql_ac->callback) {
1127 req->handle->status = lsql_ac->callback(module->ldb, lsql_ac->context, NULL);
1131 req->handle->state = LDB_ASYNC_DONE;
1135 /* modify a record */
1136 static int lsql_modify(struct ldb_module *module, struct ldb_request *req)
1138 struct lsqlite3_private *lsqlite3 = talloc_get_type(module->private_data, struct lsqlite3_private);
1139 struct lsql_context *lsql_ac;
1140 struct ldb_message *msg = req->op.mod.message;
1144 int ret = LDB_SUCCESS;
1146 req->handle = init_handle(lsqlite3, module, req);
1147 if (req->handle == NULL) {
1148 return LDB_ERR_OPERATIONS_ERROR;
1150 lsql_ac = talloc_get_type(req->handle->private_data, struct lsql_context);
1151 req->handle->state = LDB_ASYNC_DONE;
1152 req->handle->status = LDB_SUCCESS;
1154 /* See if this is an ltdb special */
1155 if (ldb_dn_is_special(msg->dn)) {
1156 /* Others return an error */
1157 ret = LDB_ERR_UNWILLING_TO_PERFORM;
1161 eid = lsqlite3_get_eid(module, msg->dn);
1163 ret = LDB_ERR_OTHER;
1167 for (i = 0; i < msg->num_elements; i++) {
1168 const struct ldb_message_element *el = &msg->elements[i];
1169 const struct ldb_schema_attribute *a;
1170 int flags = el->flags & LDB_FLAG_MOD_MASK;
1175 /* Get a case-folded copy of the attribute name */
1176 attr = ldb_attr_casefold(lsql_ac, el->name);
1178 ret = LDB_ERR_OTHER;
1182 a = ldb_schema_attribute_by_name(module->ldb, el->name);
1186 case LDB_FLAG_MOD_REPLACE:
1188 /* remove all attributes before adding the replacements */
1189 mod = lsqlite3_tprintf(lsql_ac,
1190 "DELETE FROM ldb_attribute_values "
1191 "WHERE eid = '%lld' "
1192 "AND norm_attr_name = '%q';",
1195 ret = LDB_ERR_OTHER;
1199 ret = sqlite3_exec(lsqlite3->sqlite, mod, NULL, NULL, &errmsg);
1200 if (ret != SQLITE_OK) {
1202 ldb_set_errstring(module->ldb, errmsg);
1205 ret = LDB_ERR_OTHER;
1209 /* MISSING break is INTENTIONAL */
1211 case LDB_FLAG_MOD_ADD:
1212 #warning "We should throw an error if no value is provided!"
1213 /* For each value of the specified attribute name... */
1214 for (j = 0; j < el->num_values; j++) {
1215 struct ldb_val value;
1217 /* Get a canonicalised copy of the data */
1218 a->syntax->canonicalise_fn(module->ldb, lsql_ac, &(el->values[j]), &value);
1219 if (value.data == NULL) {
1220 ret = LDB_ERR_OTHER;
1224 mod = lsqlite3_tprintf(lsql_ac,
1225 "INSERT OR ROLLBACK INTO ldb_attribute_values "
1226 "('eid', 'attr_name', 'norm_attr_name',"
1227 " 'attr_value', 'norm_attr_value') "
1228 "VALUES ('%lld', '%q', '%q', '%q', '%q');",
1229 eid, el->name, attr,
1230 el->values[j].data, value.data);
1233 ret = LDB_ERR_OTHER;
1237 ret = sqlite3_exec(lsqlite3->sqlite, mod, NULL, NULL, &errmsg);
1238 if (ret != SQLITE_OK) {
1240 ldb_set_errstring(module->ldb, errmsg);
1243 ret = LDB_ERR_OTHER;
1250 case LDB_FLAG_MOD_DELETE:
1251 #warning "We should throw an error if the attribute we are trying to delete does not exist!"
1252 if (el->num_values == 0) {
1253 mod = lsqlite3_tprintf(lsql_ac,
1254 "DELETE FROM ldb_attribute_values "
1255 "WHERE eid = '%lld' "
1256 "AND norm_attr_name = '%q';",
1259 ret = LDB_ERR_OTHER;
1263 ret = sqlite3_exec(lsqlite3->sqlite, mod, NULL, NULL, &errmsg);
1264 if (ret != SQLITE_OK) {
1266 ldb_set_errstring(module->ldb, errmsg);
1269 ret = LDB_ERR_OTHER;
1274 /* For each value of the specified attribute name... */
1275 for (j = 0; j < el->num_values; j++) {
1276 struct ldb_val value;
1278 /* Get a canonicalised copy of the data */
1279 a->syntax->canonicalise_fn(module->ldb, lsql_ac, &(el->values[j]), &value);
1280 if (value.data == NULL) {
1281 ret = LDB_ERR_OTHER;
1285 mod = lsqlite3_tprintf(lsql_ac,
1286 "DELETE FROM ldb_attribute_values "
1287 "WHERE eid = '%lld' "
1288 "AND norm_attr_name = '%q' "
1289 "AND norm_attr_value = '%q';",
1290 eid, attr, value.data);
1293 ret = LDB_ERR_OTHER;
1297 ret = sqlite3_exec(lsqlite3->sqlite, mod, NULL, NULL, &errmsg);
1298 if (ret != SQLITE_OK) {
1300 ldb_set_errstring(module->ldb, errmsg);
1303 ret = LDB_ERR_OTHER;
1312 if (lsql_ac->callback) {
1313 req->handle->status = lsql_ac->callback(module->ldb, lsql_ac->context, NULL);
1317 req->handle->state = LDB_ASYNC_DONE;
1321 /* delete a record */
1322 static int lsql_delete(struct ldb_module *module, struct ldb_request *req)
1324 struct lsqlite3_private *lsqlite3 = talloc_get_type(module->private_data, struct lsqlite3_private);
1325 struct lsql_context *lsql_ac;
1329 int ret = LDB_SUCCESS;
1332 req->handle = init_handle(lsqlite3, module, req);
1333 if (req->handle == NULL) {
1334 return LDB_ERR_OPERATIONS_ERROR;
1336 lsql_ac = talloc_get_type(req->handle->private_data, struct lsql_context);
1337 req->handle->state = LDB_ASYNC_DONE;
1338 req->handle->status = LDB_SUCCESS;
1340 eid = lsqlite3_get_eid(module, req->op.del.dn);
1345 query = lsqlite3_tprintf(lsql_ac,
1347 "DELETE FROM ldb_entry WHERE eid = %lld; "
1348 /* Delete attributes */
1349 "DELETE FROM ldb_attribute_values WHERE eid = %lld; ",
1351 if (query == NULL) {
1352 ret = LDB_ERR_OTHER;
1356 ret = sqlite3_exec(lsqlite3->sqlite, query, NULL, NULL, &errmsg);
1357 if (ret != SQLITE_OK) {
1359 ldb_set_errstring(module->ldb, errmsg);
1362 req->handle->status = LDB_ERR_OPERATIONS_ERROR;
1366 if (lsql_ac->callback) {
1367 ret = lsql_ac->callback(module->ldb, lsql_ac->context, NULL);
1371 req->handle->state = LDB_ASYNC_DONE;
1375 /* rename a record */
1376 static int lsql_rename(struct ldb_module *module, struct ldb_request *req)
1378 struct lsqlite3_private *lsqlite3 = talloc_get_type(module->private_data, struct lsqlite3_private);
1379 struct lsql_context *lsql_ac;
1380 char *new_dn, *new_cdn, *old_cdn;
1383 int ret = LDB_SUCCESS;
1385 req->handle = init_handle(lsqlite3, module, req);
1386 if (req->handle == NULL) {
1387 return LDB_ERR_OPERATIONS_ERROR;
1389 lsql_ac = talloc_get_type(req->handle->private_data, struct lsql_context);
1390 req->handle->state = LDB_ASYNC_DONE;
1391 req->handle->status = LDB_SUCCESS;
1393 /* create linearized and normalized dns */
1394 old_cdn = ldb_dn_alloc_casefold(lsql_ac, req->op.rename.olddn);
1395 new_cdn = ldb_dn_alloc_casefold(lsql_ac, req->op.rename.newdn);
1396 new_dn = ldb_dn_alloc_linearized(lsql_ac, req->op.rename.newdn);
1397 if (old_cdn == NULL || new_cdn == NULL || new_dn == NULL) {
1401 /* build the SQL query */
1402 query = lsqlite3_tprintf(lsql_ac,
1403 "UPDATE ldb_entry SET dn = '%q', norm_dn = '%q' "
1404 "WHERE norm_dn = '%q';",
1405 new_dn, new_cdn, old_cdn);
1406 if (query == NULL) {
1411 ret = sqlite3_exec(lsqlite3->sqlite, query, NULL, NULL, &errmsg);
1412 if (ret != SQLITE_OK) {
1414 ldb_set_errstring(module->ldb, errmsg);
1417 ret = LDB_ERR_OPERATIONS_ERROR;
1421 if (lsql_ac->callback) {
1422 ret = lsql_ac->callback(module->ldb, lsql_ac->context, NULL);
1426 req->handle->state = LDB_ASYNC_DONE;
1430 static int lsql_start_trans(struct ldb_module * module)
1434 struct lsqlite3_private * lsqlite3 = module->private_data;
1436 if (lsqlite3->trans_count == 0) {
1437 ret = sqlite3_exec(lsqlite3->sqlite, "BEGIN IMMEDIATE;", NULL, NULL, &errmsg);
1438 if (ret != SQLITE_OK) {
1440 printf("lsqlite3_start_trans: error: %s\n", errmsg);
1443 return SQLITE_ERROR;
1447 lsqlite3->trans_count++;
1452 static int lsql_end_trans(struct ldb_module *module)
1456 struct lsqlite3_private *lsqlite3 = module->private_data;
1458 if (lsqlite3->trans_count > 0) {
1459 lsqlite3->trans_count--;
1460 } else return SQLITE_ERROR;
1462 if (lsqlite3->trans_count == 0) {
1463 ret = sqlite3_exec(lsqlite3->sqlite, "COMMIT;", NULL, NULL, &errmsg);
1464 if (ret != SQLITE_OK) {
1466 printf("lsqlite3_end_trans: error: %s\n", errmsg);
1469 return SQLITE_ERROR;
1476 static int lsql_del_trans(struct ldb_module *module)
1478 struct lsqlite3_private *lsqlite3 = module->private_data;
1480 if (lsqlite3->trans_count > 0) {
1481 lsqlite3->trans_count--;
1482 } else return SQLITE_ERROR;
1484 if (lsqlite3->trans_count == 0) {
1485 return lsqlite3_safe_rollback(lsqlite3->sqlite);
1488 return SQLITE_ERROR;
1491 static int destructor(struct lsqlite3_private *lsqlite3)
1493 if (lsqlite3->sqlite) {
1494 sqlite3_close(lsqlite3->sqlite);
1499 static int lsql_request(struct ldb_module *module, struct ldb_request *req)
1501 return LDB_ERR_OPERATIONS_ERROR;
1504 static int lsql_wait(struct ldb_handle *handle, enum ldb_wait_type type)
1506 return handle->status;
1510 * Table of operations for the sqlite3 backend
1512 static const struct ldb_module_ops lsqlite3_ops = {
1514 .search = lsql_search,
1516 .modify = lsql_modify,
1518 .rename = lsql_rename,
1519 .request = lsql_request,
1520 .start_transaction = lsql_start_trans,
1521 .end_transaction = lsql_end_trans,
1522 .del_transaction = lsql_del_trans,
1530 static int initialize(struct lsqlite3_private *lsqlite3,
1531 struct ldb_context *ldb, const char *url, int flags)
1533 TALLOC_CTX *local_ctx;
1540 /* create a local ctx */
1541 local_ctx = talloc_named(lsqlite3, 0, "lsqlite3_rename local context");
1542 if (local_ctx == NULL) {
1543 return SQLITE_ERROR;
1546 schema = lsqlite3_tprintf(local_ctx,
1549 "CREATE TABLE ldb_info AS "
1550 " SELECT 'LDB' AS database_type,"
1551 " '1.0' AS version;"
1554 * The entry table holds the information about an entry.
1555 * This table is used to obtain the EID of the entry and to
1556 * support scope=one and scope=base. The parent and child
1557 * table is included in the entry table since all the other
1558 * attributes are dependent on EID.
1560 "CREATE TABLE ldb_entry "
1562 " eid INTEGER PRIMARY KEY AUTOINCREMENT,"
1563 " dn TEXT UNIQUE NOT NULL,"
1564 " norm_dn TEXT UNIQUE NOT NULL"
1568 "CREATE TABLE ldb_object_classes"
1570 " class_name TEXT PRIMARY KEY,"
1571 " parent_class_name TEXT,"
1572 " tree_key TEXT UNIQUE,"
1573 " max_child_num INTEGER DEFAULT 0"
1577 * We keep a full listing of attribute/value pairs here
1579 "CREATE TABLE ldb_attribute_values"
1581 " eid INTEGER REFERENCES ldb_entry,"
1583 " norm_attr_name TEXT,"
1585 " norm_attr_value TEXT "
1592 "CREATE INDEX ldb_attribute_values_eid_idx "
1593 " ON ldb_attribute_values (eid);"
1595 "CREATE INDEX ldb_attribute_values_name_value_idx "
1596 " ON ldb_attribute_values (attr_name, norm_attr_value);"
1604 "CREATE TRIGGER ldb_object_classes_insert_tr"
1606 " ON ldb_object_classes"
1609 " UPDATE ldb_object_classes"
1610 " SET tree_key = COALESCE(tree_key, "
1612 " SELECT tree_key || "
1613 " (SELECT base160(max_child_num + 1)"
1614 " FROM ldb_object_classes"
1615 " WHERE class_name = "
1616 " new.parent_class_name)"
1617 " FROM ldb_object_classes "
1618 " WHERE class_name = new.parent_class_name "
1620 " UPDATE ldb_object_classes "
1621 " SET max_child_num = max_child_num + 1"
1622 " WHERE class_name = new.parent_class_name;"
1626 * Table initialization
1629 "INSERT INTO ldb_object_classes "
1630 " (class_name, tree_key) "
1632 " ('TOP', '0001');");
1634 /* Skip protocol indicator of url */
1635 if (strncmp(url, "sqlite3://", 10) != 0) {
1636 return SQLITE_MISUSE;
1639 /* Update pointer to just after the protocol indicator */
1642 /* Try to open the (possibly empty/non-existent) database */
1643 if ((ret = sqlite3_open(url, &lsqlite3->sqlite)) != SQLITE_OK) {
1647 /* In case this is a new database, enable auto_vacuum */
1648 ret = sqlite3_exec(lsqlite3->sqlite, "PRAGMA auto_vacuum = 1;", NULL, NULL, &errmsg);
1649 if (ret != SQLITE_OK) {
1651 printf("lsqlite3 initializaion error: %s\n", errmsg);
1657 if (flags & LDB_FLG_NOSYNC) {
1659 ret = sqlite3_exec(lsqlite3->sqlite, "PRAGMA synchronous = OFF;", NULL, NULL, &errmsg);
1660 if (ret != SQLITE_OK) {
1662 printf("lsqlite3 initializaion error: %s\n", errmsg);
1671 /* Establish a busy timeout of 30 seconds */
1672 if ((ret = sqlite3_busy_timeout(lsqlite3->sqlite,
1673 30000)) != SQLITE_OK) {
1677 /* Create a function, callable from sql, to increment a tree_key */
1679 sqlite3_create_function(lsqlite3->sqlite,/* handle */
1680 "base160_next", /* function name */
1681 1, /* number of args */
1682 SQLITE_ANY, /* preferred text type */
1683 NULL, /* user data */
1684 base160next_sql, /* called func */
1685 NULL, /* step func */
1686 NULL /* final func */
1691 /* Create a function, callable from sql, to convert int to base160 */
1693 sqlite3_create_function(lsqlite3->sqlite,/* handle */
1694 "base160", /* function name */
1695 1, /* number of args */
1696 SQLITE_ANY, /* preferred text type */
1697 NULL, /* user data */
1698 base160_sql, /* called func */
1699 NULL, /* step func */
1700 NULL /* final func */
1705 /* Create a function, callable from sql, to perform various comparisons */
1707 sqlite3_create_function(lsqlite3->sqlite, /* handle */
1708 "ldap_compare", /* function name */
1709 4, /* number of args */
1710 SQLITE_ANY, /* preferred text type */
1711 ldb , /* user data */
1712 lsqlite3_compare, /* called func */
1713 NULL, /* step func */
1714 NULL /* final func */
1719 /* Begin a transaction */
1720 ret = sqlite3_exec(lsqlite3->sqlite, "BEGIN EXCLUSIVE;", NULL, NULL, &errmsg);
1721 if (ret != SQLITE_OK) {
1723 printf("lsqlite3: initialization error: %s\n", errmsg);
1730 /* Determine if this is a new database. No tables means it is. */
1731 if (query_int(lsqlite3,
1734 " FROM sqlite_master\n"
1735 " WHERE type = 'table';") != 0) {
1739 if (queryInt == 0) {
1741 * Create the database schema
1743 ret = sqlite3_exec(lsqlite3->sqlite, schema, NULL, NULL, &errmsg);
1744 if (ret != SQLITE_OK) {
1746 printf("lsqlite3 initializaion error: %s\n", errmsg);
1753 * Ensure that the database we opened is one of ours
1755 if (query_int(lsqlite3,
1758 " (SELECT COUNT(*) = 2"
1759 " FROM sqlite_master "
1760 " WHERE type = 'table' "
1764 " 'ldb_object_classes' "
1770 " WHERE database_type = 'LDB' "
1771 " AND version = '1.0'"
1775 /* It's not one that we created. See ya! */
1780 /* Commit the transaction */
1781 ret = sqlite3_exec(lsqlite3->sqlite, "COMMIT;", NULL, NULL, &errmsg);
1782 if (ret != SQLITE_OK) {
1784 printf("lsqlite3: iniialization error: %s\n", errmsg);
1793 if (rollback) lsqlite3_safe_rollback(lsqlite3->sqlite);
1794 sqlite3_close(lsqlite3->sqlite);
1795 return SQLITE_ERROR;
1799 * connect to the database
1801 static int lsqlite3_connect(struct ldb_context *ldb,
1804 const char *options[],
1805 struct ldb_module **module)
1809 struct lsqlite3_private * lsqlite3 = NULL;
1811 lsqlite3 = talloc(ldb, struct lsqlite3_private);
1816 lsqlite3->sqlite = NULL;
1817 lsqlite3->options = NULL;
1818 lsqlite3->trans_count = 0;
1820 ret = initialize(lsqlite3, ldb, url, flags);
1821 if (ret != SQLITE_OK) {
1825 talloc_set_destructor(lsqlite3, destructor);
1829 *module = talloc(ldb, struct ldb_module);
1834 talloc_set_name_const(*module, "ldb_sqlite3 backend");
1835 (*module)->ldb = ldb;
1836 (*module)->prev = (*module)->next = NULL;
1837 (*module)->private_data = lsqlite3;
1838 (*module)->ops = &lsqlite3_ops;
1842 * take a copy of the options array, so we don't have to rely
1843 * on the caller keeping it around (it might be dynamic)
1845 for (i=0;options[i];i++) ;
1847 lsqlite3->options = talloc_array(lsqlite3, char *, i+1);
1848 if (!lsqlite3->options) {
1852 for (i=0;options[i];i++) {
1854 lsqlite3->options[i+1] = NULL;
1855 lsqlite3->options[i] =
1856 talloc_strdup(lsqlite3->options, options[i]);
1857 if (!lsqlite3->options[i]) {
1866 if (lsqlite3->sqlite != NULL) {
1867 (void) sqlite3_close(lsqlite3->sqlite);
1869 talloc_free(lsqlite3);
1870 return LDB_ERR_OPERATIONS_ERROR;
1873 const struct ldb_backend_ops ldb_sqlite3_backend_ops = {
1875 .connect_fn = lsqlite3_connect