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, "objectclass") == 0) {
354 * For object classes, we want to search for all objectclasses
355 * that are subclasses as well.
357 return lsqlite3_tprintf(mem_ctx,
358 "SELECT eid FROM ldb_attribute_values\n"
359 "WHERE norm_attr_name = 'OBJECTCLASS' "
360 "AND norm_attr_value IN\n"
361 " (SELECT class_name FROM ldb_object_classes\n"
362 " WHERE tree_key GLOB\n"
363 " (SELECT tree_key FROM ldb_object_classes\n"
364 " WHERE class_name = '%q'\n"
368 } else if (strcasecmp(t->u.equality.attr, "dn") == 0) {
369 /* DN query is a special ldb case */
370 const char *cdn = ldb_dn_get_casefold(
371 ldb_dn_new(mem_ctx, module->ldb,
372 (const char *)value.data));
374 return lsqlite3_tprintf(mem_ctx,
375 "SELECT eid FROM ldb_entry "
376 "WHERE norm_dn = '%q'", cdn);
379 /* A normal query. */
380 return lsqlite3_tprintf(mem_ctx,
381 "SELECT eid FROM ldb_attribute_values "
382 "WHERE norm_attr_name = '%q' "
383 "AND norm_attr_value = '%q'",
389 case LDB_OP_SUBSTRING:
391 wild_card_string = talloc_strdup(mem_ctx,
392 (t->u.substring.start_with_wildcard)?"*":"");
393 if (wild_card_string == NULL) return NULL;
395 for (i = 0; t->u.substring.chunks[i]; i++) {
396 wild_card_string = talloc_asprintf_append(wild_card_string, "%s*",
397 t->u.substring.chunks[i]->data);
398 if (wild_card_string == NULL) return NULL;
401 if ( ! t->u.substring.end_with_wildcard ) {
402 /* remove last wildcard */
403 wild_card_string[strlen(wild_card_string) - 1] = '\0';
406 attr = ldb_attr_casefold(mem_ctx, t->u.substring.attr);
407 if (attr == NULL) return NULL;
408 a = ldb_schema_attribute_by_name(module->ldb, attr);
410 subval.data = (void *)wild_card_string;
411 subval.length = strlen(wild_card_string) + 1;
413 /* Get a canonicalised copy of the data */
414 a->syntax->canonicalise_fn(module->ldb, mem_ctx, &(subval), &value);
415 if (value.data == NULL) {
419 return lsqlite3_tprintf(mem_ctx,
420 "SELECT eid FROM ldb_attribute_values "
421 "WHERE norm_attr_name = '%q' "
422 "AND norm_attr_value GLOB '%q'",
427 attr = ldb_attr_casefold(mem_ctx, t->u.equality.attr);
428 if (attr == NULL) return NULL;
429 a = ldb_schema_attribute_by_name(module->ldb, attr);
431 /* Get a canonicalised copy of the data */
432 a->syntax->canonicalise_fn(module->ldb, mem_ctx, &(t->u.equality.value), &value);
433 if (value.data == NULL) {
437 return lsqlite3_tprintf(mem_ctx,
438 "SELECT eid FROM ldb_attribute_values "
439 "WHERE norm_attr_name = '%q' "
440 "AND ldap_compare(norm_attr_value, '>=', '%q', '%q') ",
446 attr = ldb_attr_casefold(mem_ctx, t->u.equality.attr);
447 if (attr == NULL) return NULL;
448 a = ldb_schema_attribute_by_name(module->ldb, attr);
450 /* Get a canonicalised copy of the data */
451 a->syntax->canonicalise_fn(module->ldb, mem_ctx, &(t->u.equality.value), &value);
452 if (value.data == NULL) {
456 return lsqlite3_tprintf(mem_ctx,
457 "SELECT eid FROM ldb_attribute_values "
458 "WHERE norm_attr_name = '%q' "
459 "AND ldap_compare(norm_attr_value, '<=', '%q', '%q') ",
465 if (strcasecmp(t->u.present.attr, "dn") == 0) {
466 return talloc_strdup(mem_ctx, "SELECT eid FROM ldb_entry");
469 attr = ldb_attr_casefold(mem_ctx, t->u.present.attr);
470 if (attr == NULL) return NULL;
472 return lsqlite3_tprintf(mem_ctx,
473 "SELECT eid FROM ldb_attribute_values "
474 "WHERE norm_attr_name = '%q' ",
478 attr = ldb_attr_casefold(mem_ctx, t->u.equality.attr);
479 if (attr == NULL) return NULL;
480 a = ldb_schema_attribute_by_name(module->ldb, attr);
482 /* Get a canonicalised copy of the data */
483 a->syntax->canonicalise_fn(module->ldb, mem_ctx, &(t->u.equality.value), &value);
484 if (value.data == NULL) {
488 return lsqlite3_tprintf(mem_ctx,
489 "SELECT eid FROM ldb_attribute_values "
490 "WHERE norm_attr_name = '%q' "
491 "AND ldap_compare(norm_attr_value, '~%', 'q', '%q') ",
496 case LDB_OP_EXTENDED:
497 #warning "work out how to handle bitops"
504 /* should never occur */
512 * This function is used for the common case of queries that return a single
515 * NOTE: If more than one value is returned by the query, all but the first
516 * one will be ignored.
519 query_int(const struct lsqlite3_private * lsqlite3,
527 sqlite3_stmt * pStmt;
530 /* Begin access to variable argument list */
531 va_start(args, pSql);
533 /* Format the query */
534 if ((p = sqlite3_vmprintf(pSql, args)) == NULL) {
539 * Prepare and execute the SQL statement. Loop allows retrying on
540 * certain errors, e.g. SQLITE_SCHEMA occurs if the schema changes,
541 * requiring retrying the operation.
543 for (bLoop = TRUE; bLoop; ) {
545 /* Compile the SQL statement into sqlite virtual machine */
546 if ((ret = sqlite3_prepare(lsqlite3->sqlite,
550 NULL)) == SQLITE_SCHEMA) {
551 if (stmtGetEID != NULL) {
552 sqlite3_finalize(stmtGetEID);
556 } else if (ret != SQLITE_OK) {
560 /* One row expected */
561 if ((ret = sqlite3_step(pStmt)) == SQLITE_SCHEMA) {
562 if (stmtGetEID != NULL) {
563 sqlite3_finalize(stmtGetEID);
566 (void) sqlite3_finalize(pStmt);
568 } else if (ret != SQLITE_ROW) {
569 (void) sqlite3_finalize(pStmt);
573 /* Get the value to be returned */
574 *pRet = sqlite3_column_int64(pStmt, 0);
576 /* Free the virtual machine */
577 if ((ret = sqlite3_finalize(pStmt)) == SQLITE_SCHEMA) {
578 if (stmtGetEID != NULL) {
579 sqlite3_finalize(stmtGetEID);
583 } else if (ret != SQLITE_OK) {
584 (void) sqlite3_finalize(pStmt);
589 * Normal condition is only one time through loop. Loop is
590 * rerun in error conditions, via "continue", above.
595 /* All done with variable argument list */
599 /* Free the memory we allocated for our query string */
606 * This is a bad hack to support ldap style comparisons whithin sqlite.
607 * val is the attribute in the row currently under test
608 * func is the desired test "<=" ">=" "~" ":"
609 * cmp is the value to compare against (eg: "test")
610 * attr is the attribute name the value of which we want to test
613 static void lsqlite3_compare(sqlite3_context *ctx, int argc,
614 sqlite3_value **argv)
616 struct ldb_context *ldb = (struct ldb_context *)sqlite3_user_data(ctx);
617 const char *val = (const char *)sqlite3_value_text(argv[0]);
618 const char *func = (const char *)sqlite3_value_text(argv[1]);
619 const char *cmp = (const char *)sqlite3_value_text(argv[2]);
620 const char *attr = (const char *)sqlite3_value_text(argv[3]);
621 const struct ldb_schema_attribute *a;
629 a = ldb_schema_attribute_by_name(ldb, attr);
630 valX.data = (void *)cmp;
631 valX.length = strlen(cmp);
632 valY.data = (void *)val;
633 valY.length = strlen(val);
634 ret = a->syntax->comparison_fn(ldb, ldb, &valY, &valX);
636 sqlite3_result_int(ctx, 1);
638 sqlite3_result_int(ctx, 0);
643 a = ldb_schema_attribute_by_name(ldb, attr);
644 valX.data = (void *)cmp;
645 valX.length = strlen(cmp);
646 valY.data = (void *)val;
647 valY.length = strlen(val);
648 ret = a->syntax->comparison_fn(ldb, ldb, &valY, &valX);
650 sqlite3_result_int(ctx, 1);
652 sqlite3_result_int(ctx, 0);
658 sqlite3_result_int(ctx, 0);
664 sqlite3_result_int(ctx, 0);
671 sqlite3_result_error(ctx, "Value must start with a special operation char (<>~:)!", -1);
676 /* rename a record */
677 static int lsqlite3_safe_rollback(sqlite3 *sqlite)
683 ret = sqlite3_exec(sqlite, "ROLLBACK;", NULL, NULL, &errmsg);
684 if (ret != SQLITE_OK) {
686 printf("lsqlite3_safe_rollback: Error: %s\n", errmsg);
695 /* return an eid as result */
696 static int lsqlite3_eid_callback(void *result, int col_num, char **cols, char **names)
698 long long *eid = (long long *)result;
700 if (col_num != 1) return SQLITE_ABORT;
701 if (strcasecmp(names[0], "eid") != 0) return SQLITE_ABORT;
703 *eid = atoll(cols[0]);
708 * add a single set of ldap message values to a ldb_message
710 static int lsqlite3_search_callback(void *result, int col_num, char **cols, char **names)
712 struct ldb_handle *handle = talloc_get_type(result, struct ldb_handle);
713 struct lsql_context *ac = talloc_get_type(handle->private_data, struct lsql_context);
714 struct ldb_message *msg;
718 /* eid, dn, attr_name, attr_value */
722 eid = atoll(cols[0]);
724 if (eid != ac->current_eid) { /* here begin a new entry */
726 /* call the async callback for the last entry
727 * except the first time */
728 if (ac->current_eid != 0) {
729 ac->ares->message = ldb_msg_canonicalize(ac->module->ldb, ac->ares->message);
730 if (ac->ares->message == NULL)
733 handle->status = ac->callback(ac->module->ldb, ac->context, ac->ares);
734 if (handle->status != LDB_SUCCESS)
739 ac->ares = talloc_zero(ac, struct ldb_reply);
743 ac->ares->message = ldb_msg_new(ac->ares);
744 if (!ac->ares->message)
747 ac->ares->type = LDB_REPLY_ENTRY;
748 ac->current_eid = eid;
751 msg = ac->ares->message;
753 if (msg->dn == NULL) {
754 msg->dn = ldb_dn_new(msg, ac->module->ldb, cols[1]);
761 for (i = 0; ac->attrs[i]; i++) {
762 if (strcasecmp(cols[2], ac->attrs[i]) == 0) {
767 if (!found) return SQLITE_OK;
770 if (ldb_msg_add_string(msg, cols[2], cols[3]) != 0) {
780 * lsqlite3_get_eid_ndn()
782 * These functions are used for the very common case of retrieving an EID value
783 * given a (normalized) DN.
786 static long long lsqlite3_get_eid_ndn(sqlite3 *sqlite, void *mem_ctx, const char *norm_dn)
794 query = lsqlite3_tprintf(mem_ctx, "SELECT eid "
796 "WHERE norm_dn = '%q';", norm_dn);
797 if (query == NULL) return -1;
799 ret = sqlite3_exec(sqlite, query, lsqlite3_eid_callback, &eid, &errmsg);
800 if (ret != SQLITE_OK) {
802 printf("lsqlite3_get_eid: Fatal Error: %s\n", errmsg);
811 static long long lsqlite3_get_eid(struct ldb_module *module, struct ldb_dn *dn)
813 TALLOC_CTX *local_ctx;
814 struct lsqlite3_private *lsqlite3 = module->private_data;
818 /* ignore ltdb specials */
819 if (ldb_dn_is_special(dn)) {
823 /* create a local ctx */
824 local_ctx = talloc_named(lsqlite3, 0, "lsqlite3_get_eid local context");
825 if (local_ctx == NULL) {
829 cdn = ldb_dn_alloc_casefold(local_ctx, dn);
832 eid = lsqlite3_get_eid_ndn(lsqlite3->sqlite, local_ctx, cdn);
835 talloc_free(local_ctx);
840 * Interface functions referenced by lsqlite3_ops
843 /* search for matching records, by tree */
844 int lsql_search(struct ldb_module *module, struct ldb_request *req)
846 struct lsqlite3_private *lsqlite3 = talloc_get_type(module->private_data, struct lsqlite3_private);
847 struct lsql_context *lsql_ac;
854 req->handle = init_handle(lsqlite3, module, req);
855 if (req->handle == NULL) {
856 return LDB_ERR_OPERATIONS_ERROR;
859 lsql_ac = talloc_get_type(req->handle->private_data, struct lsql_context);
861 if ((( ! ldb_dn_is_valid(req->op.search.base)) || ldb_dn_is_null(req->op.search.base)) &&
862 (req->op.search.scope == LDB_SCOPE_BASE || req->op.search.scope == LDB_SCOPE_ONELEVEL))
863 return LDB_ERR_OPERATIONS_ERROR;
865 if (req->op.search.base) {
866 norm_basedn = ldb_dn_alloc_casefold(lsql_ac, req->op.search.base);
867 if (norm_basedn == NULL) {
868 ret = LDB_ERR_INVALID_DN_SYNTAX;
871 } else norm_basedn = talloc_strdup(lsql_ac, "");
873 /* Convert filter into a series of SQL conditions (constraints) */
874 sqlfilter = parsetree_to_sql(module, lsql_ac, req->op.search.tree);
876 switch(req->op.search.scope) {
877 case LDB_SCOPE_DEFAULT:
878 case LDB_SCOPE_SUBTREE:
879 if (*norm_basedn != '\0') {
880 query = lsqlite3_tprintf(lsql_ac,
881 "SELECT entry.eid,\n"
885 " FROM ldb_entry AS entry\n"
887 " LEFT OUTER JOIN ldb_attribute_values AS av\n"
888 " ON av.eid = entry.eid\n"
890 " WHERE entry.eid IN\n"
891 " (SELECT DISTINCT ldb_entry.eid\n"
893 " WHERE (ldb_entry.norm_dn GLOB('*,%q')\n"
894 " OR ldb_entry.norm_dn = '%q')\n"
895 " AND ldb_entry.eid IN\n"
899 " ORDER BY entry.eid ASC;",
904 query = lsqlite3_tprintf(lsql_ac,
905 "SELECT entry.eid,\n"
909 " FROM ldb_entry AS entry\n"
911 " LEFT OUTER JOIN ldb_attribute_values AS av\n"
912 " ON av.eid = entry.eid\n"
914 " WHERE entry.eid IN\n"
915 " (SELECT DISTINCT ldb_entry.eid\n"
917 " WHERE ldb_entry.eid IN\n"
921 " ORDER BY entry.eid ASC;",
928 query = lsqlite3_tprintf(lsql_ac,
929 "SELECT entry.eid,\n"
933 " FROM ldb_entry AS entry\n"
935 " LEFT OUTER JOIN ldb_attribute_values AS av\n"
936 " ON av.eid = entry.eid\n"
938 " WHERE entry.eid IN\n"
939 " (SELECT DISTINCT ldb_entry.eid\n"
941 " WHERE ldb_entry.norm_dn = '%q'\n"
942 " AND ldb_entry.eid IN\n"
946 " ORDER BY entry.eid ASC;",
951 case LDB_SCOPE_ONELEVEL:
952 query = lsqlite3_tprintf(lsql_ac,
953 "SELECT entry.eid,\n"
957 " FROM ldb_entry AS entry\n"
959 " LEFT OUTER JOIN ldb_attribute_values AS av\n"
960 " ON av.eid = entry.eid\n"
962 " WHERE entry.eid IN\n"
963 " (SELECT DISTINCT ldb_entry.eid\n"
965 " WHERE norm_dn GLOB('*,%q')\n"
966 " AND NOT norm_dn GLOB('*,*,%q')\n"
967 " AND ldb_entry.eid IN\n(%s)\n"
970 " ORDER BY entry.eid ASC;",
982 printf ("%s\n", query);
985 lsql_ac->current_eid = 0;
986 lsql_ac->attrs = req->op.search.attrs;
987 lsql_ac->ares = NULL;
989 req->handle->state = LDB_ASYNC_PENDING;
991 ret = sqlite3_exec(lsqlite3->sqlite, query, lsqlite3_search_callback, req->handle, &errmsg);
992 if (ret != SQLITE_OK) {
994 ldb_set_errstring(module->ldb, errmsg);
1000 /* complete the last message if any */
1001 if (lsql_ac->ares) {
1002 lsql_ac->ares->message = ldb_msg_canonicalize(module->ldb, lsql_ac->ares->message);
1003 if (lsql_ac->ares->message == NULL)
1006 req->handle->status = lsql_ac->callback(module->ldb, lsql_ac->context, lsql_ac->ares);
1007 if (req->handle->status != LDB_SUCCESS)
1011 req->handle->state = LDB_ASYNC_DONE;
1016 return LDB_ERR_OPERATIONS_ERROR;
1020 static int lsql_add(struct ldb_module *module, struct ldb_request *req)
1022 struct lsqlite3_private *lsqlite3 = talloc_get_type(module->private_data, struct lsqlite3_private);
1023 struct lsql_context *lsql_ac;
1024 struct ldb_message *msg = req->op.add.message;
1030 int ret = LDB_SUCCESS;
1032 req->handle = init_handle(lsqlite3, module, req);
1033 if (req->handle == NULL) {
1034 return LDB_ERR_OPERATIONS_ERROR;
1036 lsql_ac = talloc_get_type(req->handle->private_data, struct lsql_context);
1037 req->handle->state = LDB_ASYNC_DONE;
1038 req->handle->status = LDB_SUCCESS;
1040 /* See if this is an ltdb special */
1041 if (ldb_dn_is_special(msg->dn)) {
1044 c = ldb_dn_new(lsql_ac, module->ldb, "@SUBCLASSES");
1045 if (ldb_dn_compare(msg->dn, c) == 0) {
1046 #warning "insert subclasses into object class tree"
1047 ret = LDB_ERR_UNWILLING_TO_PERFORM;
1052 c = ldb_dn_new(local_ctx, module->ldb, "@INDEXLIST");
1053 if (ldb_dn_compare(module->ldb, msg->dn, c) == 0) {
1054 #warning "should we handle indexes somehow ?"
1055 ret = LDB_ERR_UNWILLING_TO_PERFORM;
1059 /* Others return an error */
1060 ret = LDB_ERR_UNWILLING_TO_PERFORM;
1064 /* create linearized and normalized dns */
1065 dn = ldb_dn_alloc_linearized(lsql_ac, msg->dn);
1066 ndn = ldb_dn_alloc_casefold(lsql_ac, msg->dn);
1067 if (dn == NULL || ndn == NULL) {
1068 ret = LDB_ERR_OTHER;
1072 query = lsqlite3_tprintf(lsql_ac,
1074 "INSERT OR ABORT INTO ldb_entry "
1075 "('dn', 'norm_dn') "
1076 "VALUES ('%q', '%q');",
1078 if (query == NULL) {
1079 ret = LDB_ERR_OTHER;
1083 ret = sqlite3_exec(lsqlite3->sqlite, query, NULL, NULL, &errmsg);
1084 if (ret != SQLITE_OK) {
1086 ldb_set_errstring(module->ldb, errmsg);
1089 ret = LDB_ERR_OTHER;
1093 eid = lsqlite3_get_eid_ndn(lsqlite3->sqlite, lsql_ac, ndn);
1095 ret = LDB_ERR_OTHER;
1099 for (i = 0; i < msg->num_elements; i++) {
1100 const struct ldb_message_element *el = &msg->elements[i];
1101 const struct ldb_schema_attribute *a;
1105 /* Get a case-folded copy of the attribute name */
1106 attr = ldb_attr_casefold(lsql_ac, el->name);
1108 ret = LDB_ERR_OTHER;
1112 a = ldb_schema_attribute_by_name(module->ldb, el->name);
1114 /* For each value of the specified attribute name... */
1115 for (j = 0; j < el->num_values; j++) {
1116 struct ldb_val value;
1119 /* Get a canonicalised copy of the data */
1120 a->syntax->canonicalise_fn(module->ldb, lsql_ac, &(el->values[j]), &value);
1121 if (value.data == NULL) {
1122 ret = LDB_ERR_OTHER;
1126 insert = lsqlite3_tprintf(lsql_ac,
1127 "INSERT OR ROLLBACK INTO ldb_attribute_values "
1128 "('eid', 'attr_name', 'norm_attr_name',"
1129 " 'attr_value', 'norm_attr_value') "
1130 "VALUES ('%lld', '%q', '%q', '%q', '%q');",
1131 eid, el->name, attr,
1132 el->values[j].data, value.data);
1133 if (insert == NULL) {
1134 ret = LDB_ERR_OTHER;
1138 ret = sqlite3_exec(lsqlite3->sqlite, insert, NULL, NULL, &errmsg);
1139 if (ret != SQLITE_OK) {
1141 ldb_set_errstring(module->ldb, errmsg);
1144 ret = LDB_ERR_OTHER;
1150 if (lsql_ac->callback) {
1151 req->handle->status = lsql_ac->callback(module->ldb, lsql_ac->context, NULL);
1155 req->handle->state = LDB_ASYNC_DONE;
1159 /* modify a record */
1160 static int lsql_modify(struct ldb_module *module, struct ldb_request *req)
1162 struct lsqlite3_private *lsqlite3 = talloc_get_type(module->private_data, struct lsqlite3_private);
1163 struct lsql_context *lsql_ac;
1164 struct ldb_message *msg = req->op.mod.message;
1168 int ret = LDB_SUCCESS;
1170 req->handle = init_handle(lsqlite3, module, req);
1171 if (req->handle == NULL) {
1172 return LDB_ERR_OPERATIONS_ERROR;
1174 lsql_ac = talloc_get_type(req->handle->private_data, struct lsql_context);
1175 req->handle->state = LDB_ASYNC_DONE;
1176 req->handle->status = LDB_SUCCESS;
1178 /* See if this is an ltdb special */
1179 if (ldb_dn_is_special(msg->dn)) {
1182 c = ldb_dn_new(lsql_ac, module->ldb, "@SUBCLASSES");
1183 if (ldb_dn_compare(msg->dn, c) == 0) {
1184 #warning "modify subclasses into object class tree"
1185 ret = LDB_ERR_UNWILLING_TO_PERFORM;
1189 /* Others return an error */
1190 ret = LDB_ERR_UNWILLING_TO_PERFORM;
1194 eid = lsqlite3_get_eid(module, msg->dn);
1196 ret = LDB_ERR_OTHER;
1200 for (i = 0; i < msg->num_elements; i++) {
1201 const struct ldb_message_element *el = &msg->elements[i];
1202 const struct ldb_schema_attribute *a;
1203 int flags = el->flags & LDB_FLAG_MOD_MASK;
1208 /* Get a case-folded copy of the attribute name */
1209 attr = ldb_attr_casefold(lsql_ac, el->name);
1211 ret = LDB_ERR_OTHER;
1215 a = ldb_schema_attribute_by_name(module->ldb, el->name);
1219 case LDB_FLAG_MOD_REPLACE:
1221 /* remove all attributes before adding the replacements */
1222 mod = lsqlite3_tprintf(lsql_ac,
1223 "DELETE FROM ldb_attribute_values "
1224 "WHERE eid = '%lld' "
1225 "AND norm_attr_name = '%q';",
1228 ret = LDB_ERR_OTHER;
1232 ret = sqlite3_exec(lsqlite3->sqlite, mod, NULL, NULL, &errmsg);
1233 if (ret != SQLITE_OK) {
1235 ldb_set_errstring(module->ldb, errmsg);
1238 ret = LDB_ERR_OTHER;
1242 /* MISSING break is INTENTIONAL */
1244 case LDB_FLAG_MOD_ADD:
1245 #warning "We should throw an error if no value is provided!"
1246 /* For each value of the specified attribute name... */
1247 for (j = 0; j < el->num_values; j++) {
1248 struct ldb_val value;
1250 /* Get a canonicalised copy of the data */
1251 a->syntax->canonicalise_fn(module->ldb, lsql_ac, &(el->values[j]), &value);
1252 if (value.data == NULL) {
1253 ret = LDB_ERR_OTHER;
1257 mod = lsqlite3_tprintf(lsql_ac,
1258 "INSERT OR ROLLBACK INTO ldb_attribute_values "
1259 "('eid', 'attr_name', 'norm_attr_name',"
1260 " 'attr_value', 'norm_attr_value') "
1261 "VALUES ('%lld', '%q', '%q', '%q', '%q');",
1262 eid, el->name, attr,
1263 el->values[j].data, value.data);
1266 ret = LDB_ERR_OTHER;
1270 ret = sqlite3_exec(lsqlite3->sqlite, mod, NULL, NULL, &errmsg);
1271 if (ret != SQLITE_OK) {
1273 ldb_set_errstring(module->ldb, errmsg);
1276 ret = LDB_ERR_OTHER;
1283 case LDB_FLAG_MOD_DELETE:
1284 #warning "We should throw an error if the attribute we are trying to delete does not exist!"
1285 if (el->num_values == 0) {
1286 mod = lsqlite3_tprintf(lsql_ac,
1287 "DELETE FROM ldb_attribute_values "
1288 "WHERE eid = '%lld' "
1289 "AND norm_attr_name = '%q';",
1292 ret = LDB_ERR_OTHER;
1296 ret = sqlite3_exec(lsqlite3->sqlite, mod, NULL, NULL, &errmsg);
1297 if (ret != SQLITE_OK) {
1299 ldb_set_errstring(module->ldb, errmsg);
1302 ret = LDB_ERR_OTHER;
1307 /* For each value of the specified attribute name... */
1308 for (j = 0; j < el->num_values; j++) {
1309 struct ldb_val value;
1311 /* Get a canonicalised copy of the data */
1312 a->syntax->canonicalise_fn(module->ldb, lsql_ac, &(el->values[j]), &value);
1313 if (value.data == NULL) {
1314 ret = LDB_ERR_OTHER;
1318 mod = lsqlite3_tprintf(lsql_ac,
1319 "DELETE FROM ldb_attribute_values "
1320 "WHERE eid = '%lld' "
1321 "AND norm_attr_name = '%q' "
1322 "AND norm_attr_value = '%q';",
1323 eid, attr, value.data);
1326 ret = LDB_ERR_OTHER;
1330 ret = sqlite3_exec(lsqlite3->sqlite, mod, NULL, NULL, &errmsg);
1331 if (ret != SQLITE_OK) {
1333 ldb_set_errstring(module->ldb, errmsg);
1336 ret = LDB_ERR_OTHER;
1345 if (lsql_ac->callback) {
1346 req->handle->status = lsql_ac->callback(module->ldb, lsql_ac->context, NULL);
1350 req->handle->state = LDB_ASYNC_DONE;
1354 /* delete a record */
1355 static int lsql_delete(struct ldb_module *module, struct ldb_request *req)
1357 struct lsqlite3_private *lsqlite3 = talloc_get_type(module->private_data, struct lsqlite3_private);
1358 struct lsql_context *lsql_ac;
1362 int ret = LDB_SUCCESS;
1365 req->handle = init_handle(lsqlite3, module, req);
1366 if (req->handle == NULL) {
1367 return LDB_ERR_OPERATIONS_ERROR;
1369 lsql_ac = talloc_get_type(req->handle->private_data, struct lsql_context);
1370 req->handle->state = LDB_ASYNC_DONE;
1371 req->handle->status = LDB_SUCCESS;
1373 eid = lsqlite3_get_eid(module, req->op.del.dn);
1378 query = lsqlite3_tprintf(lsql_ac,
1380 "DELETE FROM ldb_entry WHERE eid = %lld; "
1381 /* Delete attributes */
1382 "DELETE FROM ldb_attribute_values WHERE eid = %lld; ",
1384 if (query == NULL) {
1385 ret = LDB_ERR_OTHER;
1389 ret = sqlite3_exec(lsqlite3->sqlite, query, NULL, NULL, &errmsg);
1390 if (ret != SQLITE_OK) {
1392 ldb_set_errstring(module->ldb, errmsg);
1395 req->handle->status = LDB_ERR_OPERATIONS_ERROR;
1399 if (lsql_ac->callback) {
1400 ret = lsql_ac->callback(module->ldb, lsql_ac->context, NULL);
1404 req->handle->state = LDB_ASYNC_DONE;
1408 /* rename a record */
1409 static int lsql_rename(struct ldb_module *module, struct ldb_request *req)
1411 struct lsqlite3_private *lsqlite3 = talloc_get_type(module->private_data, struct lsqlite3_private);
1412 struct lsql_context *lsql_ac;
1413 char *new_dn, *new_cdn, *old_cdn;
1416 int ret = LDB_SUCCESS;
1418 req->handle = init_handle(lsqlite3, module, req);
1419 if (req->handle == NULL) {
1420 return LDB_ERR_OPERATIONS_ERROR;
1422 lsql_ac = talloc_get_type(req->handle->private_data, struct lsql_context);
1423 req->handle->state = LDB_ASYNC_DONE;
1424 req->handle->status = LDB_SUCCESS;
1426 /* create linearized and normalized dns */
1427 old_cdn = ldb_dn_alloc_casefold(lsql_ac, req->op.rename.olddn);
1428 new_cdn = ldb_dn_alloc_casefold(lsql_ac, req->op.rename.newdn);
1429 new_dn = ldb_dn_alloc_linearized(lsql_ac, req->op.rename.newdn);
1430 if (old_cdn == NULL || new_cdn == NULL || new_dn == NULL) {
1434 /* build the SQL query */
1435 query = lsqlite3_tprintf(lsql_ac,
1436 "UPDATE ldb_entry SET dn = '%q', norm_dn = '%q' "
1437 "WHERE norm_dn = '%q';",
1438 new_dn, new_cdn, old_cdn);
1439 if (query == NULL) {
1444 ret = sqlite3_exec(lsqlite3->sqlite, query, NULL, NULL, &errmsg);
1445 if (ret != SQLITE_OK) {
1447 ldb_set_errstring(module->ldb, errmsg);
1450 ret = LDB_ERR_OPERATIONS_ERROR;
1454 if (lsql_ac->callback) {
1455 ret = lsql_ac->callback(module->ldb, lsql_ac->context, NULL);
1459 req->handle->state = LDB_ASYNC_DONE;
1463 static int lsql_start_trans(struct ldb_module * module)
1467 struct lsqlite3_private * lsqlite3 = module->private_data;
1469 if (lsqlite3->trans_count == 0) {
1470 ret = sqlite3_exec(lsqlite3->sqlite, "BEGIN IMMEDIATE;", NULL, NULL, &errmsg);
1471 if (ret != SQLITE_OK) {
1473 printf("lsqlite3_start_trans: error: %s\n", errmsg);
1480 lsqlite3->trans_count++;
1485 static int lsql_end_trans(struct ldb_module *module)
1489 struct lsqlite3_private *lsqlite3 = module->private_data;
1491 if (lsqlite3->trans_count > 0) {
1492 lsqlite3->trans_count--;
1495 if (lsqlite3->trans_count == 0) {
1496 ret = sqlite3_exec(lsqlite3->sqlite, "COMMIT;", NULL, NULL, &errmsg);
1497 if (ret != SQLITE_OK) {
1499 printf("lsqlite3_end_trans: error: %s\n", errmsg);
1509 static int lsql_del_trans(struct ldb_module *module)
1511 struct lsqlite3_private *lsqlite3 = module->private_data;
1513 if (lsqlite3->trans_count > 0) {
1514 lsqlite3->trans_count--;
1517 if (lsqlite3->trans_count == 0) {
1518 return lsqlite3_safe_rollback(lsqlite3->sqlite);
1524 static int destructor(struct lsqlite3_private *lsqlite3)
1526 if (lsqlite3->sqlite) {
1527 sqlite3_close(lsqlite3->sqlite);
1532 static int lsql_request(struct ldb_module *module, struct ldb_request *req)
1534 return LDB_ERR_OPERATIONS_ERROR;
1537 static int lsql_wait(struct ldb_handle *handle, enum ldb_wait_type type)
1539 return handle->status;
1543 * Table of operations for the sqlite3 backend
1545 static const struct ldb_module_ops lsqlite3_ops = {
1547 .search = lsql_search,
1549 .modify = lsql_modify,
1551 .rename = lsql_rename,
1552 .request = lsql_request,
1553 .start_transaction = lsql_start_trans,
1554 .end_transaction = lsql_end_trans,
1555 .del_transaction = lsql_del_trans,
1563 static int initialize(struct lsqlite3_private *lsqlite3,
1564 struct ldb_context *ldb, const char *url, int flags)
1566 TALLOC_CTX *local_ctx;
1573 /* create a local ctx */
1574 local_ctx = talloc_named(lsqlite3, 0, "lsqlite3_rename local context");
1575 if (local_ctx == NULL) {
1579 schema = lsqlite3_tprintf(local_ctx,
1582 "CREATE TABLE ldb_info AS "
1583 " SELECT 'LDB' AS database_type,"
1584 " '1.0' AS version;"
1587 * The entry table holds the information about an entry.
1588 * This table is used to obtain the EID of the entry and to
1589 * support scope=one and scope=base. The parent and child
1590 * table is included in the entry table since all the other
1591 * attributes are dependent on EID.
1593 "CREATE TABLE ldb_entry "
1595 " eid INTEGER PRIMARY KEY AUTOINCREMENT,"
1596 " dn TEXT UNIQUE NOT NULL,"
1597 " norm_dn TEXT UNIQUE NOT NULL"
1601 "CREATE TABLE ldb_object_classes"
1603 " class_name TEXT PRIMARY KEY,"
1604 " parent_class_name TEXT,"
1605 " tree_key TEXT UNIQUE,"
1606 " max_child_num INTEGER DEFAULT 0"
1610 * We keep a full listing of attribute/value pairs here
1612 "CREATE TABLE ldb_attribute_values"
1614 " eid INTEGER REFERENCES ldb_entry,"
1616 " norm_attr_name TEXT,"
1618 " norm_attr_value TEXT "
1625 "CREATE INDEX ldb_attribute_values_eid_idx "
1626 " ON ldb_attribute_values (eid);"
1628 "CREATE INDEX ldb_attribute_values_name_value_idx "
1629 " ON ldb_attribute_values (attr_name, norm_attr_value);"
1637 "CREATE TRIGGER ldb_object_classes_insert_tr"
1639 " ON ldb_object_classes"
1642 " UPDATE ldb_object_classes"
1643 " SET tree_key = COALESCE(tree_key, "
1645 " SELECT tree_key || "
1646 " (SELECT base160(max_child_num + 1)"
1647 " FROM ldb_object_classes"
1648 " WHERE class_name = "
1649 " new.parent_class_name)"
1650 " FROM ldb_object_classes "
1651 " WHERE class_name = new.parent_class_name "
1653 " UPDATE ldb_object_classes "
1654 " SET max_child_num = max_child_num + 1"
1655 " WHERE class_name = new.parent_class_name;"
1659 * Table initialization
1662 "INSERT INTO ldb_object_classes "
1663 " (class_name, tree_key) "
1665 " ('TOP', '0001');");
1667 /* Skip protocol indicator of url */
1668 if (strncmp(url, "sqlite3://", 10) != 0) {
1669 return SQLITE_MISUSE;
1672 /* Update pointer to just after the protocol indicator */
1675 /* Try to open the (possibly empty/non-existent) database */
1676 if ((ret = sqlite3_open(url, &lsqlite3->sqlite)) != SQLITE_OK) {
1680 /* In case this is a new database, enable auto_vacuum */
1681 ret = sqlite3_exec(lsqlite3->sqlite, "PRAGMA auto_vacuum = 1;", NULL, NULL, &errmsg);
1682 if (ret != SQLITE_OK) {
1684 printf("lsqlite3 initializaion error: %s\n", errmsg);
1690 if (flags & LDB_FLG_NOSYNC) {
1692 ret = sqlite3_exec(lsqlite3->sqlite, "PRAGMA synchronous = OFF;", NULL, NULL, &errmsg);
1693 if (ret != SQLITE_OK) {
1695 printf("lsqlite3 initializaion error: %s\n", errmsg);
1704 /* Establish a busy timeout of 30 seconds */
1705 if ((ret = sqlite3_busy_timeout(lsqlite3->sqlite,
1706 30000)) != SQLITE_OK) {
1710 /* Create a function, callable from sql, to increment a tree_key */
1712 sqlite3_create_function(lsqlite3->sqlite,/* handle */
1713 "base160_next", /* function name */
1714 1, /* number of args */
1715 SQLITE_ANY, /* preferred text type */
1716 NULL, /* user data */
1717 base160next_sql, /* called func */
1718 NULL, /* step func */
1719 NULL /* final func */
1724 /* Create a function, callable from sql, to convert int to base160 */
1726 sqlite3_create_function(lsqlite3->sqlite,/* handle */
1727 "base160", /* function name */
1728 1, /* number of args */
1729 SQLITE_ANY, /* preferred text type */
1730 NULL, /* user data */
1731 base160_sql, /* called func */
1732 NULL, /* step func */
1733 NULL /* final func */
1738 /* Create a function, callable from sql, to perform various comparisons */
1740 sqlite3_create_function(lsqlite3->sqlite, /* handle */
1741 "ldap_compare", /* function name */
1742 4, /* number of args */
1743 SQLITE_ANY, /* preferred text type */
1744 ldb , /* user data */
1745 lsqlite3_compare, /* called func */
1746 NULL, /* step func */
1747 NULL /* final func */
1752 /* Begin a transaction */
1753 ret = sqlite3_exec(lsqlite3->sqlite, "BEGIN EXCLUSIVE;", NULL, NULL, &errmsg);
1754 if (ret != SQLITE_OK) {
1756 printf("lsqlite3: initialization error: %s\n", errmsg);
1763 /* Determine if this is a new database. No tables means it is. */
1764 if (query_int(lsqlite3,
1767 " FROM sqlite_master\n"
1768 " WHERE type = 'table';") != 0) {
1772 if (queryInt == 0) {
1774 * Create the database schema
1776 ret = sqlite3_exec(lsqlite3->sqlite, schema, NULL, NULL, &errmsg);
1777 if (ret != SQLITE_OK) {
1779 printf("lsqlite3 initializaion error: %s\n", errmsg);
1786 * Ensure that the database we opened is one of ours
1788 if (query_int(lsqlite3,
1791 " (SELECT COUNT(*) = 2"
1792 " FROM sqlite_master "
1793 " WHERE type = 'table' "
1797 " 'ldb_object_classes' "
1803 " WHERE database_type = 'LDB' "
1804 " AND version = '1.0'"
1808 /* It's not one that we created. See ya! */
1813 /* Commit the transaction */
1814 ret = sqlite3_exec(lsqlite3->sqlite, "COMMIT;", NULL, NULL, &errmsg);
1815 if (ret != SQLITE_OK) {
1817 printf("lsqlite3: iniialization error: %s\n", errmsg);
1826 if (rollback) lsqlite3_safe_rollback(lsqlite3->sqlite);
1827 sqlite3_close(lsqlite3->sqlite);
1832 * connect to the database
1834 static int lsqlite3_connect(struct ldb_context *ldb,
1837 const char *options[],
1838 struct ldb_module **module)
1842 struct lsqlite3_private * lsqlite3 = NULL;
1844 lsqlite3 = talloc(ldb, struct lsqlite3_private);
1849 lsqlite3->sqlite = NULL;
1850 lsqlite3->options = NULL;
1851 lsqlite3->trans_count = 0;
1853 ret = initialize(lsqlite3, ldb, url, flags);
1854 if (ret != SQLITE_OK) {
1858 talloc_set_destructor(lsqlite3, destructor);
1862 *module = talloc(ldb, struct ldb_module);
1867 talloc_set_name_const(*module, "ldb_sqlite3 backend");
1868 (*module)->ldb = ldb;
1869 (*module)->prev = (*module)->next = NULL;
1870 (*module)->private_data = lsqlite3;
1871 (*module)->ops = &lsqlite3_ops;
1875 * take a copy of the options array, so we don't have to rely
1876 * on the caller keeping it around (it might be dynamic)
1878 for (i=0;options[i];i++) ;
1880 lsqlite3->options = talloc_array(lsqlite3, char *, i+1);
1881 if (!lsqlite3->options) {
1885 for (i=0;options[i];i++) {
1887 lsqlite3->options[i+1] = NULL;
1888 lsqlite3->options[i] =
1889 talloc_strdup(lsqlite3->options, options[i]);
1890 if (!lsqlite3->options[i]) {
1899 if (lsqlite3->sqlite != NULL) {
1900 (void) sqlite3_close(lsqlite3->sqlite);
1902 talloc_free(lsqlite3);
1906 const struct ldb_backend_ops ldb_sqlite3_backend_ops = {
1908 .connect_fn = lsqlite3_connect