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)
38 #include "ldb/include/ldb.h"
39 #include "ldb/include/ldb_private.h"
40 #include "ldb/ldb_sqlite3/ldb_sqlite3.h"
43 * Macros used throughout
48 # define TRUE (! FALSE)
51 #define RESULT_ATTR_TABLE "temp_result_attrs"
53 //#define TEMPTAB /* for testing, create non-temporary table */
54 #define TEMPTAB "TEMPORARY"
59 sqlite3_stmt * stmtGetEID = NULL;
61 static char *lsqlite3_tprintf(TALLOC_CTX *mem_ctx, const char *fmt, ...)
67 str = sqlite3_vmprintf(fmt, ap);
70 if (str == NULL) return NULL;
72 ret = talloc_strdup(mem_ctx, str);
82 static unsigned char base160tab[161] = {
83 48 ,49 ,50 ,51 ,52 ,53 ,54 ,55 ,56 ,57 , /* 0-9 */
84 58 ,59 ,65 ,66 ,67 ,68 ,69 ,70 ,71 ,72 , /* : ; A-H */
85 73 ,74 ,75 ,76 ,77 ,78 ,79 ,80 ,81 ,82 , /* I-R */
86 83 ,84 ,85 ,86 ,87 ,88 ,89 ,90 ,97 ,98 , /* S-Z , a-b */
87 99 ,100,101,102,103,104,105,106,107,108, /* c-l */
88 109,110,111,112,113,114,115,116,117,118, /* m-v */
89 119,120,121,122,160,161,162,163,164,165, /* w-z, latin1 */
90 166,167,168,169,170,171,172,173,174,175, /* latin1 */
91 176,177,178,179,180,181,182,183,184,185, /* latin1 */
92 186,187,188,189,190,191,192,193,194,195, /* latin1 */
93 196,197,198,199,200,201,202,203,204,205, /* latin1 */
94 206,207,208,209,210,211,212,213,214,215, /* latin1 */
95 216,217,218,219,220,221,222,223,224,225, /* latin1 */
96 226,227,228,229,230,231,232,233,234,235, /* latin1 */
97 236,237,238,239,240,241,242,243,244,245, /* latin1 */
98 246,247,248,249,250,251,252,253,254,255, /* latin1 */
106 * Convert an unsigned long integer into a base160 representation of the
111 * value to be converted
114 * character array, 5 bytes long, into which the base160 representation
115 * will be placed. The result will be a four-digit representation of the
116 * number (with leading zeros prepended as necessary), and null
123 base160_sql(sqlite3_context * hContext,
125 sqlite3_value ** argv)
131 val = sqlite3_value_int64(argv[0]);
133 for (i = 3; i >= 0; i--) {
135 result[i] = base160tab[val % 160];
141 sqlite3_result_text(hContext, result, -1, SQLITE_TRANSIENT);
148 * This function enhances sqlite by adding a "base160_next()" function which is
149 * accessible via queries.
151 * Retrieve the next-greater number in the base160 sequence for the terminal
152 * tree node (the last four digits). Only one tree level (four digits) is
156 * A character string: either an empty string (in which case no operation is
157 * performed), or a string of base160 digits with a length of a multiple of
161 * Upon return, the trailing four digits (one tree level) will have been
165 base160next_sql(sqlite3_context * hContext,
167 sqlite3_value ** argv)
171 unsigned char * pTab;
172 unsigned char * pBase160 =
173 strdup(sqlite3_value_text(argv[0]));
174 unsigned char * pStart = pBase160;
177 * We need a minimum of four digits, and we will always get a multiple
180 if (pBase160 != NULL &&
181 (len = strlen(pBase160)) >= 4 &&
184 if (pBase160 == NULL) {
186 sqlite3_result_null(hContext);
190 pBase160 += strlen(pBase160) - 1;
192 /* We only carry through four digits: one level in the tree */
193 for (i = 0; i < 4; i++) {
195 /* What base160 value does this digit have? */
196 pTab = strchr(base160tab, *pBase160);
198 /* Is there a carry? */
199 if (pTab < base160tab + sizeof(base160tab) - 1) {
202 * Nope. Just increment this value and we're
210 * There's a carry. This value gets
211 * base160tab[0], we decrement the buffer
212 * pointer to get the next higher-order digit,
213 * and continue in the loop.
215 *pBase160-- = base160tab[0];
219 sqlite3_result_text(hContext,
224 sqlite3_result_value(hContext, argv[0]);
225 if (pBase160 != NULL) {
231 static char *parsetree_to_sql(struct ldb_module *module,
233 const struct ldb_parse_tree *t)
235 const struct ldb_attrib_handler *h;
236 struct ldb_val value, subval;
237 char *wild_card_string;
244 switch(t->operation) {
247 tmp = parsetree_to_sql(module, mem_ctx, t->u.list.elements[0]);
248 if (tmp == NULL) return NULL;
250 for (i = 1; i < t->u.list.num_elements; i++) {
252 child = parsetree_to_sql(module, mem_ctx, t->u.list.elements[i]);
253 if (child == NULL) return NULL;
255 tmp = talloc_asprintf_append(tmp, " INTERSECT %s ", child);
256 if (tmp == NULL) return NULL;
259 ret = talloc_asprintf(mem_ctx, "SELECT * FROM ( %s )\n", tmp);
265 tmp = parsetree_to_sql(module, mem_ctx, t->u.list.elements[0]);
266 if (tmp == NULL) return NULL;
268 for (i = 1; i < t->u.list.num_elements; i++) {
270 child = parsetree_to_sql(module, mem_ctx, t->u.list.elements[i]);
271 if (child == NULL) return NULL;
273 tmp = talloc_asprintf_append(tmp, " UNION %s ", child);
274 if (tmp == NULL) return NULL;
277 return talloc_asprintf(mem_ctx, "SELECT * FROM ( %s ) ", tmp);
281 child = parsetree_to_sql(module, mem_ctx, t->u.isnot.child);
282 if (child == NULL) return NULL;
284 return talloc_asprintf(mem_ctx,
285 "SELECT eid FROM ldb_entry "
286 "WHERE eid NOT IN ( %s ) ", child);
288 case LDB_OP_EQUALITY:
290 * For simple searches, we want to retrieve the list of EIDs that
291 * match the criteria.
293 attr = ldb_casefold(mem_ctx, t->u.equality.attr);
294 if (attr == NULL) return NULL;
295 h = ldb_attrib_handler(module->ldb, attr);
297 /* Get a canonicalised copy of the data */
298 h->canonicalise_fn(module->ldb, mem_ctx, &(t->u.equality.value), &value);
299 if (value.data == NULL) {
303 if (strcasecmp(t->u.equality.attr, "objectclass") == 0) {
305 * For object classes, we want to search for all objectclasses
306 * that are subclasses as well.
308 return lsqlite3_tprintf(mem_ctx,
309 "SELECT eid FROM ldb_attribute_values\n"
310 "WHERE norm_attr_name = 'OBJECTCLASS' "
311 "AND norm_attr_value IN\n"
312 " (SELECT class_name FROM ldb_object_classes\n"
313 " WHERE tree_key GLOB\n"
314 " (SELECT tree_key FROM ldb_object_classes\n"
315 " WHERE class_name = '%q'\n"
319 } else if (strcasecmp(t->u.equality.attr, "dn") == 0) {
320 /* DN query is a special ldb case */
321 char *cdn = ldb_dn_linearize_casefold(module->ldb,
322 ldb_dn_explode(module->ldb,
325 return lsqlite3_tprintf(mem_ctx,
326 "SELECT eid FROM ldb_entry "
327 "WHERE norm_dn = '%q'", cdn);
330 /* A normal query. */
331 return lsqlite3_tprintf(mem_ctx,
332 "SELECT eid FROM ldb_attribute_values "
333 "WHERE norm_attr_name = '%q' "
334 "AND norm_attr_value = '%q'",
340 case LDB_OP_SUBSTRING:
342 wild_card_string = talloc_strdup(mem_ctx,
343 (t->u.substring.start_with_wildcard)?"*":"");
344 if (wild_card_string == NULL) return NULL;
346 for (i = 0; t->u.substring.chunks[i]; i++) {
347 wild_card_string = talloc_asprintf_append(wild_card_string, "%s*",
348 t->u.substring.chunks[i]->data);
349 if (wild_card_string == NULL) return NULL;
352 if ( ! t->u.substring.end_with_wildcard ) {
353 /* remove last wildcard */
354 wild_card_string[strlen(wild_card_string) - 1] = '\0';
357 attr = ldb_casefold(mem_ctx, t->u.substring.attr);
358 if (attr == NULL) return NULL;
359 h = ldb_attrib_handler(module->ldb, attr);
361 subval.data = wild_card_string;
362 subval.length = strlen(wild_card_string) + 1;
364 /* Get a canonicalised copy of the data */
365 h->canonicalise_fn(module->ldb, mem_ctx, &(subval), &value);
366 if (value.data == NULL) {
370 return lsqlite3_tprintf(mem_ctx,
371 "SELECT eid FROM ldb_attribute_values "
372 "WHERE norm_attr_name = '%q' "
373 "AND norm_attr_value GLOB '%q'",
378 attr = ldb_casefold(mem_ctx, t->u.equality.attr);
379 if (attr == NULL) return NULL;
380 h = ldb_attrib_handler(module->ldb, attr);
382 /* Get a canonicalised copy of the data */
383 h->canonicalise_fn(module->ldb, mem_ctx, &(t->u.equality.value), &value);
384 if (value.data == NULL) {
388 return lsqlite3_tprintf(mem_ctx,
389 "SELECT eid FROM ldb_attribute_values "
390 "WHERE norm_attr_name = '%q' "
391 "AND ldap_compare(norm_attr_value, '>=', '%q', '%q') ",
397 attr = ldb_casefold(mem_ctx, t->u.equality.attr);
398 if (attr == NULL) return NULL;
399 h = ldb_attrib_handler(module->ldb, attr);
401 /* Get a canonicalised copy of the data */
402 h->canonicalise_fn(module->ldb, mem_ctx, &(t->u.equality.value), &value);
403 if (value.data == NULL) {
407 return lsqlite3_tprintf(mem_ctx,
408 "SELECT eid FROM ldb_attribute_values "
409 "WHERE norm_attr_name = '%q' "
410 "AND ldap_compare(norm_attr_value, '<=', '%q', '%q') ",
416 if (strcasecmp(t->u.present.attr, "dn") == 0) {
417 return talloc_strdup(mem_ctx, "SELECT eid FROM ldb_entry");
420 attr = ldb_casefold(mem_ctx, t->u.present.attr);
421 if (attr == NULL) return NULL;
423 return lsqlite3_tprintf(mem_ctx,
424 "SELECT eid FROM ldb_attribute_values "
425 "WHERE norm_attr_name = '%q' ",
429 attr = ldb_casefold(mem_ctx, t->u.equality.attr);
430 if (attr == NULL) return NULL;
431 h = ldb_attrib_handler(module->ldb, attr);
433 /* Get a canonicalised copy of the data */
434 h->canonicalise_fn(module->ldb, mem_ctx, &(t->u.equality.value), &value);
435 if (value.data == NULL) {
439 return lsqlite3_tprintf(mem_ctx,
440 "SELECT eid FROM ldb_attribute_values "
441 "WHERE norm_attr_name = '%q' "
442 "AND ldap_compare(norm_attr_value, '~%', 'q', '%q') ",
447 case LDB_OP_EXTENDED:
448 #warning "work out how to handle bitops"
455 /* should never occur */
460 /* obtain a named lock */
462 lsqlite3_lock(struct ldb_module * module,
463 const char * lockname)
465 struct lsqlite3_private * lsqlite3 = module->private_data;
468 if (lockname == NULL) {
472 if (strcmp(lockname, "transaction") == 0) {
473 if (lsqlite3->lock_count == 0) {
474 if (query_norows(lsqlite3, "BEGIN EXCLUSIVE;") != 0) {
478 ++lsqlite3->lock_count;
484 /* release a named lock */
486 lsqlite3_unlock(struct ldb_module *module,
487 const char *lockname)
489 struct lsqlite3_private * lsqlite3 = module->private_data;
492 if (lockname == NULL) {
496 if (strcmp(lockname, "transaction") == 0) {
497 if (lsqlite3->lock_count == 1) {
498 if (query_norows(lsqlite3, "COMMIT;") != 0) {
499 query_norows(lsqlite3, "ROLLBACK;");
501 } else if (lsqlite3->lock_count > 0) {
502 --lsqlite3->lock_count;
504 } else if (strcmp(lockname, "rollback") == 0) {
505 query_norows(lsqlite3, "ROLLBACK;");
514 * This function is used for the common case of queries that return a single
517 * NOTE: If more than one value is returned by the query, all but the first
518 * one will be ignored.
521 query_int(const struct lsqlite3_private * lsqlite3,
529 sqlite3_stmt * pStmt;
532 /* Begin access to variable argument list */
533 va_start(args, pSql);
535 /* Format the query */
536 if ((p = sqlite3_vmprintf(pSql, args)) == NULL) {
541 * Prepare and execute the SQL statement. Loop allows retrying on
542 * certain errors, e.g. SQLITE_SCHEMA occurs if the schema changes,
543 * requiring retrying the operation.
545 for (bLoop = TRUE; bLoop; ) {
547 /* Compile the SQL statement into sqlite virtual machine */
548 if ((ret = sqlite3_prepare(lsqlite3->sqlite,
552 NULL)) == SQLITE_SCHEMA) {
553 if (stmtGetEID != NULL) {
554 sqlite3_finalize(stmtGetEID);
558 } else if (ret != SQLITE_OK) {
562 /* One row expected */
563 if ((ret = sqlite3_step(pStmt)) == SQLITE_SCHEMA) {
564 if (stmtGetEID != NULL) {
565 sqlite3_finalize(stmtGetEID);
568 (void) sqlite3_finalize(pStmt);
570 } else if (ret != SQLITE_ROW) {
571 (void) sqlite3_finalize(pStmt);
575 /* Get the value to be returned */
576 *pRet = sqlite3_column_int64(pStmt, 0);
578 /* Free the virtual machine */
579 if ((ret = sqlite3_finalize(pStmt)) == SQLITE_SCHEMA) {
580 if (stmtGetEID != NULL) {
581 sqlite3_finalize(stmtGetEID);
585 } else if (ret != SQLITE_OK) {
586 (void) sqlite3_finalize(pStmt);
591 * Normal condition is only one time through loop. Loop is
592 * rerun in error conditions, via "continue", above.
597 /* All done with variable argument list */
601 /* Free the memory we allocated for our query string */
608 * This is a bad hack to support ldap style comparisons whithin sqlite.
609 * val is the attribute in the row currently under test
610 * func is the desired test "<=" ">=" "~" ":"
611 * cmp is the value to compare against (eg: "test")
612 * attr is the attribute name the value of which we want to test
615 static void lsqlite3_compare(sqlite3_context *ctx, int argc,
616 sqlite3_value **argv)
618 struct ldb_context *ldb = (struct ldb_context *)sqlite3_user_data(ctx);
619 const unsigned char *val = sqlite3_value_text(argv[0]);
620 const unsigned char *func = sqlite3_value_text(argv[1]);
621 const unsigned char *cmp = sqlite3_value_text(argv[2]);
622 const unsigned char *attr = sqlite3_value_text(argv[3]);
623 const struct ldb_attrib_handler *h;
631 h = ldb_attrib_handler(ldb, attr);
633 valX.length = strlen(cmp);
635 valY.length = strlen(val);
636 ret = h->comparison_fn(ldb, ldb, &valY, &valX);
638 sqlite3_result_int(ctx, 1);
640 sqlite3_result_int(ctx, 0);
645 h = ldb_attrib_handler(ldb, attr);
647 valX.length = strlen(cmp);
649 valY.length = strlen(val);
650 ret = h->comparison_fn(ldb, ldb, &valY, &valX);
652 sqlite3_result_int(ctx, 1);
654 sqlite3_result_int(ctx, 0);
660 sqlite3_result_int(ctx, 0);
666 sqlite3_result_int(ctx, 0);
673 sqlite3_result_error(ctx, "Value must start with a special operation char (<>~:)!", -1);
678 /* rename a record */
679 static int lsqlite3_safe_rollback(sqlite3 *sqlite)
685 ret = sqlite3_exec(sqlite, "ROLLBACK;", NULL, NULL, &errmsg);
686 if (ret != SQLITE_OK) {
688 printf("lsqlite3_safe_rollback: Serious Error: %s\n", errmsg);
697 /* return an eid as result */
698 static int lsqlite3_eid_callback(void *result, int col_num, char **cols, char **names)
700 long long *eid = (long long *)result;
702 if (col_num != 1) return SQLITE_ABORT;
703 if (strcasecmp(names[0], "eid") != 0) return SQLITE_ABORT;
705 *eid = atoll(cols[0]);
709 struct lsqlite3_msgs {
711 struct ldb_message **msgs;
712 long long current_eid;
713 const char * const * attrs;
718 * add a single set of ldap message values to a ldb_message
721 static int lsqlite3_search_callback(void *result, int col_num, char **cols, char **names)
723 struct lsqlite3_msgs *msgs = (struct lsqlite3_msgs *)result;
724 struct ldb_message *msg;
728 /* eid, dn, attr_name, attr_value */
729 if (col_num != 4) return SQLITE_ABORT;
731 eid = atoll(cols[0]);
733 if (eid != msgs->current_eid) {
734 msgs->msgs = talloc_realloc(msgs->mem_ctx,
736 struct ldb_message *,
738 if (msgs->msgs == NULL) return SQLITE_ABORT;
740 msgs->msgs[msgs->count] = talloc(msgs->msgs, struct ldb_message);
741 if (msgs->msgs[msgs->count] == NULL) return SQLITE_ABORT;
743 msgs->msgs[msgs->count]->dn = NULL;
744 msgs->msgs[msgs->count]->num_elements = 0;
745 msgs->msgs[msgs->count]->elements = NULL;
746 msgs->msgs[msgs->count]->private_data = NULL;
749 msgs->current_eid = eid;
752 msg = msgs->msgs[msgs->count -1];
754 if (msg->dn == NULL) {
755 msg->dn = ldb_dn_explode(msg, cols[1]);
756 if (msg->dn == NULL) return SQLITE_ABORT;
761 for (i = 0; msgs->attrs[i]; i++) {
762 if (strcasecmp(cols[2], msgs->attrs[i]) == 0) {
767 if (!found) return 0;
770 msg->elements = talloc_realloc(msg,
772 struct ldb_message_element,
773 msg->num_elements + 1);
774 if (msg->elements == NULL) return SQLITE_ABORT;
776 msg->elements[msg->num_elements].flags = 0;
777 msg->elements[msg->num_elements].name = talloc_strdup(msg->elements, cols[2]);
778 if (msg->elements[msg->num_elements].name == NULL) return SQLITE_ABORT;
780 msg->elements[msg->num_elements].num_values = 1;
781 msg->elements[msg->num_elements].values = talloc_array(msg->elements,
783 if (msg->elements[msg->num_elements].values == NULL) return SQLITE_ABORT;
785 msg->elements[msg->num_elements].values[0].length = strlen(cols[3]);
786 msg->elements[msg->num_elements].values[0].data = talloc_strdup(msg->elements, cols[3]);
787 if (msg->elements[msg->num_elements].values[0].data == NULL) return SQLITE_ABORT;
797 * lsqlite3_get_eid_ndn()
799 * These functions are used for the very common case of retrieving an EID value
800 * given a (normalized) DN.
803 static long long lsqlite3_get_eid_ndn(sqlite3 *sqlite, void *mem_ctx, const char *norm_dn)
811 query = lsqlite3_tprintf(mem_ctx, "SELECT eid "
813 "WHERE norm_dn = '%q';", norm_dn);
814 if (query == NULL) return -1;
816 ret = sqlite3_exec(sqlite, query, lsqlite3_eid_callback, &eid, &errmsg);
817 if (ret != SQLITE_OK) {
819 printf("lsqlite3_get_eid: Fatal Error: %s\n", errmsg);
828 static long long lsqlite3_get_eid(struct ldb_module *module, const struct ldb_dn *dn)
830 TALLOC_CTX *local_ctx;
831 struct lsqlite3_private *lsqlite3 = module->private_data;
835 /* ignore ltdb specials */
836 if (ldb_dn_is_special(dn)) {
840 /* create a local ctx */
841 local_ctx = talloc_named(lsqlite3, 0, "lsqlite3_get_eid local context");
842 if (local_ctx == NULL) {
846 cdn = ldb_dn_linearize(local_ctx, ldb_dn_casefold(module->ldb, dn));
849 eid = lsqlite3_get_eid_ndn(lsqlite3->sqlite, local_ctx, cdn);
852 talloc_free(local_ctx);
857 * Interface functions referenced by lsqlite3_ops
860 /* search for matching records, by tree */
861 static int lsqlite3_search_bytree(struct ldb_module * module, const struct ldb_dn* basedn,
862 enum ldb_scope scope, struct ldb_parse_tree * tree,
863 const char * const * attrs, struct ldb_message *** res)
865 TALLOC_CTX *local_ctx;
866 struct lsqlite3_private *lsqlite3 = module->private_data;
867 struct lsqlite3_msgs msgs;
874 /* create a local ctx */
875 local_ctx = talloc_named(lsqlite3, 0, "lsqlite3_search_by_tree local context");
876 if (local_ctx == NULL) {
881 norm_basedn = ldb_dn_linearize(local_ctx, ldb_dn_casefold(module->ldb, basedn));
882 if (norm_basedn == NULL) goto failed;
883 } else norm_basedn = talloc_strdup(local_ctx, "");
885 if (*norm_basedn == '\0' &&
886 (scope == LDB_SCOPE_BASE || scope == LDB_SCOPE_ONELEVEL))
889 /* Convert filter into a series of SQL conditions (constraints) */
890 sqlfilter = parsetree_to_sql(module, local_ctx, tree);
893 case LDB_SCOPE_DEFAULT:
894 case LDB_SCOPE_SUBTREE:
895 if (*norm_basedn != '\0') {
896 query = lsqlite3_tprintf(local_ctx,
897 "SELECT entry.eid,\n"
901 " FROM ldb_entry AS entry\n"
903 " LEFT OUTER JOIN ldb_attribute_values AS av\n"
904 " ON av.eid = entry.eid\n"
906 " WHERE entry.eid IN\n"
907 " (SELECT DISTINCT ldb_entry.eid\n"
909 " WHERE (ldb_entry.norm_dn GLOB('*,%q')\n"
910 " OR ldb_entry.norm_dn = '%q')\n"
911 " AND ldb_entry.eid IN\n"
915 " ORDER BY entry.eid ASC;",
920 query = lsqlite3_tprintf(local_ctx,
921 "SELECT entry.eid,\n"
925 " FROM ldb_entry AS entry\n"
927 " LEFT OUTER JOIN ldb_attribute_values AS av\n"
928 " ON av.eid = entry.eid\n"
930 " WHERE entry.eid IN\n"
931 " (SELECT DISTINCT ldb_entry.eid\n"
933 " WHERE ldb_entry.eid IN\n"
937 " ORDER BY entry.eid ASC;",
944 query = lsqlite3_tprintf(local_ctx,
945 "SELECT entry.eid,\n"
949 " FROM ldb_entry AS entry\n"
951 " LEFT OUTER JOIN ldb_attribute_values AS av\n"
952 " ON av.eid = entry.eid\n"
954 " WHERE entry.eid IN\n"
955 " (SELECT DISTINCT ldb_entry.eid\n"
957 " WHERE ldb_entry.norm_dn = '%q'\n"
958 " AND ldb_entry.eid IN\n"
962 " ORDER BY entry.eid ASC;",
967 case LDB_SCOPE_ONELEVEL:
968 query = lsqlite3_tprintf(local_ctx,
969 "SELECT entry.eid,\n"
973 " FROM ldb_entry AS entry\n"
975 " LEFT OUTER JOIN ldb_attribute_values AS av\n"
976 " ON av.eid = entry.eid\n"
978 " WHERE entry.eid IN\n"
979 " (SELECT DISTINCT ldb_entry.eid\n"
981 " WHERE norm_dn GLOB('*,%q')\n"
982 " AND NOT norm_dn GLOB('*,*,%q')\n"
983 " AND ldb_entry.eid IN\n(%s)\n"
986 " ORDER BY entry.eid ASC;",
999 printf ("%s\n", query);
1004 msgs.current_eid = 0;
1005 msgs.mem_ctx = local_ctx;
1008 ret = sqlite3_exec(lsqlite3->sqlite, query, lsqlite3_search_callback, &msgs, &errmsg);
1009 if (ret != SQLITE_OK) {
1011 printf("lsqlite3_search_bytree: Fatal Error: %s\n", errmsg);
1017 for (i = 0; i < msgs.count; i++) {
1018 msgs.msgs[i] = ldb_msg_canonicalize(module->ldb, msgs.msgs[i]);
1019 if (msgs.msgs[i] == NULL) goto failed;
1022 *res = talloc_steal(module, msgs.msgs);
1025 talloc_free(local_ctx);
1028 /* If error, return error code; otherwise return number of results */
1030 talloc_free(local_ctx);
1034 /* search for matching records, by expression */
1035 static int lsqlite3_search(struct ldb_module * module, const struct ldb_dn *basedn,
1036 enum ldb_scope scope, const char * expression,
1037 const char * const *attrs, struct ldb_message *** res)
1039 struct ldb_parse_tree * tree;
1042 /* Handle tdb specials */
1043 if (ldb_dn_is_special(basedn)) {
1044 #warning "handle tdb specials"
1049 /* (|(objectclass=*)(dn=*)) is passed by the command line tool now instead */
1050 /* Handle the special case of requesting all */
1051 if (pExpression != NULL && *pExpression == '\0') {
1052 pExpression = "dn=*";
1056 /* Parse the filter expression into a tree we can work with */
1057 if ((tree = ldb_parse_tree(module->ldb, expression)) == NULL) {
1061 /* Now use the bytree function for the remainder of processing */
1062 ret = lsqlite3_search_bytree(module, basedn, scope, tree, attrs, res);
1064 /* Free the parse tree */
1073 static int lsqlite3_add(struct ldb_module *module, const struct ldb_message *msg)
1075 TALLOC_CTX *local_ctx;
1076 struct lsqlite3_private *lsqlite3 = module->private_data;
1085 /* create a local ctx */
1086 local_ctx = talloc_named(lsqlite3, 0, "lsqlite3_add local context");
1087 if (local_ctx == NULL) {
1091 /* See if this is an ltdb special */
1092 if (ldb_dn_is_special(msg->dn)) {
1095 c = ldb_dn_explode(local_ctx, "@SUBCLASSES");
1096 if (ldb_dn_compare(module->ldb, msg->dn, c) == 0) {
1097 #warning "insert subclasses into object class tree"
1102 c = ldb_dn_explode(local_ctx, "@INDEXLIST");
1103 if (ldb_dn_compare(module->ldb, msg->dn, c) == 0) {
1104 #warning "should we handle indexes somehow ?"
1108 /* Others are implicitly ignored */
1112 /* create linearized and normalized dns */
1113 dn = ldb_dn_linearize(local_ctx, msg->dn);
1114 ndn = ldb_dn_linearize(local_ctx, ldb_dn_casefold(module->ldb, msg->dn));
1115 if (dn == NULL || ndn == NULL) goto failed;
1117 query = lsqlite3_tprintf(local_ctx,
1118 /* Begin the transaction */
1121 "INSERT OR ABORT INTO ldb_entry "
1122 "('dn', 'norm_dn') "
1123 "VALUES ('%q', '%q');",
1125 if (query == NULL) goto failed;
1127 ret = sqlite3_exec(lsqlite3->sqlite, query, NULL, NULL, &errmsg);
1128 if (ret != SQLITE_OK) {
1130 printf("lsqlite3_add: exec error: %s\n", errmsg);
1133 lsqlite3_safe_rollback(lsqlite3->sqlite);
1138 eid = lsqlite3_get_eid_ndn(lsqlite3->sqlite, local_ctx, ndn);
1139 if (eid == -1) goto failed;
1141 for (i = 0; i < msg->num_elements; i++) {
1142 const struct ldb_message_element *el = &msg->elements[i];
1143 const struct ldb_attrib_handler *h;
1147 /* Get a case-folded copy of the attribute name */
1148 attr = ldb_casefold(local_ctx, el->name);
1149 if (attr == NULL) goto failed;
1151 h = ldb_attrib_handler(module->ldb, el->name);
1153 /* For each value of the specified attribute name... */
1154 for (j = 0; j < el->num_values; j++) {
1155 struct ldb_val value;
1158 /* Get a canonicalised copy of the data */
1159 h->canonicalise_fn(module->ldb, local_ctx, &(el->values[j]), &value);
1160 if (value.data == NULL) goto failed;
1162 insert = lsqlite3_tprintf(local_ctx,
1163 "INSERT OR ROLLBACK INTO ldb_attribute_values "
1164 "('eid', 'attr_name', 'norm_attr_name',"
1165 " 'attr_value', 'norm_attr_value') "
1166 "VALUES ('%lld', '%q', '%q', '%q', '%q');",
1167 eid, el->name, attr,
1168 el->values[j].data, value.data);
1169 if (insert == NULL) goto failed;
1171 ret = sqlite3_exec(lsqlite3->sqlite, insert, NULL, NULL, &errmsg);
1172 if (ret != SQLITE_OK) {
1174 printf("lsqlite3_add: insert error: %s\n", errmsg);
1182 ret = sqlite3_exec(lsqlite3->sqlite, "COMMIT;", NULL, NULL, &errmsg);
1183 if (ret != SQLITE_OK) {
1185 printf("lsqlite3_add: commit error: %s\n", errmsg);
1191 talloc_free(local_ctx);
1195 if (rollback) lsqlite3_safe_rollback(lsqlite3->sqlite);
1196 talloc_free(local_ctx);
1201 /* modify a record */
1202 static int lsqlite3_modify(struct ldb_module *module, const struct ldb_message *msg)
1204 TALLOC_CTX *local_ctx;
1205 struct lsqlite3_private *lsqlite3 = module->private_data;
1212 /* create a local ctx */
1213 local_ctx = talloc_named(lsqlite3, 0, "lsqlite3_modify local context");
1214 if (local_ctx == NULL) {
1218 /* See if this is an ltdb special */
1219 if (ldb_dn_is_special(msg->dn)) {
1222 c = ldb_dn_explode(local_ctx, "@SUBCLASSES");
1223 if (ldb_dn_compare(module->ldb, msg->dn, c) == 0) {
1224 #warning "modify subclasses into object class tree"
1228 c = ldb_dn_explode(local_ctx, "@INDEXLIST");
1229 if (ldb_dn_compare(module->ldb, msg->dn, c) == 0) {
1230 #warning "should we handle indexes somehow ?"
1234 /* Others are implicitly ignored */
1238 ret = sqlite3_exec(lsqlite3->sqlite, "BEGIN EXCLUSIVE;", NULL, NULL, &errmsg);
1239 if (ret != SQLITE_OK) {
1241 printf("lsqlite3_modify: error: %s\n", errmsg);
1248 eid = lsqlite3_get_eid(module, msg->dn);
1253 for (i = 0; i < msg->num_elements; i++) {
1254 const struct ldb_message_element *el = &msg->elements[i];
1255 const struct ldb_attrib_handler *h;
1256 int flags = el->flags & LDB_FLAG_MOD_MASK;
1261 /* Get a case-folded copy of the attribute name */
1262 attr = ldb_casefold(local_ctx, el->name);
1267 h = ldb_attrib_handler(module->ldb, el->name);
1271 case LDB_FLAG_MOD_REPLACE:
1273 /* remove all attributes before adding the replacements */
1274 mod = lsqlite3_tprintf(local_ctx,
1275 "DELETE FROM ldb_attribute_values "
1276 "WHERE eid = '%lld' "
1277 "AND norm_attr_name = '%q';",
1279 if (mod == NULL) goto failed;
1281 ret = sqlite3_exec(lsqlite3->sqlite, mod, NULL, NULL, &errmsg);
1282 if (ret != SQLITE_OK) {
1284 printf("lsqlite3_modify: error: %s\n", errmsg);
1290 /* MISSING break is INTENTIONAL */
1292 case LDB_FLAG_MOD_ADD:
1293 #warning "We should throw an error if no value is provided!"
1294 /* For each value of the specified attribute name... */
1295 for (j = 0; j < el->num_values; j++) {
1296 struct ldb_val value;
1298 /* Get a canonicalised copy of the data */
1299 h->canonicalise_fn(module->ldb, local_ctx, &(el->values[j]), &value);
1300 if (value.data == NULL) {
1304 mod = lsqlite3_tprintf(local_ctx,
1305 "INSERT OR ROLLBACK INTO ldb_attribute_values "
1306 "('eid', 'attr_name', 'norm_attr_name',"
1307 " 'attr_value', 'norm_attr_value') "
1308 "VALUES ('%lld', '%q', '%q', '%q', '%q');",
1309 eid, el->name, attr,
1310 el->values[j].data, value.data);
1312 if (mod == NULL) goto failed;
1314 ret = sqlite3_exec(lsqlite3->sqlite, mod, NULL, NULL, &errmsg);
1315 if (ret != SQLITE_OK) {
1317 printf("lsqlite3_modify: error: %s\n", errmsg);
1326 case LDB_FLAG_MOD_DELETE:
1327 #warning "We should throw an error if the attribute we are trying to delete does not exist!"
1328 if (el->num_values == 0) {
1329 mod = lsqlite3_tprintf(local_ctx,
1330 "DELETE FROM ldb_attribute_values "
1331 "WHERE eid = '%lld' "
1332 "AND norm_attr_name = '%q';",
1334 if (mod == NULL) goto failed;
1336 ret = sqlite3_exec(lsqlite3->sqlite, mod, NULL, NULL, &errmsg);
1337 if (ret != SQLITE_OK) {
1339 printf("lsqlite3_modify: error: %s\n", errmsg);
1346 /* For each value of the specified attribute name... */
1347 for (j = 0; j < el->num_values; j++) {
1348 struct ldb_val value;
1350 /* Get a canonicalised copy of the data */
1351 h->canonicalise_fn(module->ldb, local_ctx, &(el->values[j]), &value);
1352 if (value.data == NULL) {
1356 mod = lsqlite3_tprintf(local_ctx,
1357 "DELETE FROM ldb_attribute_values "
1358 "WHERE eid = '%lld' "
1359 "AND norm_attr_name = '%q' "
1360 "AND norm_attr_value = '%q';",
1361 eid, attr, value.data);
1363 if (mod == NULL) goto failed;
1365 ret = sqlite3_exec(lsqlite3->sqlite, mod, NULL, NULL, &errmsg);
1366 if (ret != SQLITE_OK) {
1368 printf("lsqlite3_modify: error: %s\n", errmsg);
1379 ret = sqlite3_exec(lsqlite3->sqlite, "COMMIT;", NULL, NULL, &errmsg);
1380 if (ret != SQLITE_OK) {
1382 printf("lsqlite3_modify: error: %s\n", errmsg);
1388 talloc_free(local_ctx);
1392 if (rollback) lsqlite3_safe_rollback(lsqlite3->sqlite);
1393 talloc_free(local_ctx);
1397 /* delete a record */
1398 static int lsqlite3_delete(struct ldb_module *module, const struct ldb_dn *dn)
1400 TALLOC_CTX *local_ctx;
1401 struct lsqlite3_private *lsqlite3 = module->private_data;
1407 /* ignore ltdb specials */
1408 if (ldb_dn_is_special(dn)) {
1412 /* create a local ctx */
1413 local_ctx = talloc_named(lsqlite3, 0, "lsqlite3_delete local context");
1414 if (local_ctx == NULL) {
1418 eid = lsqlite3_get_eid(module, dn);
1419 if (eid == -1) goto failed;
1421 query = lsqlite3_tprintf(local_ctx,
1422 /* Begin the transaction */
1425 "DELETE FROM ldb_entry WHERE eid = %lld; "
1426 /* Delete attributes */
1427 "DELETE FROM ldb_attribute_values WHERE eid = %lld; "
1431 if (query == NULL) goto failed;
1433 ret = sqlite3_exec(lsqlite3->sqlite, query, NULL, NULL, &errmsg);
1434 if (ret != SQLITE_OK) {
1436 printf("lsqlite3_delete: error getting eid: %s\n", errmsg);
1439 lsqlite3_safe_rollback(lsqlite3->sqlite);
1443 talloc_free(local_ctx);
1447 talloc_free(local_ctx);
1451 /* rename a record */
1452 static int lsqlite3_rename(struct ldb_module *module, const struct ldb_dn *olddn, const struct ldb_dn *newdn)
1454 TALLOC_CTX *local_ctx;
1455 struct lsqlite3_private *lsqlite3 = module->private_data;
1456 char *new_dn, *new_cdn, *old_cdn;
1461 /* ignore ltdb specials */
1462 if (ldb_dn_is_special(olddn) || ldb_dn_is_special(newdn)) {
1466 /* create a local ctx */
1467 local_ctx = talloc_named(lsqlite3, 0, "lsqlite3_rename local context");
1468 if (local_ctx == NULL) {
1472 /* create linearized and normalized dns */
1473 old_cdn = ldb_dn_linearize(local_ctx, ldb_dn_casefold(module->ldb, olddn));
1474 new_cdn = ldb_dn_linearize(local_ctx, ldb_dn_casefold(module->ldb, newdn));
1475 new_dn = ldb_dn_linearize(local_ctx, newdn);
1476 if (old_cdn == NULL || new_cdn == NULL || new_dn == NULL) goto failed;
1478 /* build the SQL query */
1479 query = lsqlite3_tprintf(local_ctx,
1480 "UPDATE ldb_entry SET dn = '%q', norm_dn = '%q' "
1481 "WHERE norm_dn = '%q';",
1482 new_dn, new_cdn, old_cdn);
1483 if (query == NULL) goto failed;
1486 ret = sqlite3_exec(lsqlite3->sqlite, query, NULL, NULL, &errmsg);
1487 if (ret != SQLITE_OK) {
1489 printf("lsqlite3_rename: sqlite3_exec error: %s\n", errmsg);
1495 /* clean up and exit */
1496 talloc_free(local_ctx);
1500 talloc_free(local_ctx);
1503 /* return extended error information */
1505 lsqlite3_errstring(struct ldb_module *module)
1507 struct lsqlite3_private * lsqlite3 = module->private_data;
1509 return sqlite3_errmsg(lsqlite3->sqlite);
1519 static int initialize(struct lsqlite3_private *lsqlite3,
1520 struct ldb_context *ldb, const char *url)
1522 TALLOC_CTX *local_ctx;
1529 /* create a local ctx */
1530 local_ctx = talloc_named(lsqlite3, 0, "lsqlite3_rename local context");
1531 if (local_ctx == NULL) {
1535 schema = lsqlite3_tprintf(local_ctx,
1538 "CREATE TABLE ldb_info AS "
1539 " SELECT 'LDB' AS database_type,"
1540 " '1.0' AS version;"
1543 * The entry table holds the information about an entry.
1544 * This table is used to obtain the EID of the entry and to
1545 * support scope=one and scope=base. The parent and child
1546 * table is included in the entry table since all the other
1547 * attributes are dependent on EID.
1549 "CREATE TABLE ldb_entry "
1551 " eid INTEGER PRIMARY KEY AUTOINCREMENT,"
1552 " dn TEXT UNIQUE NOT NULL,"
1553 " norm_dn TEXT UNIQUE NOT NULL"
1557 "CREATE TABLE ldb_object_classes"
1559 " class_name TEXT PRIMARY KEY,"
1560 " parent_class_name TEXT,"
1561 " tree_key TEXT UNIQUE,"
1562 " max_child_num INTEGER DEFAULT 0"
1566 * We keep a full listing of attribute/value pairs here
1568 "CREATE TABLE ldb_attribute_values"
1570 " eid INTEGER REFERENCES ldb_entry,"
1572 " norm_attr_name TEXT,"
1574 " norm_attr_value TEXT "
1581 "CREATE INDEX ldb_attribute_values_eid_idx "
1582 " ON ldb_attribute_values (eid);"
1584 "CREATE INDEX ldb_attribute_values_name_value_idx "
1585 " ON ldb_attribute_values (attr_name, norm_attr_value);"
1593 "CREATE TRIGGER ldb_object_classes_insert_tr"
1595 " ON ldb_object_classes"
1598 " UPDATE ldb_object_classes"
1599 " SET tree_key = COALESCE(tree_key, "
1601 " SELECT tree_key || "
1602 " (SELECT base160(max_child_num + 1)"
1603 " FROM ldb_object_classes"
1604 " WHERE class_name = "
1605 " new.parent_class_name)"
1606 " FROM ldb_object_classes "
1607 " WHERE class_name = new.parent_class_name "
1609 " UPDATE ldb_object_classes "
1610 " SET max_child_num = max_child_num + 1"
1611 " WHERE class_name = new.parent_class_name;"
1615 * Table initialization
1618 "INSERT INTO ldb_object_classes "
1619 " (class_name, tree_key) "
1621 " ('TOP', '0001');");
1623 /* Skip protocol indicator of url */
1624 if (strncmp(url, "sqlite://", 9) != 0) {
1625 return SQLITE_MISUSE;
1628 /* Update pointer to just after the protocol indicator */
1631 /* Try to open the (possibly empty/non-existent) database */
1632 if ((ret = sqlite3_open(url, &lsqlite3->sqlite)) != SQLITE_OK) {
1636 /* In case this is a new database, enable auto_vacuum */
1637 ret = sqlite3_exec(lsqlite3->sqlite, "PRAGMA auto_vacuum = 1;", NULL, NULL, &errmsg);
1638 if (ret != SQLITE_OK) {
1640 printf("lsqlite3 initializaion error: %s\n", errmsg);
1647 ret = sqlite3_exec(lsqlite3->sqlite, "PRAGMA synchronous = OFF;", NULL, NULL, &errmsg);
1648 if (ret != SQLITE_OK) {
1650 printf("lsqlite3 initializaion error: %s\n", errmsg);
1658 /* Establish a busy timeout of 30 seconds */
1659 if ((ret = sqlite3_busy_timeout(lsqlite3->sqlite,
1660 30000)) != SQLITE_OK) {
1664 /* Create a function, callable from sql, to increment a tree_key */
1666 sqlite3_create_function(lsqlite3->sqlite,/* handle */
1667 "base160_next", /* function name */
1668 1, /* number of args */
1669 SQLITE_ANY, /* preferred text type */
1670 NULL, /* user data */
1671 base160next_sql, /* called func */
1672 NULL, /* step func */
1673 NULL /* final func */
1678 /* Create a function, callable from sql, to convert int to base160 */
1680 sqlite3_create_function(lsqlite3->sqlite,/* handle */
1681 "base160", /* function name */
1682 1, /* number of args */
1683 SQLITE_ANY, /* preferred text type */
1684 NULL, /* user data */
1685 base160_sql, /* called func */
1686 NULL, /* step func */
1687 NULL /* final func */
1692 /* Create a function, callable from sql, to perform various comparisons */
1694 sqlite3_create_function(lsqlite3->sqlite, /* handle */
1695 "ldap_compare", /* function name */
1696 4, /* number of args */
1697 SQLITE_ANY, /* preferred text type */
1698 ldb , /* user data */
1699 lsqlite3_compare, /* called func */
1700 NULL, /* step func */
1701 NULL /* final func */
1706 /* Begin a transaction */
1707 ret = sqlite3_exec(lsqlite3->sqlite, "BEGIN EXCLUSIVE;", NULL, NULL, &errmsg);
1708 if (ret != SQLITE_OK) {
1710 printf("lsqlite3: initialization error: %s\n", errmsg);
1717 /* Determine if this is a new database. No tables means it is. */
1718 if (query_int(lsqlite3,
1721 " FROM sqlite_master\n"
1722 " WHERE type = 'table';") != 0) {
1726 if (queryInt == 0) {
1728 * Create the database schema
1730 ret = sqlite3_exec(lsqlite3->sqlite, schema, NULL, NULL, &errmsg);
1731 if (ret != SQLITE_OK) {
1733 printf("lsqlite3 initializaion error: %s\n", errmsg);
1740 * Ensure that the database we opened is one of ours
1742 if (query_int(lsqlite3,
1745 " (SELECT COUNT(*) = 2"
1746 " FROM sqlite_master "
1747 " WHERE type = 'table' "
1751 " 'ldb_object_classes' "
1757 " WHERE database_type = 'LDB' "
1758 " AND version = '1.0'"
1762 /* It's not one that we created. See ya! */
1767 /* Commit the transaction */
1768 ret = sqlite3_exec(lsqlite3->sqlite, "COMMIT;", NULL, NULL, &errmsg);
1769 if (ret != SQLITE_OK) {
1771 printf("lsqlite3: iniialization error: %s\n", errmsg);
1780 if (rollback) lsqlite3_safe_rollback(lsqlite3->sqlite);
1781 sqlite3_close(lsqlite3->sqlite);
1788 struct lsqlite3_private *lsqlite3 = p;
1790 if (lsqlite3->sqlite) {
1791 sqlite3_close(lsqlite3->sqlite);
1799 * Table of operations for the sqlite3 backend
1801 static const struct ldb_module_ops lsqlite3_ops = {
1803 .search = lsqlite3_search,
1804 .search_bytree = lsqlite3_search_bytree,
1805 .add_record = lsqlite3_add,
1806 .modify_record = lsqlite3_modify,
1807 .delete_record = lsqlite3_delete,
1808 .rename_record = lsqlite3_rename,
1809 .named_lock = lsqlite3_lock,
1810 .named_unlock = lsqlite3_unlock,
1811 .errstring = lsqlite3_errstring
1815 * connect to the database
1817 int lsqlite3_connect(struct ldb_context *ldb,
1820 const char *options[])
1824 struct lsqlite3_private * lsqlite3 = NULL;
1826 lsqlite3 = talloc(ldb, struct lsqlite3_private);
1831 lsqlite3->sqlite = NULL;
1832 lsqlite3->options = NULL;
1834 ret = initialize(lsqlite3, ldb, url);
1835 if (ret != SQLITE_OK) {
1839 talloc_set_destructor(lsqlite3, destructor);
1841 ldb->modules = talloc(ldb, struct ldb_module);
1842 if (!ldb->modules) {
1845 ldb->modules->ldb = ldb;
1846 ldb->modules->prev = ldb->modules->next = NULL;
1847 ldb->modules->private_data = lsqlite3;
1848 ldb->modules->ops = &lsqlite3_ops;
1852 * take a copy of the options array, so we don't have to rely
1853 * on the caller keeping it around (it might be dynamic)
1855 for (i=0;options[i];i++) ;
1857 lsqlite3->options = talloc_array(lsqlite3, char *, i+1);
1858 if (!lsqlite3->options) {
1862 for (i=0;options[i];i++) {
1864 lsqlite3->options[i+1] = NULL;
1865 lsqlite3->options[i] =
1866 talloc_strdup(lsqlite3->options, options[i]);
1867 if (!lsqlite3->options[i]) {
1876 if (lsqlite3->sqlite != NULL) {
1877 (void) sqlite3_close(lsqlite3->sqlite);
1879 talloc_free(lsqlite3);