4 Copyright (C) Derrell Lipman 2005
5 Copyright (C) Simo Sorce 2005
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 2 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, write to the Free Software
23 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
29 * Component: ldb sqlite3 backend
31 * Description: core files for SQLITE3 backend
33 * Author: Derrell Lipman (based on Andrew Tridgell's LDAP backend)
37 #include "ldb/include/includes.h"
39 #include "ldb/ldb_sqlite3/ldb_sqlite3.h"
42 * Macros used throughout
47 # define TRUE (! FALSE)
50 #define RESULT_ATTR_TABLE "temp_result_attrs"
52 //#define TEMPTAB /* for testing, create non-temporary table */
53 #define TEMPTAB "TEMPORARY"
58 sqlite3_stmt * stmtGetEID = NULL;
60 static char *lsqlite3_tprintf(TALLOC_CTX *mem_ctx, const char *fmt, ...)
66 str = sqlite3_vmprintf(fmt, ap);
69 if (str == NULL) return NULL;
71 ret = talloc_strdup(mem_ctx, str);
81 static unsigned char base160tab[161] = {
82 48 ,49 ,50 ,51 ,52 ,53 ,54 ,55 ,56 ,57 , /* 0-9 */
83 58 ,59 ,65 ,66 ,67 ,68 ,69 ,70 ,71 ,72 , /* : ; A-H */
84 73 ,74 ,75 ,76 ,77 ,78 ,79 ,80 ,81 ,82 , /* I-R */
85 83 ,84 ,85 ,86 ,87 ,88 ,89 ,90 ,97 ,98 , /* S-Z , a-b */
86 99 ,100,101,102,103,104,105,106,107,108, /* c-l */
87 109,110,111,112,113,114,115,116,117,118, /* m-v */
88 119,120,121,122,160,161,162,163,164,165, /* w-z, latin1 */
89 166,167,168,169,170,171,172,173,174,175, /* latin1 */
90 176,177,178,179,180,181,182,183,184,185, /* latin1 */
91 186,187,188,189,190,191,192,193,194,195, /* latin1 */
92 196,197,198,199,200,201,202,203,204,205, /* latin1 */
93 206,207,208,209,210,211,212,213,214,215, /* latin1 */
94 216,217,218,219,220,221,222,223,224,225, /* latin1 */
95 226,227,228,229,230,231,232,233,234,235, /* latin1 */
96 236,237,238,239,240,241,242,243,244,245, /* latin1 */
97 246,247,248,249,250,251,252,253,254,255, /* latin1 */
105 * Convert an unsigned long integer into a base160 representation of the
110 * value to be converted
113 * character array, 5 bytes long, into which the base160 representation
114 * will be placed. The result will be a four-digit representation of the
115 * number (with leading zeros prepended as necessary), and null
122 base160_sql(sqlite3_context * hContext,
124 sqlite3_value ** argv)
130 val = sqlite3_value_int64(argv[0]);
132 for (i = 3; i >= 0; i--) {
134 result[i] = base160tab[val % 160];
140 sqlite3_result_text(hContext, result, -1, SQLITE_TRANSIENT);
147 * This function enhances sqlite by adding a "base160_next()" function which is
148 * accessible via queries.
150 * Retrieve the next-greater number in the base160 sequence for the terminal
151 * tree node (the last four digits). Only one tree level (four digits) is
155 * A character string: either an empty string (in which case no operation is
156 * performed), or a string of base160 digits with a length of a multiple of
160 * Upon return, the trailing four digits (one tree level) will have been
164 base160next_sql(sqlite3_context * hContext,
166 sqlite3_value ** argv)
170 unsigned char * pTab;
171 unsigned char * pBase160 =
172 strdup(sqlite3_value_text(argv[0]));
173 unsigned char * pStart = pBase160;
176 * We need a minimum of four digits, and we will always get a multiple
179 if (pBase160 != NULL &&
180 (len = strlen(pBase160)) >= 4 &&
183 if (pBase160 == NULL) {
185 sqlite3_result_null(hContext);
189 pBase160 += strlen(pBase160) - 1;
191 /* We only carry through four digits: one level in the tree */
192 for (i = 0; i < 4; i++) {
194 /* What base160 value does this digit have? */
195 pTab = strchr(base160tab, *pBase160);
197 /* Is there a carry? */
198 if (pTab < base160tab + sizeof(base160tab) - 1) {
201 * Nope. Just increment this value and we're
209 * There's a carry. This value gets
210 * base160tab[0], we decrement the buffer
211 * pointer to get the next higher-order digit,
212 * and continue in the loop.
214 *pBase160-- = base160tab[0];
218 sqlite3_result_text(hContext,
223 sqlite3_result_value(hContext, argv[0]);
224 if (pBase160 != NULL) {
230 static char *parsetree_to_sql(struct ldb_module *module,
232 const struct ldb_parse_tree *t)
234 const struct ldb_attrib_handler *h;
235 struct ldb_val value, subval;
236 char *wild_card_string;
243 switch(t->operation) {
246 tmp = parsetree_to_sql(module, mem_ctx, t->u.list.elements[0]);
247 if (tmp == NULL) return NULL;
249 for (i = 1; i < t->u.list.num_elements; i++) {
251 child = parsetree_to_sql(module, mem_ctx, t->u.list.elements[i]);
252 if (child == NULL) return NULL;
254 tmp = talloc_asprintf_append(tmp, " INTERSECT %s ", child);
255 if (tmp == NULL) return NULL;
258 ret = talloc_asprintf(mem_ctx, "SELECT * FROM ( %s )\n", tmp);
264 tmp = parsetree_to_sql(module, mem_ctx, t->u.list.elements[0]);
265 if (tmp == NULL) return NULL;
267 for (i = 1; i < t->u.list.num_elements; i++) {
269 child = parsetree_to_sql(module, mem_ctx, t->u.list.elements[i]);
270 if (child == NULL) return NULL;
272 tmp = talloc_asprintf_append(tmp, " UNION %s ", child);
273 if (tmp == NULL) return NULL;
276 return talloc_asprintf(mem_ctx, "SELECT * FROM ( %s ) ", tmp);
280 child = parsetree_to_sql(module, mem_ctx, t->u.isnot.child);
281 if (child == NULL) return NULL;
283 return talloc_asprintf(mem_ctx,
284 "SELECT eid FROM ldb_entry "
285 "WHERE eid NOT IN ( %s ) ", child);
287 case LDB_OP_EQUALITY:
289 * For simple searches, we want to retrieve the list of EIDs that
290 * match the criteria.
292 attr = ldb_casefold(module->ldb, mem_ctx, t->u.equality.attr);
293 if (attr == NULL) return NULL;
294 h = ldb_attrib_handler(module->ldb, attr);
296 /* Get a canonicalised copy of the data */
297 h->canonicalise_fn(module->ldb, mem_ctx, &(t->u.equality.value), &value);
298 if (value.data == NULL) {
302 if (strcasecmp(t->u.equality.attr, "objectclass") == 0) {
304 * For object classes, we want to search for all objectclasses
305 * that are subclasses as well.
307 return lsqlite3_tprintf(mem_ctx,
308 "SELECT eid FROM ldb_attribute_values\n"
309 "WHERE norm_attr_name = 'OBJECTCLASS' "
310 "AND norm_attr_value IN\n"
311 " (SELECT class_name FROM ldb_object_classes\n"
312 " WHERE tree_key GLOB\n"
313 " (SELECT tree_key FROM ldb_object_classes\n"
314 " WHERE class_name = '%q'\n"
318 } else if (strcasecmp(t->u.equality.attr, "dn") == 0) {
319 /* DN query is a special ldb case */
320 char *cdn = ldb_dn_linearize_casefold(module->ldb,
321 ldb_dn_explode(module->ldb,
324 return lsqlite3_tprintf(mem_ctx,
325 "SELECT eid FROM ldb_entry "
326 "WHERE norm_dn = '%q'", cdn);
329 /* A normal query. */
330 return lsqlite3_tprintf(mem_ctx,
331 "SELECT eid FROM ldb_attribute_values "
332 "WHERE norm_attr_name = '%q' "
333 "AND norm_attr_value = '%q'",
339 case LDB_OP_SUBSTRING:
341 wild_card_string = talloc_strdup(mem_ctx,
342 (t->u.substring.start_with_wildcard)?"*":"");
343 if (wild_card_string == NULL) return NULL;
345 for (i = 0; t->u.substring.chunks[i]; i++) {
346 wild_card_string = talloc_asprintf_append(wild_card_string, "%s*",
347 t->u.substring.chunks[i]->data);
348 if (wild_card_string == NULL) return NULL;
351 if ( ! t->u.substring.end_with_wildcard ) {
352 /* remove last wildcard */
353 wild_card_string[strlen(wild_card_string) - 1] = '\0';
356 attr = ldb_casefold(module->ldb, mem_ctx, t->u.substring.attr);
357 if (attr == NULL) return NULL;
358 h = ldb_attrib_handler(module->ldb, attr);
360 subval.data = wild_card_string;
361 subval.length = strlen(wild_card_string) + 1;
363 /* Get a canonicalised copy of the data */
364 h->canonicalise_fn(module->ldb, mem_ctx, &(subval), &value);
365 if (value.data == NULL) {
369 return lsqlite3_tprintf(mem_ctx,
370 "SELECT eid FROM ldb_attribute_values "
371 "WHERE norm_attr_name = '%q' "
372 "AND norm_attr_value GLOB '%q'",
377 attr = ldb_casefold(module->ldb, mem_ctx, t->u.equality.attr);
378 if (attr == NULL) return NULL;
379 h = ldb_attrib_handler(module->ldb, attr);
381 /* Get a canonicalised copy of the data */
382 h->canonicalise_fn(module->ldb, mem_ctx, &(t->u.equality.value), &value);
383 if (value.data == NULL) {
387 return lsqlite3_tprintf(mem_ctx,
388 "SELECT eid FROM ldb_attribute_values "
389 "WHERE norm_attr_name = '%q' "
390 "AND ldap_compare(norm_attr_value, '>=', '%q', '%q') ",
396 attr = ldb_casefold(module->ldb, mem_ctx, t->u.equality.attr);
397 if (attr == NULL) return NULL;
398 h = ldb_attrib_handler(module->ldb, attr);
400 /* Get a canonicalised copy of the data */
401 h->canonicalise_fn(module->ldb, mem_ctx, &(t->u.equality.value), &value);
402 if (value.data == NULL) {
406 return lsqlite3_tprintf(mem_ctx,
407 "SELECT eid FROM ldb_attribute_values "
408 "WHERE norm_attr_name = '%q' "
409 "AND ldap_compare(norm_attr_value, '<=', '%q', '%q') ",
415 if (strcasecmp(t->u.present.attr, "dn") == 0) {
416 return talloc_strdup(mem_ctx, "SELECT eid FROM ldb_entry");
419 attr = ldb_casefold(module->ldb, mem_ctx, t->u.present.attr);
420 if (attr == NULL) return NULL;
422 return lsqlite3_tprintf(mem_ctx,
423 "SELECT eid FROM ldb_attribute_values "
424 "WHERE norm_attr_name = '%q' ",
428 attr = ldb_casefold(module->ldb, mem_ctx, t->u.equality.attr);
429 if (attr == NULL) return NULL;
430 h = ldb_attrib_handler(module->ldb, attr);
432 /* Get a canonicalised copy of the data */
433 h->canonicalise_fn(module->ldb, mem_ctx, &(t->u.equality.value), &value);
434 if (value.data == NULL) {
438 return lsqlite3_tprintf(mem_ctx,
439 "SELECT eid FROM ldb_attribute_values "
440 "WHERE norm_attr_name = '%q' "
441 "AND ldap_compare(norm_attr_value, '~%', 'q', '%q') ",
446 case LDB_OP_EXTENDED:
447 #warning "work out how to handle bitops"
454 /* should never occur */
462 * This function is used for the common case of queries that return a single
465 * NOTE: If more than one value is returned by the query, all but the first
466 * one will be ignored.
469 query_int(const struct lsqlite3_private * lsqlite3,
477 sqlite3_stmt * pStmt;
480 /* Begin access to variable argument list */
481 va_start(args, pSql);
483 /* Format the query */
484 if ((p = sqlite3_vmprintf(pSql, args)) == NULL) {
489 * Prepare and execute the SQL statement. Loop allows retrying on
490 * certain errors, e.g. SQLITE_SCHEMA occurs if the schema changes,
491 * requiring retrying the operation.
493 for (bLoop = TRUE; bLoop; ) {
495 /* Compile the SQL statement into sqlite virtual machine */
496 if ((ret = sqlite3_prepare(lsqlite3->sqlite,
500 NULL)) == SQLITE_SCHEMA) {
501 if (stmtGetEID != NULL) {
502 sqlite3_finalize(stmtGetEID);
506 } else if (ret != SQLITE_OK) {
510 /* One row expected */
511 if ((ret = sqlite3_step(pStmt)) == SQLITE_SCHEMA) {
512 if (stmtGetEID != NULL) {
513 sqlite3_finalize(stmtGetEID);
516 (void) sqlite3_finalize(pStmt);
518 } else if (ret != SQLITE_ROW) {
519 (void) sqlite3_finalize(pStmt);
523 /* Get the value to be returned */
524 *pRet = sqlite3_column_int64(pStmt, 0);
526 /* Free the virtual machine */
527 if ((ret = sqlite3_finalize(pStmt)) == SQLITE_SCHEMA) {
528 if (stmtGetEID != NULL) {
529 sqlite3_finalize(stmtGetEID);
533 } else if (ret != SQLITE_OK) {
534 (void) sqlite3_finalize(pStmt);
539 * Normal condition is only one time through loop. Loop is
540 * rerun in error conditions, via "continue", above.
545 /* All done with variable argument list */
549 /* Free the memory we allocated for our query string */
556 * This is a bad hack to support ldap style comparisons whithin sqlite.
557 * val is the attribute in the row currently under test
558 * func is the desired test "<=" ">=" "~" ":"
559 * cmp is the value to compare against (eg: "test")
560 * attr is the attribute name the value of which we want to test
563 static void lsqlite3_compare(sqlite3_context *ctx, int argc,
564 sqlite3_value **argv)
566 struct ldb_context *ldb = (struct ldb_context *)sqlite3_user_data(ctx);
567 const unsigned char *val = sqlite3_value_text(argv[0]);
568 const unsigned char *func = sqlite3_value_text(argv[1]);
569 const unsigned char *cmp = sqlite3_value_text(argv[2]);
570 const unsigned char *attr = sqlite3_value_text(argv[3]);
571 const struct ldb_attrib_handler *h;
579 h = ldb_attrib_handler(ldb, attr);
581 valX.length = strlen(cmp);
583 valY.length = strlen(val);
584 ret = h->comparison_fn(ldb, ldb, &valY, &valX);
586 sqlite3_result_int(ctx, 1);
588 sqlite3_result_int(ctx, 0);
593 h = ldb_attrib_handler(ldb, attr);
595 valX.length = strlen(cmp);
597 valY.length = strlen(val);
598 ret = h->comparison_fn(ldb, ldb, &valY, &valX);
600 sqlite3_result_int(ctx, 1);
602 sqlite3_result_int(ctx, 0);
608 sqlite3_result_int(ctx, 0);
614 sqlite3_result_int(ctx, 0);
621 sqlite3_result_error(ctx, "Value must start with a special operation char (<>~:)!", -1);
626 /* rename a record */
627 static int lsqlite3_safe_rollback(sqlite3 *sqlite)
633 ret = sqlite3_exec(sqlite, "ROLLBACK;", NULL, NULL, &errmsg);
634 if (ret != SQLITE_OK) {
636 printf("lsqlite3_safe_rollback: Error: %s\n", errmsg);
645 /* return an eid as result */
646 static int lsqlite3_eid_callback(void *result, int col_num, char **cols, char **names)
648 long long *eid = (long long *)result;
650 if (col_num != 1) return SQLITE_ABORT;
651 if (strcasecmp(names[0], "eid") != 0) return SQLITE_ABORT;
653 *eid = atoll(cols[0]);
657 struct lsqlite3_msgs {
659 struct ldb_message **msgs;
660 long long current_eid;
661 const char * const * attrs;
666 * add a single set of ldap message values to a ldb_message
669 static int lsqlite3_search_callback(void *result, int col_num, char **cols, char **names)
671 struct lsqlite3_msgs *msgs = (struct lsqlite3_msgs *)result;
672 struct ldb_message *msg;
676 /* eid, dn, attr_name, attr_value */
677 if (col_num != 4) return SQLITE_ABORT;
679 eid = atoll(cols[0]);
681 if (eid != msgs->current_eid) {
682 msgs->msgs = talloc_realloc(msgs->mem_ctx,
684 struct ldb_message *,
686 if (msgs->msgs == NULL) return SQLITE_ABORT;
688 msgs->msgs[msgs->count] = talloc(msgs->msgs, struct ldb_message);
689 if (msgs->msgs[msgs->count] == NULL) return SQLITE_ABORT;
691 msgs->msgs[msgs->count]->dn = NULL;
692 msgs->msgs[msgs->count]->num_elements = 0;
693 msgs->msgs[msgs->count]->elements = NULL;
694 msgs->msgs[msgs->count]->private_data = NULL;
697 msgs->current_eid = eid;
700 msg = msgs->msgs[msgs->count -1];
702 if (msg->dn == NULL) {
703 msg->dn = ldb_dn_explode(msg, cols[1]);
704 if (msg->dn == NULL) return SQLITE_ABORT;
709 for (i = 0; msgs->attrs[i]; i++) {
710 if (strcasecmp(cols[2], msgs->attrs[i]) == 0) {
715 if (!found) return 0;
718 if (ldb_msg_add_string(msg, cols[2], cols[3]) != 0)
727 * lsqlite3_get_eid_ndn()
729 * These functions are used for the very common case of retrieving an EID value
730 * given a (normalized) DN.
733 static long long lsqlite3_get_eid_ndn(sqlite3 *sqlite, void *mem_ctx, const char *norm_dn)
741 query = lsqlite3_tprintf(mem_ctx, "SELECT eid "
743 "WHERE norm_dn = '%q';", norm_dn);
744 if (query == NULL) return -1;
746 ret = sqlite3_exec(sqlite, query, lsqlite3_eid_callback, &eid, &errmsg);
747 if (ret != SQLITE_OK) {
749 printf("lsqlite3_get_eid: Fatal Error: %s\n", errmsg);
758 static long long lsqlite3_get_eid(struct ldb_module *module, const struct ldb_dn *dn)
760 TALLOC_CTX *local_ctx;
761 struct lsqlite3_private *lsqlite3 = module->private_data;
765 /* ignore ltdb specials */
766 if (ldb_dn_is_special(dn)) {
770 /* create a local ctx */
771 local_ctx = talloc_named(lsqlite3, 0, "lsqlite3_get_eid local context");
772 if (local_ctx == NULL) {
776 cdn = ldb_dn_linearize(local_ctx, ldb_dn_casefold(module->ldb, dn));
779 eid = lsqlite3_get_eid_ndn(lsqlite3->sqlite, local_ctx, cdn);
782 talloc_free(local_ctx);
787 * Interface functions referenced by lsqlite3_ops
790 /* search for matching records, by tree */
791 static int lsqlite3_search_bytree(struct ldb_module * module, const struct ldb_dn* basedn,
792 enum ldb_scope scope, struct ldb_parse_tree * tree,
793 const char * const * attrs, struct ldb_result ** res)
795 TALLOC_CTX *local_ctx;
796 struct lsqlite3_private *lsqlite3 = module->private_data;
797 struct lsqlite3_msgs msgs;
804 /* create a local ctx */
805 local_ctx = talloc_named(lsqlite3, 0, "lsqlite3_search_bytree local context");
806 if (local_ctx == NULL) {
811 norm_basedn = ldb_dn_linearize(local_ctx, ldb_dn_casefold(module->ldb, basedn));
812 if (norm_basedn == NULL) {
813 ret = LDB_ERR_INVALID_DN_SYNTAX;
816 } else norm_basedn = talloc_strdup(local_ctx, "");
818 if (*norm_basedn == '\0' &&
819 (scope == LDB_SCOPE_BASE || scope == LDB_SCOPE_ONELEVEL)) {
820 ret = LDB_ERR_UNWILLING_TO_PERFORM;
824 /* Convert filter into a series of SQL conditions (constraints) */
825 sqlfilter = parsetree_to_sql(module, local_ctx, tree);
828 case LDB_SCOPE_DEFAULT:
829 case LDB_SCOPE_SUBTREE:
830 if (*norm_basedn != '\0') {
831 query = lsqlite3_tprintf(local_ctx,
832 "SELECT entry.eid,\n"
836 " FROM ldb_entry AS entry\n"
838 " LEFT OUTER JOIN ldb_attribute_values AS av\n"
839 " ON av.eid = entry.eid\n"
841 " WHERE entry.eid IN\n"
842 " (SELECT DISTINCT ldb_entry.eid\n"
844 " WHERE (ldb_entry.norm_dn GLOB('*,%q')\n"
845 " OR ldb_entry.norm_dn = '%q')\n"
846 " AND ldb_entry.eid IN\n"
850 " ORDER BY entry.eid ASC;",
855 query = lsqlite3_tprintf(local_ctx,
856 "SELECT entry.eid,\n"
860 " FROM ldb_entry AS entry\n"
862 " LEFT OUTER JOIN ldb_attribute_values AS av\n"
863 " ON av.eid = entry.eid\n"
865 " WHERE entry.eid IN\n"
866 " (SELECT DISTINCT ldb_entry.eid\n"
868 " WHERE ldb_entry.eid IN\n"
872 " ORDER BY entry.eid ASC;",
879 query = lsqlite3_tprintf(local_ctx,
880 "SELECT entry.eid,\n"
884 " FROM ldb_entry AS entry\n"
886 " LEFT OUTER JOIN ldb_attribute_values AS av\n"
887 " ON av.eid = entry.eid\n"
889 " WHERE entry.eid IN\n"
890 " (SELECT DISTINCT ldb_entry.eid\n"
892 " WHERE ldb_entry.norm_dn = '%q'\n"
893 " AND ldb_entry.eid IN\n"
897 " ORDER BY entry.eid ASC;",
902 case LDB_SCOPE_ONELEVEL:
903 query = lsqlite3_tprintf(local_ctx,
904 "SELECT entry.eid,\n"
908 " FROM ldb_entry AS entry\n"
910 " LEFT OUTER JOIN ldb_attribute_values AS av\n"
911 " ON av.eid = entry.eid\n"
913 " WHERE entry.eid IN\n"
914 " (SELECT DISTINCT ldb_entry.eid\n"
916 " WHERE norm_dn GLOB('*,%q')\n"
917 " AND NOT norm_dn GLOB('*,*,%q')\n"
918 " AND ldb_entry.eid IN\n(%s)\n"
921 " ORDER BY entry.eid ASC;",
934 printf ("%s\n", query);
939 msgs.current_eid = 0;
940 msgs.mem_ctx = local_ctx;
943 ret = sqlite3_exec(lsqlite3->sqlite, query, lsqlite3_search_callback, &msgs, &errmsg);
944 if (ret != SQLITE_OK) {
946 ldb_set_errstring(module, talloc_strdup(module, errmsg));
953 for (i = 0; i < msgs.count; i++) {
954 msgs.msgs[i] = ldb_msg_canonicalize(module->ldb, msgs.msgs[i]);
955 if (msgs.msgs[i] == NULL) {
960 *res = talloc(module, struct ldb_result);
965 (*res)->msgs = talloc_steal(*res, msgs.msgs);
966 (*res)->count = msgs.count;
967 (*res)->controls = NULL;
969 talloc_free(local_ctx);
972 /* If error, return error code; otherwise return number of results */
974 talloc_free(local_ctx);
975 return LDB_ERR_OTHER;
980 static int lsqlite3_add(struct ldb_module *module, const struct ldb_message *msg)
982 TALLOC_CTX *local_ctx;
983 struct lsqlite3_private *lsqlite3 = module->private_data;
991 /* create a local ctx */
992 local_ctx = talloc_named(lsqlite3, 0, "lsqlite3_add local context");
993 if (local_ctx == NULL) {
994 return LDB_ERR_OTHER;
997 /* See if this is an ltdb special */
998 if (ldb_dn_is_special(msg->dn)) {
1001 c = ldb_dn_explode(local_ctx, "@SUBCLASSES");
1002 if (ldb_dn_compare(module->ldb, msg->dn, c) == 0) {
1003 #warning "insert subclasses into object class tree"
1004 ret = LDB_ERR_UNWILLING_TO_PERFORM;
1009 c = ldb_dn_explode(local_ctx, "@INDEXLIST");
1010 if (ldb_dn_compare(module->ldb, msg->dn, c) == 0) {
1011 #warning "should we handle indexes somehow ?"
1015 /* Others are implicitly ignored */
1019 /* create linearized and normalized dns */
1020 dn = ldb_dn_linearize(local_ctx, msg->dn);
1021 ndn = ldb_dn_linearize(local_ctx, ldb_dn_casefold(module->ldb, msg->dn));
1022 if (dn == NULL || ndn == NULL) {
1023 ret = LDB_ERR_OTHER;
1027 query = lsqlite3_tprintf(local_ctx,
1029 "INSERT OR ABORT INTO ldb_entry "
1030 "('dn', 'norm_dn') "
1031 "VALUES ('%q', '%q');",
1033 if (query == NULL) {
1034 ret = LDB_ERR_OTHER;
1038 ret = sqlite3_exec(lsqlite3->sqlite, query, NULL, NULL, &errmsg);
1039 if (ret != SQLITE_OK) {
1041 ldb_set_errstring(module, talloc_strdup(module, errmsg));
1044 ret = LDB_ERR_OTHER;
1048 eid = lsqlite3_get_eid_ndn(lsqlite3->sqlite, local_ctx, ndn);
1050 ret = LDB_ERR_OTHER;
1054 for (i = 0; i < msg->num_elements; i++) {
1055 const struct ldb_message_element *el = &msg->elements[i];
1056 const struct ldb_attrib_handler *h;
1060 /* Get a case-folded copy of the attribute name */
1061 attr = ldb_casefold(module->ldb, local_ctx, el->name);
1063 ret = LDB_ERR_OTHER;
1067 h = ldb_attrib_handler(module->ldb, el->name);
1069 /* For each value of the specified attribute name... */
1070 for (j = 0; j < el->num_values; j++) {
1071 struct ldb_val value;
1074 /* Get a canonicalised copy of the data */
1075 h->canonicalise_fn(module->ldb, local_ctx, &(el->values[j]), &value);
1076 if (value.data == NULL) {
1077 ret = LDB_ERR_OTHER;
1081 insert = lsqlite3_tprintf(local_ctx,
1082 "INSERT OR ROLLBACK INTO ldb_attribute_values "
1083 "('eid', 'attr_name', 'norm_attr_name',"
1084 " 'attr_value', 'norm_attr_value') "
1085 "VALUES ('%lld', '%q', '%q', '%q', '%q');",
1086 eid, el->name, attr,
1087 el->values[j].data, value.data);
1088 if (insert == NULL) {
1089 ret = LDB_ERR_OTHER;
1093 ret = sqlite3_exec(lsqlite3->sqlite, insert, NULL, NULL, &errmsg);
1094 if (ret != SQLITE_OK) {
1096 ldb_set_errstring(module, talloc_strdup(module, errmsg));
1099 ret = LDB_ERR_OTHER;
1105 talloc_free(local_ctx);
1109 talloc_free(local_ctx);
1114 /* modify a record */
1115 static int lsqlite3_modify(struct ldb_module *module, const struct ldb_message *msg)
1117 TALLOC_CTX *local_ctx;
1118 struct lsqlite3_private *lsqlite3 = module->private_data;
1124 /* create a local ctx */
1125 local_ctx = talloc_named(lsqlite3, 0, "lsqlite3_modify local context");
1126 if (local_ctx == NULL) {
1127 return LDB_ERR_OTHER;
1130 /* See if this is an ltdb special */
1131 if (ldb_dn_is_special(msg->dn)) {
1134 c = ldb_dn_explode(local_ctx, "@SUBCLASSES");
1135 if (ldb_dn_compare(module->ldb, msg->dn, c) == 0) {
1136 #warning "modify subclasses into object class tree"
1137 ret = LDB_ERR_UNWILLING_TO_PERFORM;
1141 /* Others are implicitly ignored */
1145 eid = lsqlite3_get_eid(module, msg->dn);
1147 ret = LDB_ERR_OTHER;
1151 for (i = 0; i < msg->num_elements; i++) {
1152 const struct ldb_message_element *el = &msg->elements[i];
1153 const struct ldb_attrib_handler *h;
1154 int flags = el->flags & LDB_FLAG_MOD_MASK;
1159 /* Get a case-folded copy of the attribute name */
1160 attr = ldb_casefold(module->ldb, local_ctx, el->name);
1162 ret = LDB_ERR_OTHER;
1166 h = ldb_attrib_handler(module->ldb, el->name);
1170 case LDB_FLAG_MOD_REPLACE:
1172 /* remove all attributes before adding the replacements */
1173 mod = lsqlite3_tprintf(local_ctx,
1174 "DELETE FROM ldb_attribute_values "
1175 "WHERE eid = '%lld' "
1176 "AND norm_attr_name = '%q';",
1179 ret = LDB_ERR_OTHER;
1183 ret = sqlite3_exec(lsqlite3->sqlite, mod, NULL, NULL, &errmsg);
1184 if (ret != SQLITE_OK) {
1186 ldb_set_errstring(module, talloc_strdup(module, errmsg));
1189 ret = LDB_ERR_OTHER;
1193 /* MISSING break is INTENTIONAL */
1195 case LDB_FLAG_MOD_ADD:
1196 #warning "We should throw an error if no value is provided!"
1197 /* For each value of the specified attribute name... */
1198 for (j = 0; j < el->num_values; j++) {
1199 struct ldb_val value;
1201 /* Get a canonicalised copy of the data */
1202 h->canonicalise_fn(module->ldb, local_ctx, &(el->values[j]), &value);
1203 if (value.data == NULL) {
1204 ret = LDB_ERR_OTHER;
1208 mod = lsqlite3_tprintf(local_ctx,
1209 "INSERT OR ROLLBACK INTO ldb_attribute_values "
1210 "('eid', 'attr_name', 'norm_attr_name',"
1211 " 'attr_value', 'norm_attr_value') "
1212 "VALUES ('%lld', '%q', '%q', '%q', '%q');",
1213 eid, el->name, attr,
1214 el->values[j].data, value.data);
1217 ret = LDB_ERR_OTHER;
1221 ret = sqlite3_exec(lsqlite3->sqlite, mod, NULL, NULL, &errmsg);
1222 if (ret != SQLITE_OK) {
1224 ldb_set_errstring(module, talloc_strdup(module, errmsg));
1227 ret = LDB_ERR_OTHER;
1234 case LDB_FLAG_MOD_DELETE:
1235 #warning "We should throw an error if the attribute we are trying to delete does not exist!"
1236 if (el->num_values == 0) {
1237 mod = lsqlite3_tprintf(local_ctx,
1238 "DELETE FROM ldb_attribute_values "
1239 "WHERE eid = '%lld' "
1240 "AND norm_attr_name = '%q';",
1243 ret = LDB_ERR_OTHER;
1247 ret = sqlite3_exec(lsqlite3->sqlite, mod, NULL, NULL, &errmsg);
1248 if (ret != SQLITE_OK) {
1250 ldb_set_errstring(module, talloc_strdup(module, errmsg));
1253 ret = LDB_ERR_OTHER;
1258 /* For each value of the specified attribute name... */
1259 for (j = 0; j < el->num_values; j++) {
1260 struct ldb_val value;
1262 /* Get a canonicalised copy of the data */
1263 h->canonicalise_fn(module->ldb, local_ctx, &(el->values[j]), &value);
1264 if (value.data == NULL) {
1265 ret = LDB_ERR_OTHER;
1269 mod = lsqlite3_tprintf(local_ctx,
1270 "DELETE FROM ldb_attribute_values "
1271 "WHERE eid = '%lld' "
1272 "AND norm_attr_name = '%q' "
1273 "AND norm_attr_value = '%q';",
1274 eid, attr, value.data);
1277 ret = LDB_ERR_OTHER;
1281 ret = sqlite3_exec(lsqlite3->sqlite, mod, NULL, NULL, &errmsg);
1282 if (ret != SQLITE_OK) {
1284 ldb_set_errstring(module, talloc_strdup(module, errmsg));
1287 ret = LDB_ERR_OTHER;
1296 talloc_free(local_ctx);
1300 talloc_free(local_ctx);
1304 /* delete a record */
1305 static int lsqlite3_delete(struct ldb_module *module, const struct ldb_dn *dn)
1307 TALLOC_CTX *local_ctx;
1308 struct lsqlite3_private *lsqlite3 = module->private_data;
1314 /* ignore ltdb specials */
1315 if (ldb_dn_is_special(dn)) {
1319 /* create a local ctx */
1320 local_ctx = talloc_named(lsqlite3, 0, "lsqlite3_delete local context");
1321 if (local_ctx == NULL) {
1322 return LDB_ERR_OTHER;
1325 eid = lsqlite3_get_eid(module, dn);
1327 ret = LDB_ERR_OTHER;
1331 query = lsqlite3_tprintf(local_ctx,
1333 "DELETE FROM ldb_entry WHERE eid = %lld; "
1334 /* Delete attributes */
1335 "DELETE FROM ldb_attribute_values WHERE eid = %lld; ",
1337 if (query == NULL) {
1338 ret = LDB_ERR_OTHER;
1342 ret = sqlite3_exec(lsqlite3->sqlite, query, NULL, NULL, &errmsg);
1343 if (ret != SQLITE_OK) {
1345 ldb_set_errstring(module, talloc_strdup(module, errmsg));
1348 ret = LDB_ERR_OTHER;
1352 talloc_free(local_ctx);
1356 talloc_free(local_ctx);
1360 /* rename a record */
1361 static int lsqlite3_rename(struct ldb_module *module, const struct ldb_dn *olddn, const struct ldb_dn *newdn)
1363 TALLOC_CTX *local_ctx;
1364 struct lsqlite3_private *lsqlite3 = module->private_data;
1365 char *new_dn, *new_cdn, *old_cdn;
1370 /* ignore ltdb specials */
1371 if (ldb_dn_is_special(olddn) || ldb_dn_is_special(newdn)) {
1375 /* create a local ctx */
1376 local_ctx = talloc_named(lsqlite3, 0, "lsqlite3_rename local context");
1377 if (local_ctx == NULL) {
1378 return LDB_ERR_OTHER;
1381 /* create linearized and normalized dns */
1382 old_cdn = ldb_dn_linearize(local_ctx, ldb_dn_casefold(module->ldb, olddn));
1383 new_cdn = ldb_dn_linearize(local_ctx, ldb_dn_casefold(module->ldb, newdn));
1384 new_dn = ldb_dn_linearize(local_ctx, newdn);
1385 if (old_cdn == NULL || new_cdn == NULL || new_dn == NULL) {
1386 ret = LDB_ERR_OTHER;
1390 /* build the SQL query */
1391 query = lsqlite3_tprintf(local_ctx,
1392 "UPDATE ldb_entry SET dn = '%q', norm_dn = '%q' "
1393 "WHERE norm_dn = '%q';",
1394 new_dn, new_cdn, old_cdn);
1395 if (query == NULL) {
1396 ret = LDB_ERR_OTHER;
1401 ret = sqlite3_exec(lsqlite3->sqlite, query, NULL, NULL, &errmsg);
1402 if (ret != SQLITE_OK) {
1404 ldb_set_errstring(module, talloc_strdup(module, errmsg));
1407 ret = LDB_ERR_OTHER;
1411 /* clean up and exit */
1412 talloc_free(local_ctx);
1416 talloc_free(local_ctx);
1420 static int lsqlite3_start_trans(struct ldb_module * module)
1424 struct lsqlite3_private * lsqlite3 = module->private_data;
1426 if (lsqlite3->trans_count == 0) {
1427 ret = sqlite3_exec(lsqlite3->sqlite, "BEGIN IMMEDIATE;", NULL, NULL, &errmsg);
1428 if (ret != SQLITE_OK) {
1430 printf("lsqlite3_start_trans: error: %s\n", errmsg);
1437 lsqlite3->trans_count++;
1442 static int lsqlite3_end_trans(struct ldb_module *module)
1446 struct lsqlite3_private *lsqlite3 = module->private_data;
1448 if (lsqlite3->trans_count > 0) {
1449 lsqlite3->trans_count--;
1452 if (lsqlite3->trans_count == 0) {
1453 ret = sqlite3_exec(lsqlite3->sqlite, "COMMIT;", NULL, NULL, &errmsg);
1454 if (ret != SQLITE_OK) {
1456 printf("lsqlite3_end_trans: error: %s\n", errmsg);
1466 static int lsqlite3_del_trans(struct ldb_module *module)
1468 struct lsqlite3_private *lsqlite3 = module->private_data;
1470 if (lsqlite3->trans_count > 0) {
1471 lsqlite3->trans_count--;
1474 if (lsqlite3->trans_count == 0) {
1475 return lsqlite3_safe_rollback(lsqlite3->sqlite);
1485 static int initialize(struct lsqlite3_private *lsqlite3,
1486 struct ldb_context *ldb, const char *url, int flags)
1488 TALLOC_CTX *local_ctx;
1495 /* create a local ctx */
1496 local_ctx = talloc_named(lsqlite3, 0, "lsqlite3_rename local context");
1497 if (local_ctx == NULL) {
1501 schema = lsqlite3_tprintf(local_ctx,
1504 "CREATE TABLE ldb_info AS "
1505 " SELECT 'LDB' AS database_type,"
1506 " '1.0' AS version;"
1509 * The entry table holds the information about an entry.
1510 * This table is used to obtain the EID of the entry and to
1511 * support scope=one and scope=base. The parent and child
1512 * table is included in the entry table since all the other
1513 * attributes are dependent on EID.
1515 "CREATE TABLE ldb_entry "
1517 " eid INTEGER PRIMARY KEY AUTOINCREMENT,"
1518 " dn TEXT UNIQUE NOT NULL,"
1519 " norm_dn TEXT UNIQUE NOT NULL"
1523 "CREATE TABLE ldb_object_classes"
1525 " class_name TEXT PRIMARY KEY,"
1526 " parent_class_name TEXT,"
1527 " tree_key TEXT UNIQUE,"
1528 " max_child_num INTEGER DEFAULT 0"
1532 * We keep a full listing of attribute/value pairs here
1534 "CREATE TABLE ldb_attribute_values"
1536 " eid INTEGER REFERENCES ldb_entry,"
1538 " norm_attr_name TEXT,"
1540 " norm_attr_value TEXT "
1547 "CREATE INDEX ldb_attribute_values_eid_idx "
1548 " ON ldb_attribute_values (eid);"
1550 "CREATE INDEX ldb_attribute_values_name_value_idx "
1551 " ON ldb_attribute_values (attr_name, norm_attr_value);"
1559 "CREATE TRIGGER ldb_object_classes_insert_tr"
1561 " ON ldb_object_classes"
1564 " UPDATE ldb_object_classes"
1565 " SET tree_key = COALESCE(tree_key, "
1567 " SELECT tree_key || "
1568 " (SELECT base160(max_child_num + 1)"
1569 " FROM ldb_object_classes"
1570 " WHERE class_name = "
1571 " new.parent_class_name)"
1572 " FROM ldb_object_classes "
1573 " WHERE class_name = new.parent_class_name "
1575 " UPDATE ldb_object_classes "
1576 " SET max_child_num = max_child_num + 1"
1577 " WHERE class_name = new.parent_class_name;"
1581 * Table initialization
1584 "INSERT INTO ldb_object_classes "
1585 " (class_name, tree_key) "
1587 " ('TOP', '0001');");
1589 /* Skip protocol indicator of url */
1590 if (strncmp(url, "sqlite://", 9) != 0) {
1591 return SQLITE_MISUSE;
1594 /* Update pointer to just after the protocol indicator */
1597 /* Try to open the (possibly empty/non-existent) database */
1598 if ((ret = sqlite3_open(url, &lsqlite3->sqlite)) != SQLITE_OK) {
1602 /* In case this is a new database, enable auto_vacuum */
1603 ret = sqlite3_exec(lsqlite3->sqlite, "PRAGMA auto_vacuum = 1;", NULL, NULL, &errmsg);
1604 if (ret != SQLITE_OK) {
1606 printf("lsqlite3 initializaion error: %s\n", errmsg);
1612 if (flags & LDB_FLG_NOSYNC) {
1614 ret = sqlite3_exec(lsqlite3->sqlite, "PRAGMA synchronous = OFF;", NULL, NULL, &errmsg);
1615 if (ret != SQLITE_OK) {
1617 printf("lsqlite3 initializaion error: %s\n", errmsg);
1626 /* Establish a busy timeout of 30 seconds */
1627 if ((ret = sqlite3_busy_timeout(lsqlite3->sqlite,
1628 30000)) != SQLITE_OK) {
1632 /* Create a function, callable from sql, to increment a tree_key */
1634 sqlite3_create_function(lsqlite3->sqlite,/* handle */
1635 "base160_next", /* function name */
1636 1, /* number of args */
1637 SQLITE_ANY, /* preferred text type */
1638 NULL, /* user data */
1639 base160next_sql, /* called func */
1640 NULL, /* step func */
1641 NULL /* final func */
1646 /* Create a function, callable from sql, to convert int to base160 */
1648 sqlite3_create_function(lsqlite3->sqlite,/* handle */
1649 "base160", /* function name */
1650 1, /* number of args */
1651 SQLITE_ANY, /* preferred text type */
1652 NULL, /* user data */
1653 base160_sql, /* called func */
1654 NULL, /* step func */
1655 NULL /* final func */
1660 /* Create a function, callable from sql, to perform various comparisons */
1662 sqlite3_create_function(lsqlite3->sqlite, /* handle */
1663 "ldap_compare", /* function name */
1664 4, /* number of args */
1665 SQLITE_ANY, /* preferred text type */
1666 ldb , /* user data */
1667 lsqlite3_compare, /* called func */
1668 NULL, /* step func */
1669 NULL /* final func */
1674 /* Begin a transaction */
1675 ret = sqlite3_exec(lsqlite3->sqlite, "BEGIN EXCLUSIVE;", NULL, NULL, &errmsg);
1676 if (ret != SQLITE_OK) {
1678 printf("lsqlite3: initialization error: %s\n", errmsg);
1685 /* Determine if this is a new database. No tables means it is. */
1686 if (query_int(lsqlite3,
1689 " FROM sqlite_master\n"
1690 " WHERE type = 'table';") != 0) {
1694 if (queryInt == 0) {
1696 * Create the database schema
1698 ret = sqlite3_exec(lsqlite3->sqlite, schema, NULL, NULL, &errmsg);
1699 if (ret != SQLITE_OK) {
1701 printf("lsqlite3 initializaion error: %s\n", errmsg);
1708 * Ensure that the database we opened is one of ours
1710 if (query_int(lsqlite3,
1713 " (SELECT COUNT(*) = 2"
1714 " FROM sqlite_master "
1715 " WHERE type = 'table' "
1719 " 'ldb_object_classes' "
1725 " WHERE database_type = 'LDB' "
1726 " AND version = '1.0'"
1730 /* It's not one that we created. See ya! */
1735 /* Commit the transaction */
1736 ret = sqlite3_exec(lsqlite3->sqlite, "COMMIT;", NULL, NULL, &errmsg);
1737 if (ret != SQLITE_OK) {
1739 printf("lsqlite3: iniialization error: %s\n", errmsg);
1748 if (rollback) lsqlite3_safe_rollback(lsqlite3->sqlite);
1749 sqlite3_close(lsqlite3->sqlite);
1756 struct lsqlite3_private *lsqlite3 = p;
1758 if (lsqlite3->sqlite) {
1759 sqlite3_close(lsqlite3->sqlite);
1765 static int lsqlite3_request(struct ldb_module *module, struct ldb_request *req)
1767 /* check for oustanding critical controls and return an error if found */
1768 if (check_critical_controls(req->controls)) {
1769 return LDB_ERR_UNSUPPORTED_CRITICAL_EXTENSION;
1772 switch (req->operation) {
1774 case LDB_REQ_SEARCH:
1775 return lsqlite3_search_bytree(module,
1776 req->op.search.base,
1777 req->op.search.scope,
1778 req->op.search.tree,
1779 req->op.search.attrs,
1780 &req->op.search.res);
1783 return lsqlite3_add(module, req->op.add.message);
1785 case LDB_REQ_MODIFY:
1786 return lsqlite3_modify(module, req->op.mod.message);
1788 case LDB_REQ_DELETE:
1789 return lsqlite3_delete(module, req->op.del.dn);
1791 case LDB_REQ_RENAME:
1792 return lsqlite3_rename(module,
1793 req->op.rename.olddn,
1794 req->op.rename.newdn);
1797 return LDB_ERR_OPERATIONS_ERROR;
1802 static int lsqlite3_init_2(struct ldb_module *module)
1808 * Table of operations for the sqlite3 backend
1810 static const struct ldb_module_ops lsqlite3_ops = {
1812 .request = lsqlite3_request,
1813 .start_transaction = lsqlite3_start_trans,
1814 .end_transaction = lsqlite3_end_trans,
1815 .del_transaction = lsqlite3_del_trans,
1816 .second_stage_init = lsqlite3_init_2
1820 * connect to the database
1822 int lsqlite3_connect(struct ldb_context *ldb,
1825 const char *options[])
1829 struct lsqlite3_private * lsqlite3 = NULL;
1831 lsqlite3 = talloc(ldb, struct lsqlite3_private);
1836 lsqlite3->sqlite = NULL;
1837 lsqlite3->options = NULL;
1838 lsqlite3->trans_count = 0;
1840 ret = initialize(lsqlite3, ldb, url, flags);
1841 if (ret != SQLITE_OK) {
1845 talloc_set_destructor(lsqlite3, destructor);
1847 ldb->modules = talloc(ldb, struct ldb_module);
1848 if (!ldb->modules) {
1851 ldb->modules->ldb = ldb;
1852 ldb->modules->prev = ldb->modules->next = NULL;
1853 ldb->modules->private_data = lsqlite3;
1854 ldb->modules->ops = &lsqlite3_ops;
1858 * take a copy of the options array, so we don't have to rely
1859 * on the caller keeping it around (it might be dynamic)
1861 for (i=0;options[i];i++) ;
1863 lsqlite3->options = talloc_array(lsqlite3, char *, i+1);
1864 if (!lsqlite3->options) {
1868 for (i=0;options[i];i++) {
1870 lsqlite3->options[i+1] = NULL;
1871 lsqlite3->options[i] =
1872 talloc_strdup(lsqlite3->options, options[i]);
1873 if (!lsqlite3->options[i]) {
1882 if (lsqlite3->sqlite != NULL) {
1883 (void) sqlite3_close(lsqlite3->sqlite);
1885 talloc_free(lsqlite3);