r19430: merge recent ldb changes from Samba4. This includes memory leak fixes
[Samba/bb.git] / source / lib / ldb / ldb_sqlite3 / ldb_sqlite3.c
blob8dd25db1d6c628db4948e5d9578579dd447e7d13
1 /*
2 ldb database library
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
9 ** under the LGPL
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
27 * Name: ldb
29 * Component: ldb sqlite3 backend
31 * Description: core files for SQLITE3 backend
33 * Author: Derrell Lipman (based on Andrew Tridgell's LDAP backend)
36 #include "includes.h"
37 #include "ldb/include/includes.h"
39 #include <sqlite3.h>
41 struct lsqlite3_private {
42 int trans_count;
43 char **options;
44 sqlite3 *sqlite;
47 struct lsql_context {
48 struct ldb_module *module;
50 /* search stuff */
51 long long current_eid;
52 const char * const * attrs;
53 struct ldb_reply *ares;
55 /* async stuff */
56 void *context;
57 int (*callback)(struct ldb_context *, void *, struct ldb_reply *);
60 static struct ldb_handle *init_handle(struct lsqlite3_private *lsqlite3, struct ldb_module *module,
61 void *context,
62 int (*callback)(struct ldb_context *, void *, struct ldb_reply *))
64 struct lsql_context *ac;
65 struct ldb_handle *h;
67 h = talloc_zero(lsqlite3, struct ldb_handle);
68 if (h == NULL) {
69 ldb_set_errstring(module->ldb, "Out of Memory");
70 return NULL;
73 h->module = module;
75 ac = talloc(h, struct lsql_context);
76 if (ac == NULL) {
77 ldb_set_errstring(module->ldb, "Out of Memory");
78 talloc_free(h);
79 return NULL;
82 h->private_data = (void *)ac;
84 h->state = LDB_ASYNC_INIT;
85 h->status = LDB_SUCCESS;
87 ac->module = module;
88 ac->context = context;
89 ac->callback = callback;
91 return h;
95 * Macros used throughout
98 #ifndef FALSE
99 # define FALSE (0)
100 # define TRUE (! FALSE)
101 #endif
103 #define RESULT_ATTR_TABLE "temp_result_attrs"
105 //#define TEMPTAB /* for testing, create non-temporary table */
106 #define TEMPTAB "TEMPORARY"
109 * Static variables
111 sqlite3_stmt * stmtGetEID = NULL;
113 static char *lsqlite3_tprintf(TALLOC_CTX *mem_ctx, const char *fmt, ...)
115 char *str, *ret;
116 va_list ap;
118 va_start(ap, fmt);
119 str = sqlite3_vmprintf(fmt, ap);
120 va_end(ap);
122 if (str == NULL) return NULL;
124 ret = talloc_strdup(mem_ctx, str);
125 if (ret == NULL) {
126 sqlite3_free(str);
127 return NULL;
130 sqlite3_free(str);
131 return ret;
134 static char base160tab[161] = {
135 48 ,49 ,50 ,51 ,52 ,53 ,54 ,55 ,56 ,57 , /* 0-9 */
136 58 ,59 ,65 ,66 ,67 ,68 ,69 ,70 ,71 ,72 , /* : ; A-H */
137 73 ,74 ,75 ,76 ,77 ,78 ,79 ,80 ,81 ,82 , /* I-R */
138 83 ,84 ,85 ,86 ,87 ,88 ,89 ,90 ,97 ,98 , /* S-Z , a-b */
139 99 ,100,101,102,103,104,105,106,107,108, /* c-l */
140 109,110,111,112,113,114,115,116,117,118, /* m-v */
141 119,120,121,122,160,161,162,163,164,165, /* w-z, latin1 */
142 166,167,168,169,170,171,172,173,174,175, /* latin1 */
143 176,177,178,179,180,181,182,183,184,185, /* latin1 */
144 186,187,188,189,190,191,192,193,194,195, /* latin1 */
145 196,197,198,199,200,201,202,203,204,205, /* latin1 */
146 206,207,208,209,210,211,212,213,214,215, /* latin1 */
147 216,217,218,219,220,221,222,223,224,225, /* latin1 */
148 226,227,228,229,230,231,232,233,234,235, /* latin1 */
149 236,237,238,239,240,241,242,243,244,245, /* latin1 */
150 246,247,248,249,250,251,252,253,254,255, /* latin1 */
151 '\0'
156 * base160()
158 * Convert an unsigned long integer into a base160 representation of the
159 * number.
161 * Parameters:
162 * val --
163 * value to be converted
165 * result --
166 * character array, 5 bytes long, into which the base160 representation
167 * will be placed. The result will be a four-digit representation of the
168 * number (with leading zeros prepended as necessary), and null
169 * terminated.
171 * Returns:
172 * Nothing
174 static void
175 base160_sql(sqlite3_context * hContext,
176 int argc,
177 sqlite3_value ** argv)
179 int i;
180 long long val;
181 char result[5];
183 val = sqlite3_value_int64(argv[0]);
185 for (i = 3; i >= 0; i--) {
187 result[i] = base160tab[val % 160];
188 val /= 160;
191 result[4] = '\0';
193 sqlite3_result_text(hContext, result, -1, SQLITE_TRANSIENT);
198 * base160next_sql()
200 * This function enhances sqlite by adding a "base160_next()" function which is
201 * accessible via queries.
203 * Retrieve the next-greater number in the base160 sequence for the terminal
204 * tree node (the last four digits). Only one tree level (four digits) is
205 * operated on.
207 * Input:
208 * A character string: either an empty string (in which case no operation is
209 * performed), or a string of base160 digits with a length of a multiple of
210 * four digits.
212 * Output:
213 * Upon return, the trailing four digits (one tree level) will have been
214 * incremented by 1.
216 static void
217 base160next_sql(sqlite3_context * hContext,
218 int argc,
219 sqlite3_value ** argv)
221 int i;
222 int len;
223 char * pTab;
224 char * pBase160 = strdup((const char *)sqlite3_value_text(argv[0]));
225 char * pStart = pBase160;
228 * We need a minimum of four digits, and we will always get a multiple
229 * of four digits.
231 if (pBase160 != NULL &&
232 (len = strlen(pBase160)) >= 4 &&
233 len % 4 == 0) {
235 if (pBase160 == NULL) {
237 sqlite3_result_null(hContext);
238 return;
241 pBase160 += strlen(pBase160) - 1;
243 /* We only carry through four digits: one level in the tree */
244 for (i = 0; i < 4; i++) {
246 /* What base160 value does this digit have? */
247 pTab = strchr(base160tab, *pBase160);
249 /* Is there a carry? */
250 if (pTab < base160tab + sizeof(base160tab) - 1) {
253 * Nope. Just increment this value and we're
254 * done.
256 *pBase160 = *++pTab;
257 break;
258 } else {
261 * There's a carry. This value gets
262 * base160tab[0], we decrement the buffer
263 * pointer to get the next higher-order digit,
264 * and continue in the loop.
266 *pBase160-- = base160tab[0];
270 sqlite3_result_text(hContext,
271 pStart,
272 strlen(pStart),
273 free);
274 } else {
275 sqlite3_result_value(hContext, argv[0]);
276 if (pBase160 != NULL) {
277 free(pBase160);
282 static char *parsetree_to_sql(struct ldb_module *module,
283 void *mem_ctx,
284 const struct ldb_parse_tree *t)
286 const struct ldb_attrib_handler *h;
287 struct ldb_val value, subval;
288 char *wild_card_string;
289 char *child, *tmp;
290 char *ret = NULL;
291 char *attr;
292 int i;
295 switch(t->operation) {
296 case LDB_OP_AND:
298 tmp = parsetree_to_sql(module, mem_ctx, t->u.list.elements[0]);
299 if (tmp == NULL) return NULL;
301 for (i = 1; i < t->u.list.num_elements; i++) {
303 child = parsetree_to_sql(module, mem_ctx, t->u.list.elements[i]);
304 if (child == NULL) return NULL;
306 tmp = talloc_asprintf_append(tmp, " INTERSECT %s ", child);
307 if (tmp == NULL) return NULL;
310 ret = talloc_asprintf(mem_ctx, "SELECT * FROM ( %s )\n", tmp);
312 return ret;
314 case LDB_OP_OR:
316 tmp = parsetree_to_sql(module, mem_ctx, t->u.list.elements[0]);
317 if (tmp == NULL) return NULL;
319 for (i = 1; i < t->u.list.num_elements; i++) {
321 child = parsetree_to_sql(module, mem_ctx, t->u.list.elements[i]);
322 if (child == NULL) return NULL;
324 tmp = talloc_asprintf_append(tmp, " UNION %s ", child);
325 if (tmp == NULL) return NULL;
328 return talloc_asprintf(mem_ctx, "SELECT * FROM ( %s ) ", tmp);
330 case LDB_OP_NOT:
332 child = parsetree_to_sql(module, mem_ctx, t->u.isnot.child);
333 if (child == NULL) return NULL;
335 return talloc_asprintf(mem_ctx,
336 "SELECT eid FROM ldb_entry "
337 "WHERE eid NOT IN ( %s ) ", child);
339 case LDB_OP_EQUALITY:
341 * For simple searches, we want to retrieve the list of EIDs that
342 * match the criteria.
344 attr = ldb_attr_casefold(mem_ctx, t->u.equality.attr);
345 if (attr == NULL) return NULL;
346 h = ldb_attrib_handler(module->ldb, attr);
348 /* Get a canonicalised copy of the data */
349 h->canonicalise_fn(module->ldb, mem_ctx, &(t->u.equality.value), &value);
350 if (value.data == NULL) {
351 return NULL;
354 if (strcasecmp(t->u.equality.attr, "objectclass") == 0) {
356 * For object classes, we want to search for all objectclasses
357 * that are subclasses as well.
359 return lsqlite3_tprintf(mem_ctx,
360 "SELECT eid FROM ldb_attribute_values\n"
361 "WHERE norm_attr_name = 'OBJECTCLASS' "
362 "AND norm_attr_value IN\n"
363 " (SELECT class_name FROM ldb_object_classes\n"
364 " WHERE tree_key GLOB\n"
365 " (SELECT tree_key FROM ldb_object_classes\n"
366 " WHERE class_name = '%q'\n"
367 " ) || '*'\n"
368 " )\n", value.data);
370 } else if (strcasecmp(t->u.equality.attr, "dn") == 0) {
371 /* DN query is a special ldb case */
372 char *cdn = ldb_dn_linearize_casefold(module->ldb,
373 ldb_dn_explode(module->ldb,
374 (const char *)value.data));
376 return lsqlite3_tprintf(mem_ctx,
377 "SELECT eid FROM ldb_entry "
378 "WHERE norm_dn = '%q'", cdn);
380 } else {
381 /* A normal query. */
382 return lsqlite3_tprintf(mem_ctx,
383 "SELECT eid FROM ldb_attribute_values "
384 "WHERE norm_attr_name = '%q' "
385 "AND norm_attr_value = '%q'",
386 attr,
387 value.data);
391 case LDB_OP_SUBSTRING:
393 wild_card_string = talloc_strdup(mem_ctx,
394 (t->u.substring.start_with_wildcard)?"*":"");
395 if (wild_card_string == NULL) return NULL;
397 for (i = 0; t->u.substring.chunks[i]; i++) {
398 wild_card_string = talloc_asprintf_append(wild_card_string, "%s*",
399 t->u.substring.chunks[i]->data);
400 if (wild_card_string == NULL) return NULL;
403 if ( ! t->u.substring.end_with_wildcard ) {
404 /* remove last wildcard */
405 wild_card_string[strlen(wild_card_string) - 1] = '\0';
408 attr = ldb_attr_casefold(mem_ctx, t->u.substring.attr);
409 if (attr == NULL) return NULL;
410 h = ldb_attrib_handler(module->ldb, attr);
412 subval.data = (void *)wild_card_string;
413 subval.length = strlen(wild_card_string) + 1;
415 /* Get a canonicalised copy of the data */
416 h->canonicalise_fn(module->ldb, mem_ctx, &(subval), &value);
417 if (value.data == NULL) {
418 return NULL;
421 return lsqlite3_tprintf(mem_ctx,
422 "SELECT eid FROM ldb_attribute_values "
423 "WHERE norm_attr_name = '%q' "
424 "AND norm_attr_value GLOB '%q'",
425 attr,
426 value.data);
428 case LDB_OP_GREATER:
429 attr = ldb_attr_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) {
436 return 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') ",
443 attr,
444 value.data,
445 attr);
447 case LDB_OP_LESS:
448 attr = ldb_attr_casefold(mem_ctx, t->u.equality.attr);
449 if (attr == NULL) return NULL;
450 h = ldb_attrib_handler(module->ldb, attr);
452 /* Get a canonicalised copy of the data */
453 h->canonicalise_fn(module->ldb, mem_ctx, &(t->u.equality.value), &value);
454 if (value.data == NULL) {
455 return NULL;
458 return lsqlite3_tprintf(mem_ctx,
459 "SELECT eid FROM ldb_attribute_values "
460 "WHERE norm_attr_name = '%q' "
461 "AND ldap_compare(norm_attr_value, '<=', '%q', '%q') ",
462 attr,
463 value.data,
464 attr);
466 case LDB_OP_PRESENT:
467 if (strcasecmp(t->u.present.attr, "dn") == 0) {
468 return talloc_strdup(mem_ctx, "SELECT eid FROM ldb_entry");
471 attr = ldb_attr_casefold(mem_ctx, t->u.present.attr);
472 if (attr == NULL) return NULL;
474 return lsqlite3_tprintf(mem_ctx,
475 "SELECT eid FROM ldb_attribute_values "
476 "WHERE norm_attr_name = '%q' ",
477 attr);
479 case LDB_OP_APPROX:
480 attr = ldb_attr_casefold(mem_ctx, t->u.equality.attr);
481 if (attr == NULL) return NULL;
482 h = ldb_attrib_handler(module->ldb, attr);
484 /* Get a canonicalised copy of the data */
485 h->canonicalise_fn(module->ldb, mem_ctx, &(t->u.equality.value), &value);
486 if (value.data == NULL) {
487 return NULL;
490 return lsqlite3_tprintf(mem_ctx,
491 "SELECT eid FROM ldb_attribute_values "
492 "WHERE norm_attr_name = '%q' "
493 "AND ldap_compare(norm_attr_value, '~%', 'q', '%q') ",
494 attr,
495 value.data,
496 attr);
498 case LDB_OP_EXTENDED:
499 #warning "work out how to handle bitops"
500 return NULL;
502 default:
503 break;
506 /* should never occur */
507 abort();
508 return NULL;
512 * query_int()
514 * This function is used for the common case of queries that return a single
515 * integer value.
517 * NOTE: If more than one value is returned by the query, all but the first
518 * one will be ignored.
520 static int
521 query_int(const struct lsqlite3_private * lsqlite3,
522 long long * pRet,
523 const char * pSql,
524 ...)
526 int ret;
527 int bLoop;
528 char * p;
529 sqlite3_stmt * pStmt;
530 va_list args;
532 /* Begin access to variable argument list */
533 va_start(args, pSql);
535 /* Format the query */
536 if ((p = sqlite3_vmprintf(pSql, args)) == NULL) {
537 return SQLITE_NOMEM;
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,
551 &pStmt,
552 NULL)) == SQLITE_SCHEMA) {
553 if (stmtGetEID != NULL) {
554 sqlite3_finalize(stmtGetEID);
555 stmtGetEID = NULL;
557 continue;
558 } else if (ret != SQLITE_OK) {
559 break;
562 /* One row expected */
563 if ((ret = sqlite3_step(pStmt)) == SQLITE_SCHEMA) {
564 if (stmtGetEID != NULL) {
565 sqlite3_finalize(stmtGetEID);
566 stmtGetEID = NULL;
568 (void) sqlite3_finalize(pStmt);
569 continue;
570 } else if (ret != SQLITE_ROW) {
571 (void) sqlite3_finalize(pStmt);
572 break;
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);
582 stmtGetEID = NULL;
584 continue;
585 } else if (ret != SQLITE_OK) {
586 (void) sqlite3_finalize(pStmt);
587 break;
591 * Normal condition is only one time through loop. Loop is
592 * rerun in error conditions, via "continue", above.
594 bLoop = FALSE;
597 /* All done with variable argument list */
598 va_end(args);
601 /* Free the memory we allocated for our query string */
602 sqlite3_free(p);
604 return ret;
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 char *val = (const char *)sqlite3_value_text(argv[0]);
620 const char *func = (const char *)sqlite3_value_text(argv[1]);
621 const char *cmp = (const char *)sqlite3_value_text(argv[2]);
622 const char *attr = (const char *)sqlite3_value_text(argv[3]);
623 const struct ldb_attrib_handler *h;
624 struct ldb_val valX;
625 struct ldb_val valY;
626 int ret;
628 switch (func[0]) {
629 /* greater */
630 case '>': /* >= */
631 h = ldb_attrib_handler(ldb, attr);
632 valX.data = (void *)cmp;
633 valX.length = strlen(cmp);
634 valY.data = (void *)val;
635 valY.length = strlen(val);
636 ret = h->comparison_fn(ldb, ldb, &valY, &valX);
637 if (ret >= 0)
638 sqlite3_result_int(ctx, 1);
639 else
640 sqlite3_result_int(ctx, 0);
641 return;
643 /* lesser */
644 case '<': /* <= */
645 h = ldb_attrib_handler(ldb, attr);
646 valX.data = (void *)cmp;
647 valX.length = strlen(cmp);
648 valY.data = (void *)val;
649 valY.length = strlen(val);
650 ret = h->comparison_fn(ldb, ldb, &valY, &valX);
651 if (ret <= 0)
652 sqlite3_result_int(ctx, 1);
653 else
654 sqlite3_result_int(ctx, 0);
655 return;
657 /* approx */
658 case '~':
659 /* TODO */
660 sqlite3_result_int(ctx, 0);
661 return;
663 /* bitops */
664 case ':':
665 /* TODO */
666 sqlite3_result_int(ctx, 0);
667 return;
669 default:
670 break;
673 sqlite3_result_error(ctx, "Value must start with a special operation char (<>~:)!", -1);
674 return;
678 /* rename a record */
679 static int lsqlite3_safe_rollback(sqlite3 *sqlite)
681 char *errmsg;
682 int ret;
684 /* execute */
685 ret = sqlite3_exec(sqlite, "ROLLBACK;", NULL, NULL, &errmsg);
686 if (ret != SQLITE_OK) {
687 if (errmsg) {
688 printf("lsqlite3_safe_rollback: Error: %s\n", errmsg);
689 free(errmsg);
691 return -1;
694 return 0;
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]);
706 return SQLITE_OK;
710 * add a single set of ldap message values to a ldb_message
712 static int lsqlite3_search_callback(void *result, int col_num, char **cols, char **names)
714 struct ldb_handle *handle = talloc_get_type(result, struct ldb_handle);
715 struct lsql_context *ac = talloc_get_type(handle->private_data, struct lsql_context);
716 struct ldb_message *msg;
717 long long eid;
718 int i;
720 /* eid, dn, attr_name, attr_value */
721 if (col_num != 4)
722 return SQLITE_ABORT;
724 eid = atoll(cols[0]);
726 if (eid != ac->current_eid) { /* here begin a new entry */
728 /* call the async callback for the last entry
729 * except the first time */
730 if (ac->current_eid != 0) {
731 ac->ares->message = ldb_msg_canonicalize(ac->module->ldb, ac->ares->message);
732 if (ac->ares->message == NULL)
733 return SQLITE_ABORT;
735 handle->status = ac->callback(ac->module->ldb, ac->context, ac->ares);
736 if (handle->status != LDB_SUCCESS)
737 return SQLITE_ABORT;
740 /* start over */
741 ac->ares = talloc_zero(ac, struct ldb_reply);
742 if (!ac->ares)
743 return SQLITE_ABORT;
745 ac->ares->message = ldb_msg_new(ac->ares);
746 if (!ac->ares->message)
747 return SQLITE_ABORT;
749 ac->ares->type = LDB_REPLY_ENTRY;
750 ac->current_eid = eid;
753 msg = ac->ares->message;
755 if (msg->dn == NULL) {
756 msg->dn = ldb_dn_explode(msg, cols[1]);
757 if (msg->dn == NULL)
758 return SQLITE_ABORT;
761 if (ac->attrs) {
762 int found = 0;
763 for (i = 0; ac->attrs[i]; i++) {
764 if (strcasecmp(cols[2], ac->attrs[i]) == 0) {
765 found = 1;
766 break;
769 if (!found) return SQLITE_OK;
772 if (ldb_msg_add_string(msg, cols[2], cols[3]) != 0) {
773 return SQLITE_ABORT;
776 return SQLITE_OK;
781 * lsqlite3_get_eid()
782 * lsqlite3_get_eid_ndn()
784 * These functions are used for the very common case of retrieving an EID value
785 * given a (normalized) DN.
788 static long long lsqlite3_get_eid_ndn(sqlite3 *sqlite, void *mem_ctx, const char *norm_dn)
790 char *errmsg;
791 char *query;
792 long long eid = -1;
793 long long ret;
795 /* get object eid */
796 query = lsqlite3_tprintf(mem_ctx, "SELECT eid "
797 "FROM ldb_entry "
798 "WHERE norm_dn = '%q';", norm_dn);
799 if (query == NULL) return -1;
801 ret = sqlite3_exec(sqlite, query, lsqlite3_eid_callback, &eid, &errmsg);
802 if (ret != SQLITE_OK) {
803 if (errmsg) {
804 printf("lsqlite3_get_eid: Fatal Error: %s\n", errmsg);
805 free(errmsg);
807 return -1;
810 return eid;
813 static long long lsqlite3_get_eid(struct ldb_module *module, const struct ldb_dn *dn)
815 TALLOC_CTX *local_ctx;
816 struct lsqlite3_private *lsqlite3 = module->private_data;
817 long long eid = -1;
818 char *cdn;
820 /* ignore ltdb specials */
821 if (ldb_dn_is_special(dn)) {
822 return -1;
825 /* create a local ctx */
826 local_ctx = talloc_named(lsqlite3, 0, "lsqlite3_get_eid local context");
827 if (local_ctx == NULL) {
828 return -1;
831 cdn = ldb_dn_linearize(local_ctx, ldb_dn_casefold(module->ldb, dn));
832 if (!cdn) goto done;
834 eid = lsqlite3_get_eid_ndn(lsqlite3->sqlite, local_ctx, cdn);
836 done:
837 talloc_free(local_ctx);
838 return eid;
842 * Interface functions referenced by lsqlite3_ops
845 static int lsql_search_sync_callback(struct ldb_context *ldb, void *context, struct ldb_reply *ares)
847 struct ldb_result *res = NULL;
849 if (!context) {
850 ldb_set_errstring(ldb, "NULL Context in callback");
851 goto error;
854 res = *((struct ldb_result **)context);
856 if (!res || !ares) {
857 goto error;
860 if (ares->type == LDB_REPLY_ENTRY) {
861 res->msgs = talloc_realloc(res, res->msgs, struct ldb_message *, res->count + 2);
862 if (! res->msgs) {
863 goto error;
866 res->msgs[res->count + 1] = NULL;
868 res->msgs[res->count] = talloc_move(res->msgs, &ares->message);
869 res->count++;
870 } else {
871 ldb_debug(ldb, LDB_DEBUG_ERROR, "unrecognized async reply in ltdb_search_sync_callback!\n");
872 goto error;
875 talloc_free(ares);
876 return LDB_SUCCESS;
878 error:
879 if (ares) talloc_free(ares);
880 if (res) talloc_free(res);
881 if (context) *((struct ldb_result **)context) = NULL;
882 return LDB_ERR_OPERATIONS_ERROR;
885 /* search for matching records, by tree */
886 int lsql_search_async(struct ldb_module *module, const struct ldb_dn *base,
887 enum ldb_scope scope, struct ldb_parse_tree *tree,
888 const char * const *attrs,
889 void *context,
890 int (*callback)(struct ldb_context *, void *, struct ldb_reply *),
891 struct ldb_handle **handle)
893 struct lsqlite3_private *lsqlite3 = talloc_get_type(module->private_data, struct lsqlite3_private);
894 struct lsql_context *lsql_ac;
895 char *norm_basedn;
896 char *sqlfilter;
897 char *errmsg;
898 char *query = NULL;
899 int ret;
901 *handle = init_handle(lsqlite3, module, context, callback);
902 if (*handle == NULL) {
903 talloc_free(*handle);
904 return LDB_ERR_OPERATIONS_ERROR;
907 lsql_ac = talloc_get_type((*handle)->private_data, struct lsql_context);
909 if (base) {
910 norm_basedn = ldb_dn_linearize(lsql_ac, ldb_dn_casefold(module->ldb, base));
911 if (norm_basedn == NULL) {
912 ret = LDB_ERR_INVALID_DN_SYNTAX;
913 goto failed;
915 } else norm_basedn = talloc_strdup(lsql_ac, "");
917 if (*norm_basedn == '\0' &&
918 (scope == LDB_SCOPE_BASE || scope == LDB_SCOPE_ONELEVEL)) {
919 ret = LDB_ERR_UNWILLING_TO_PERFORM;
920 goto failed;
923 /* Convert filter into a series of SQL conditions (constraints) */
924 sqlfilter = parsetree_to_sql(module, lsql_ac, tree);
926 switch(scope) {
927 case LDB_SCOPE_DEFAULT:
928 case LDB_SCOPE_SUBTREE:
929 if (*norm_basedn != '\0') {
930 query = lsqlite3_tprintf(lsql_ac,
931 "SELECT entry.eid,\n"
932 " entry.dn,\n"
933 " av.attr_name,\n"
934 " av.attr_value\n"
935 " FROM ldb_entry AS entry\n"
937 " LEFT OUTER JOIN ldb_attribute_values AS av\n"
938 " ON av.eid = entry.eid\n"
940 " WHERE entry.eid IN\n"
941 " (SELECT DISTINCT ldb_entry.eid\n"
942 " FROM ldb_entry\n"
943 " WHERE (ldb_entry.norm_dn GLOB('*,%q')\n"
944 " OR ldb_entry.norm_dn = '%q')\n"
945 " AND ldb_entry.eid IN\n"
946 " (%s)\n"
947 " )\n"
949 " ORDER BY entry.eid ASC;",
950 norm_basedn,
951 norm_basedn,
952 sqlfilter);
953 } else {
954 query = lsqlite3_tprintf(lsql_ac,
955 "SELECT entry.eid,\n"
956 " entry.dn,\n"
957 " av.attr_name,\n"
958 " av.attr_value\n"
959 " FROM ldb_entry AS entry\n"
961 " LEFT OUTER JOIN ldb_attribute_values AS av\n"
962 " ON av.eid = entry.eid\n"
964 " WHERE entry.eid IN\n"
965 " (SELECT DISTINCT ldb_entry.eid\n"
966 " FROM ldb_entry\n"
967 " WHERE ldb_entry.eid IN\n"
968 " (%s)\n"
969 " )\n"
971 " ORDER BY entry.eid ASC;",
972 sqlfilter);
975 break;
977 case LDB_SCOPE_BASE:
978 query = lsqlite3_tprintf(lsql_ac,
979 "SELECT entry.eid,\n"
980 " entry.dn,\n"
981 " av.attr_name,\n"
982 " av.attr_value\n"
983 " FROM ldb_entry AS entry\n"
985 " LEFT OUTER JOIN ldb_attribute_values AS av\n"
986 " ON av.eid = entry.eid\n"
988 " WHERE entry.eid IN\n"
989 " (SELECT DISTINCT ldb_entry.eid\n"
990 " FROM ldb_entry\n"
991 " WHERE ldb_entry.norm_dn = '%q'\n"
992 " AND ldb_entry.eid IN\n"
993 " (%s)\n"
994 " )\n"
996 " ORDER BY entry.eid ASC;",
997 norm_basedn,
998 sqlfilter);
999 break;
1001 case LDB_SCOPE_ONELEVEL:
1002 query = lsqlite3_tprintf(lsql_ac,
1003 "SELECT entry.eid,\n"
1004 " entry.dn,\n"
1005 " av.attr_name,\n"
1006 " av.attr_value\n"
1007 " FROM ldb_entry AS entry\n"
1009 " LEFT OUTER JOIN ldb_attribute_values AS av\n"
1010 " ON av.eid = entry.eid\n"
1012 " WHERE entry.eid IN\n"
1013 " (SELECT DISTINCT ldb_entry.eid\n"
1014 " FROM ldb_entry\n"
1015 " WHERE norm_dn GLOB('*,%q')\n"
1016 " AND NOT norm_dn GLOB('*,*,%q')\n"
1017 " AND ldb_entry.eid IN\n(%s)\n"
1018 " )\n"
1020 " ORDER BY entry.eid ASC;",
1021 norm_basedn,
1022 norm_basedn,
1023 sqlfilter);
1024 break;
1027 if (query == NULL) {
1028 goto failed;
1031 /* * /
1032 printf ("%s\n", query);
1033 / * */
1035 lsql_ac->current_eid = 0;
1036 lsql_ac->attrs = attrs;
1037 lsql_ac->ares = NULL;
1039 (*handle)->state = LDB_ASYNC_PENDING;
1041 ret = sqlite3_exec(lsqlite3->sqlite, query, lsqlite3_search_callback, *handle, &errmsg);
1042 if (ret != SQLITE_OK) {
1043 if (errmsg) {
1044 ldb_set_errstring(module->ldb, errmsg);
1045 free(errmsg);
1047 goto failed;
1050 /* complete the last message if any */
1051 if (lsql_ac->ares) {
1052 lsql_ac->ares->message = ldb_msg_canonicalize(module->ldb, lsql_ac->ares->message);
1053 if (lsql_ac->ares->message == NULL)
1054 goto failed;
1056 (*handle)->status = lsql_ac->callback(module->ldb, lsql_ac->context, lsql_ac->ares);
1057 if ((*handle)->status != LDB_SUCCESS)
1058 goto failed;
1061 (*handle)->state = LDB_ASYNC_DONE;
1063 return LDB_SUCCESS;
1065 failed:
1066 talloc_free(*handle);
1067 return LDB_ERR_OPERATIONS_ERROR;
1070 static int lsql_search_bytree(struct ldb_module * module, const struct ldb_dn* base,
1071 enum ldb_scope scope, struct ldb_parse_tree * tree,
1072 const char * const * attrs, struct ldb_result ** res)
1074 struct ldb_handle *handle;
1075 int ret;
1077 *res = talloc_zero(module, struct ldb_result);
1078 if (! *res) {
1079 return LDB_ERR_OPERATIONS_ERROR;
1082 ret = lsql_search_async(module, base, scope, tree, attrs,
1083 res, &lsql_search_sync_callback,
1084 &handle);
1086 if (ret == LDB_SUCCESS) {
1087 ret = ldb_wait(handle, LDB_WAIT_ALL);
1088 talloc_free(handle);
1091 if (ret != LDB_SUCCESS) {
1092 talloc_free(*res);
1095 return ret;
1098 /* add a record */
1099 static int lsql_add_async(struct ldb_module *module, struct ldb_message *msg,
1100 void *context,
1101 int (*callback)(struct ldb_context *, void *, struct ldb_reply *),
1102 struct ldb_handle **handle)
1104 struct lsqlite3_private *lsqlite3 = talloc_get_type(module->private_data, struct lsqlite3_private);
1105 struct lsql_context *lsql_ac;
1106 long long eid;
1107 char *dn, *ndn;
1108 char *errmsg;
1109 char *query;
1110 int i;
1111 int ret = LDB_ERR_OPERATIONS_ERROR;
1113 *handle = init_handle(lsqlite3, module, context, callback);
1114 if (*handle == NULL) {
1115 goto failed;
1117 lsql_ac = talloc_get_type((*handle)->private_data, struct lsql_context);
1118 (*handle)->state = LDB_ASYNC_DONE;
1119 (*handle)->status = LDB_SUCCESS;
1121 /* See if this is an ltdb special */
1122 if (ldb_dn_is_special(msg->dn)) {
1123 struct ldb_dn *c;
1125 c = ldb_dn_explode(lsql_ac, "@SUBCLASSES");
1126 if (ldb_dn_compare(module->ldb, msg->dn, c) == 0) {
1127 #warning "insert subclasses into object class tree"
1128 ret = LDB_ERR_UNWILLING_TO_PERFORM;
1129 goto failed;
1133 c = ldb_dn_explode(local_ctx, "@INDEXLIST");
1134 if (ldb_dn_compare(module->ldb, msg->dn, c) == 0) {
1135 #warning "should we handle indexes somehow ?"
1136 goto failed;
1139 /* Others are implicitly ignored */
1140 return LDB_SUCCESS;
1143 /* create linearized and normalized dns */
1144 dn = ldb_dn_linearize(lsql_ac, msg->dn);
1145 ndn = ldb_dn_linearize(lsql_ac, ldb_dn_casefold(module->ldb, msg->dn));
1146 if (dn == NULL || ndn == NULL) {
1147 ret = LDB_ERR_OTHER;
1148 goto failed;
1151 query = lsqlite3_tprintf(lsql_ac,
1152 /* Add new entry */
1153 "INSERT OR ABORT INTO ldb_entry "
1154 "('dn', 'norm_dn') "
1155 "VALUES ('%q', '%q');",
1156 dn, ndn);
1157 if (query == NULL) {
1158 ret = LDB_ERR_OTHER;
1159 goto failed;
1162 ret = sqlite3_exec(lsqlite3->sqlite, query, NULL, NULL, &errmsg);
1163 if (ret != SQLITE_OK) {
1164 if (errmsg) {
1165 ldb_set_errstring(module->ldb, errmsg);
1166 free(errmsg);
1168 ret = LDB_ERR_OTHER;
1169 goto failed;
1172 eid = lsqlite3_get_eid_ndn(lsqlite3->sqlite, lsql_ac, ndn);
1173 if (eid == -1) {
1174 ret = LDB_ERR_OTHER;
1175 goto failed;
1178 for (i = 0; i < msg->num_elements; i++) {
1179 const struct ldb_message_element *el = &msg->elements[i];
1180 const struct ldb_attrib_handler *h;
1181 char *attr;
1182 int j;
1184 /* Get a case-folded copy of the attribute name */
1185 attr = ldb_attr_casefold(lsql_ac, el->name);
1186 if (attr == NULL) {
1187 ret = LDB_ERR_OTHER;
1188 goto failed;
1191 h = ldb_attrib_handler(module->ldb, el->name);
1193 /* For each value of the specified attribute name... */
1194 for (j = 0; j < el->num_values; j++) {
1195 struct ldb_val value;
1196 char *insert;
1198 /* Get a canonicalised copy of the data */
1199 h->canonicalise_fn(module->ldb, lsql_ac, &(el->values[j]), &value);
1200 if (value.data == NULL) {
1201 ret = LDB_ERR_OTHER;
1202 goto failed;
1205 insert = lsqlite3_tprintf(lsql_ac,
1206 "INSERT OR ROLLBACK INTO ldb_attribute_values "
1207 "('eid', 'attr_name', 'norm_attr_name',"
1208 " 'attr_value', 'norm_attr_value') "
1209 "VALUES ('%lld', '%q', '%q', '%q', '%q');",
1210 eid, el->name, attr,
1211 el->values[j].data, value.data);
1212 if (insert == NULL) {
1213 ret = LDB_ERR_OTHER;
1214 goto failed;
1217 ret = sqlite3_exec(lsqlite3->sqlite, insert, NULL, NULL, &errmsg);
1218 if (ret != SQLITE_OK) {
1219 if (errmsg) {
1220 ldb_set_errstring(module->ldb, errmsg);
1221 free(errmsg);
1223 ret = LDB_ERR_OTHER;
1224 goto failed;
1229 if (lsql_ac->callback)
1230 (*handle)->status = lsql_ac->callback(module->ldb, lsql_ac->context, NULL);
1232 return LDB_SUCCESS;
1234 failed:
1235 talloc_free(*handle);
1236 return ret;
1239 static int lsql_add(struct ldb_module *module, const struct ldb_message *msg)
1241 struct ldb_handle *handle;
1242 int ret;
1244 ret = lsql_add_async(module, msg, NULL, NULL, &handle);
1246 if (ret != LDB_SUCCESS)
1247 return ret;
1249 ret = ldb_wait(handle, LDB_WAIT_ALL);
1251 talloc_free(handle);
1252 return ret;
1256 /* modify a record */
1257 static int lsql_modify_async(struct ldb_module *module, const struct ldb_message *msg,
1258 void *context,
1259 int (*callback)(struct ldb_context *, void *, struct ldb_reply *),
1260 struct ldb_handle **handle)
1262 struct lsqlite3_private *lsqlite3 = talloc_get_type(module->private_data, struct lsqlite3_private);
1263 struct lsql_context *lsql_ac;
1264 long long eid;
1265 char *errmsg;
1266 int i;
1267 int ret = LDB_ERR_OPERATIONS_ERROR;
1269 *handle = init_handle(lsqlite3, module, context, callback);
1270 if (*handle == NULL) {
1271 goto failed;
1273 lsql_ac = talloc_get_type((*handle)->private_data, struct lsql_context);
1274 (*handle)->state = LDB_ASYNC_DONE;
1275 (*handle)->status = LDB_SUCCESS;
1277 /* See if this is an ltdb special */
1278 if (ldb_dn_is_special(msg->dn)) {
1279 struct ldb_dn *c;
1281 c = ldb_dn_explode(lsql_ac, "@SUBCLASSES");
1282 if (ldb_dn_compare(module->ldb, msg->dn, c) == 0) {
1283 #warning "modify subclasses into object class tree"
1284 ret = LDB_ERR_UNWILLING_TO_PERFORM;
1285 goto failed;
1288 /* Others are implicitly ignored */
1289 return LDB_SUCCESS;
1292 eid = lsqlite3_get_eid(module, msg->dn);
1293 if (eid == -1) {
1294 ret = LDB_ERR_OTHER;
1295 goto failed;
1298 for (i = 0; i < msg->num_elements; i++) {
1299 const struct ldb_message_element *el = &msg->elements[i];
1300 const struct ldb_attrib_handler *h;
1301 int flags = el->flags & LDB_FLAG_MOD_MASK;
1302 char *attr;
1303 char *mod;
1304 int j;
1306 /* Get a case-folded copy of the attribute name */
1307 attr = ldb_attr_casefold(lsql_ac, el->name);
1308 if (attr == NULL) {
1309 ret = LDB_ERR_OTHER;
1310 goto failed;
1313 h = ldb_attrib_handler(module->ldb, el->name);
1315 switch (flags) {
1317 case LDB_FLAG_MOD_REPLACE:
1319 /* remove all attributes before adding the replacements */
1320 mod = lsqlite3_tprintf(lsql_ac,
1321 "DELETE FROM ldb_attribute_values "
1322 "WHERE eid = '%lld' "
1323 "AND norm_attr_name = '%q';",
1324 eid, attr);
1325 if (mod == NULL) {
1326 ret = LDB_ERR_OTHER;
1327 goto failed;
1330 ret = sqlite3_exec(lsqlite3->sqlite, mod, NULL, NULL, &errmsg);
1331 if (ret != SQLITE_OK) {
1332 if (errmsg) {
1333 ldb_set_errstring(module->ldb, errmsg);
1334 free(errmsg);
1336 ret = LDB_ERR_OTHER;
1337 goto failed;
1340 /* MISSING break is INTENTIONAL */
1342 case LDB_FLAG_MOD_ADD:
1343 #warning "We should throw an error if no value is provided!"
1344 /* For each value of the specified attribute name... */
1345 for (j = 0; j < el->num_values; j++) {
1346 struct ldb_val value;
1348 /* Get a canonicalised copy of the data */
1349 h->canonicalise_fn(module->ldb, lsql_ac, &(el->values[j]), &value);
1350 if (value.data == NULL) {
1351 ret = LDB_ERR_OTHER;
1352 goto failed;
1355 mod = lsqlite3_tprintf(lsql_ac,
1356 "INSERT OR ROLLBACK INTO ldb_attribute_values "
1357 "('eid', 'attr_name', 'norm_attr_name',"
1358 " 'attr_value', 'norm_attr_value') "
1359 "VALUES ('%lld', '%q', '%q', '%q', '%q');",
1360 eid, el->name, attr,
1361 el->values[j].data, value.data);
1363 if (mod == NULL) {
1364 ret = LDB_ERR_OTHER;
1365 goto failed;
1368 ret = sqlite3_exec(lsqlite3->sqlite, mod, NULL, NULL, &errmsg);
1369 if (ret != SQLITE_OK) {
1370 if (errmsg) {
1371 ldb_set_errstring(module->ldb, errmsg);
1372 free(errmsg);
1374 ret = LDB_ERR_OTHER;
1375 goto failed;
1379 break;
1381 case LDB_FLAG_MOD_DELETE:
1382 #warning "We should throw an error if the attribute we are trying to delete does not exist!"
1383 if (el->num_values == 0) {
1384 mod = lsqlite3_tprintf(lsql_ac,
1385 "DELETE FROM ldb_attribute_values "
1386 "WHERE eid = '%lld' "
1387 "AND norm_attr_name = '%q';",
1388 eid, attr);
1389 if (mod == NULL) {
1390 ret = LDB_ERR_OTHER;
1391 goto failed;
1394 ret = sqlite3_exec(lsqlite3->sqlite, mod, NULL, NULL, &errmsg);
1395 if (ret != SQLITE_OK) {
1396 if (errmsg) {
1397 ldb_set_errstring(module->ldb, errmsg);
1398 free(errmsg);
1400 ret = LDB_ERR_OTHER;
1401 goto failed;
1405 /* For each value of the specified attribute name... */
1406 for (j = 0; j < el->num_values; j++) {
1407 struct ldb_val value;
1409 /* Get a canonicalised copy of the data */
1410 h->canonicalise_fn(module->ldb, lsql_ac, &(el->values[j]), &value);
1411 if (value.data == NULL) {
1412 ret = LDB_ERR_OTHER;
1413 goto failed;
1416 mod = lsqlite3_tprintf(lsql_ac,
1417 "DELETE FROM ldb_attribute_values "
1418 "WHERE eid = '%lld' "
1419 "AND norm_attr_name = '%q' "
1420 "AND norm_attr_value = '%q';",
1421 eid, attr, value.data);
1423 if (mod == NULL) {
1424 ret = LDB_ERR_OTHER;
1425 goto failed;
1428 ret = sqlite3_exec(lsqlite3->sqlite, mod, NULL, NULL, &errmsg);
1429 if (ret != SQLITE_OK) {
1430 if (errmsg) {
1431 ldb_set_errstring(module->ldb, errmsg);
1432 free(errmsg);
1434 ret = LDB_ERR_OTHER;
1435 goto failed;
1439 break;
1443 if (lsql_ac->callback)
1444 (*handle)->status = lsql_ac->callback(module->ldb, lsql_ac->context, NULL);
1446 return LDB_SUCCESS;
1448 failed:
1449 talloc_free(*handle);
1450 return ret;
1453 static int lsql_modify(struct ldb_module *module, const struct ldb_message *msg)
1455 struct ldb_handle *handle;
1456 int ret;
1458 ret = lsql_modify_async(module, msg, NULL, NULL, &handle);
1460 if (ret != LDB_SUCCESS)
1461 return ret;
1463 ret = ldb_wait(handle, LDB_WAIT_ALL);
1465 talloc_free(handle);
1466 return ret;
1469 /* delete a record */
1470 static int lsql_delete_async(struct ldb_module *module, const struct ldb_dn *dn,
1471 void *context,
1472 int (*callback)(struct ldb_context *, void *, struct ldb_reply *),
1473 struct ldb_handle **handle)
1475 struct lsqlite3_private *lsqlite3 = talloc_get_type(module->private_data, struct lsqlite3_private);
1476 struct lsql_context *lsql_ac;
1477 long long eid;
1478 char *errmsg;
1479 char *query;
1480 int ret = LDB_ERR_OPERATIONS_ERROR;
1483 *handle = init_handle(lsqlite3, module, context, callback);
1484 if (*handle == NULL) {
1485 goto failed;
1487 lsql_ac = talloc_get_type((*handle)->private_data, struct lsql_context);
1488 (*handle)->state = LDB_ASYNC_DONE;
1489 (*handle)->status = LDB_SUCCESS;
1491 eid = lsqlite3_get_eid(module, dn);
1492 if (eid == -1) {
1493 goto failed;
1496 query = lsqlite3_tprintf(lsql_ac,
1497 /* Delete entry */
1498 "DELETE FROM ldb_entry WHERE eid = %lld; "
1499 /* Delete attributes */
1500 "DELETE FROM ldb_attribute_values WHERE eid = %lld; ",
1501 eid, eid);
1502 if (query == NULL) {
1503 ret = LDB_ERR_OTHER;
1504 goto failed;
1507 ret = sqlite3_exec(lsqlite3->sqlite, query, NULL, NULL, &errmsg);
1508 if (ret != SQLITE_OK) {
1509 if (errmsg) {
1510 ldb_set_errstring(module->ldb, errmsg);
1511 free(errmsg);
1513 ret = LDB_ERR_OPERATIONS_ERROR;
1514 goto failed;
1517 if (lsql_ac->callback)
1518 (*handle)->status = lsql_ac->callback(module->ldb, lsql_ac->context, NULL);
1520 return LDB_SUCCESS;
1522 failed:
1523 talloc_free(*handle);
1524 return ret;
1527 static int lsql_delete(struct ldb_module *module, const struct ldb_dn *dn)
1529 struct ldb_handle *handle;
1530 int ret;
1532 /* ignore ltdb specials */
1533 if (ldb_dn_is_special(dn)) {
1534 return LDB_SUCCESS;
1537 ret = lsql_delete_async(module, dn, NULL, NULL, &handle);
1539 if (ret != LDB_SUCCESS)
1540 return ret;
1542 ret = ldb_wait(handle, LDB_WAIT_ALL);
1544 talloc_free(handle);
1545 return ret;
1548 /* rename a record */
1549 static int lsql_rename_async(struct ldb_module *module, const struct ldb_dn *olddn, const struct ldb_dn *newdn,
1550 void *context,
1551 int (*callback)(struct ldb_context *, void *, struct ldb_reply *),
1552 struct ldb_handle **handle)
1554 struct lsqlite3_private *lsqlite3 = talloc_get_type(module->private_data, struct lsqlite3_private);
1555 struct lsql_context *lsql_ac;
1556 char *new_dn, *new_cdn, *old_cdn;
1557 char *errmsg;
1558 char *query;
1559 int ret = LDB_ERR_OPERATIONS_ERROR;
1561 *handle = init_handle(lsqlite3, module, context, callback);
1562 if (*handle == NULL) {
1563 goto failed;
1565 lsql_ac = talloc_get_type((*handle)->private_data, struct lsql_context);
1566 (*handle)->state = LDB_ASYNC_DONE;
1567 (*handle)->status = LDB_SUCCESS;
1569 /* create linearized and normalized dns */
1570 old_cdn = ldb_dn_linearize(lsql_ac, ldb_dn_casefold(module->ldb, olddn));
1571 new_cdn = ldb_dn_linearize(lsql_ac, ldb_dn_casefold(module->ldb, newdn));
1572 new_dn = ldb_dn_linearize(lsql_ac, newdn);
1573 if (old_cdn == NULL || new_cdn == NULL || new_dn == NULL) {
1574 goto failed;
1577 /* build the SQL query */
1578 query = lsqlite3_tprintf(lsql_ac,
1579 "UPDATE ldb_entry SET dn = '%q', norm_dn = '%q' "
1580 "WHERE norm_dn = '%q';",
1581 new_dn, new_cdn, old_cdn);
1582 if (query == NULL) {
1583 goto failed;
1586 /* execute */
1587 ret = sqlite3_exec(lsqlite3->sqlite, query, NULL, NULL, &errmsg);
1588 if (ret != SQLITE_OK) {
1589 if (errmsg) {
1590 ldb_set_errstring(module->ldb, errmsg);
1591 free(errmsg);
1593 ret = LDB_ERR_OPERATIONS_ERROR;
1594 goto failed;
1597 if (lsql_ac->callback)
1598 (*handle)->status = lsql_ac->callback(module->ldb, lsql_ac->context, NULL);
1600 return LDB_SUCCESS;
1602 failed:
1603 talloc_free(*handle);
1604 return ret;
1607 static int lsql_rename(struct ldb_module *module, const struct ldb_dn *olddn, const struct ldb_dn *newdn)
1609 struct ldb_handle *handle;
1610 int ret;
1612 /* ignore ltdb specials */
1613 if (ldb_dn_is_special(olddn) || ldb_dn_is_special(newdn)) {
1614 return LDB_SUCCESS;
1618 ret = lsql_rename_async(module, olddn, newdn, NULL, NULL, &handle);
1620 if (ret != LDB_SUCCESS)
1621 return ret;
1623 ret = ldb_wait(handle, LDB_WAIT_ALL);
1625 talloc_free(handle);
1626 return ret;
1629 static int lsql_start_trans(struct ldb_module * module)
1631 int ret;
1632 char *errmsg;
1633 struct lsqlite3_private * lsqlite3 = module->private_data;
1635 if (lsqlite3->trans_count == 0) {
1636 ret = sqlite3_exec(lsqlite3->sqlite, "BEGIN IMMEDIATE;", NULL, NULL, &errmsg);
1637 if (ret != SQLITE_OK) {
1638 if (errmsg) {
1639 printf("lsqlite3_start_trans: error: %s\n", errmsg);
1640 free(errmsg);
1642 return -1;
1646 lsqlite3->trans_count++;
1648 return 0;
1651 static int lsql_end_trans(struct ldb_module *module)
1653 int ret;
1654 char *errmsg;
1655 struct lsqlite3_private *lsqlite3 = module->private_data;
1657 if (lsqlite3->trans_count > 0) {
1658 lsqlite3->trans_count--;
1659 } else return -1;
1661 if (lsqlite3->trans_count == 0) {
1662 ret = sqlite3_exec(lsqlite3->sqlite, "COMMIT;", NULL, NULL, &errmsg);
1663 if (ret != SQLITE_OK) {
1664 if (errmsg) {
1665 printf("lsqlite3_end_trans: error: %s\n", errmsg);
1666 free(errmsg);
1668 return -1;
1672 return 0;
1675 static int lsql_del_trans(struct ldb_module *module)
1677 struct lsqlite3_private *lsqlite3 = module->private_data;
1679 if (lsqlite3->trans_count > 0) {
1680 lsqlite3->trans_count--;
1681 } else return -1;
1683 if (lsqlite3->trans_count == 0) {
1684 return lsqlite3_safe_rollback(lsqlite3->sqlite);
1687 return -1;
1691 * Static functions
1694 static int initialize(struct lsqlite3_private *lsqlite3,
1695 struct ldb_context *ldb, const char *url, int flags)
1697 TALLOC_CTX *local_ctx;
1698 long long queryInt;
1699 int rollback = 0;
1700 char *errmsg;
1701 char *schema;
1702 int ret;
1704 /* create a local ctx */
1705 local_ctx = talloc_named(lsqlite3, 0, "lsqlite3_rename local context");
1706 if (local_ctx == NULL) {
1707 return -1;
1710 schema = lsqlite3_tprintf(local_ctx,
1713 "CREATE TABLE ldb_info AS "
1714 " SELECT 'LDB' AS database_type,"
1715 " '1.0' AS version;"
1718 * The entry table holds the information about an entry.
1719 * This table is used to obtain the EID of the entry and to
1720 * support scope=one and scope=base. The parent and child
1721 * table is included in the entry table since all the other
1722 * attributes are dependent on EID.
1724 "CREATE TABLE ldb_entry "
1726 " eid INTEGER PRIMARY KEY AUTOINCREMENT,"
1727 " dn TEXT UNIQUE NOT NULL,"
1728 " norm_dn TEXT UNIQUE NOT NULL"
1729 ");"
1732 "CREATE TABLE ldb_object_classes"
1734 " class_name TEXT PRIMARY KEY,"
1735 " parent_class_name TEXT,"
1736 " tree_key TEXT UNIQUE,"
1737 " max_child_num INTEGER DEFAULT 0"
1738 ");"
1741 * We keep a full listing of attribute/value pairs here
1743 "CREATE TABLE ldb_attribute_values"
1745 " eid INTEGER REFERENCES ldb_entry,"
1746 " attr_name TEXT,"
1747 " norm_attr_name TEXT,"
1748 " attr_value TEXT,"
1749 " norm_attr_value TEXT "
1750 ");"
1754 * Indexes
1756 "CREATE INDEX ldb_attribute_values_eid_idx "
1757 " ON ldb_attribute_values (eid);"
1759 "CREATE INDEX ldb_attribute_values_name_value_idx "
1760 " ON ldb_attribute_values (attr_name, norm_attr_value);"
1765 * Triggers
1768 "CREATE TRIGGER ldb_object_classes_insert_tr"
1769 " AFTER INSERT"
1770 " ON ldb_object_classes"
1771 " FOR EACH ROW"
1772 " BEGIN"
1773 " UPDATE ldb_object_classes"
1774 " SET tree_key = COALESCE(tree_key, "
1775 " ("
1776 " SELECT tree_key || "
1777 " (SELECT base160(max_child_num + 1)"
1778 " FROM ldb_object_classes"
1779 " WHERE class_name = "
1780 " new.parent_class_name)"
1781 " FROM ldb_object_classes "
1782 " WHERE class_name = new.parent_class_name "
1783 " ));"
1784 " UPDATE ldb_object_classes "
1785 " SET max_child_num = max_child_num + 1"
1786 " WHERE class_name = new.parent_class_name;"
1787 " END;"
1790 * Table initialization
1793 "INSERT INTO ldb_object_classes "
1794 " (class_name, tree_key) "
1795 " VALUES "
1796 " ('TOP', '0001');");
1798 /* Skip protocol indicator of url */
1799 if (strncmp(url, "sqlite://", 9) != 0) {
1800 return SQLITE_MISUSE;
1803 /* Update pointer to just after the protocol indicator */
1804 url += 9;
1806 /* Try to open the (possibly empty/non-existent) database */
1807 if ((ret = sqlite3_open(url, &lsqlite3->sqlite)) != SQLITE_OK) {
1808 return ret;
1811 /* In case this is a new database, enable auto_vacuum */
1812 ret = sqlite3_exec(lsqlite3->sqlite, "PRAGMA auto_vacuum = 1;", NULL, NULL, &errmsg);
1813 if (ret != SQLITE_OK) {
1814 if (errmsg) {
1815 printf("lsqlite3 initializaion error: %s\n", errmsg);
1816 free(errmsg);
1818 goto failed;
1821 if (flags & LDB_FLG_NOSYNC) {
1822 /* DANGEROUS */
1823 ret = sqlite3_exec(lsqlite3->sqlite, "PRAGMA synchronous = OFF;", NULL, NULL, &errmsg);
1824 if (ret != SQLITE_OK) {
1825 if (errmsg) {
1826 printf("lsqlite3 initializaion error: %s\n", errmsg);
1827 free(errmsg);
1829 goto failed;
1833 /* */
1835 /* Establish a busy timeout of 30 seconds */
1836 if ((ret = sqlite3_busy_timeout(lsqlite3->sqlite,
1837 30000)) != SQLITE_OK) {
1838 return ret;
1841 /* Create a function, callable from sql, to increment a tree_key */
1842 if ((ret =
1843 sqlite3_create_function(lsqlite3->sqlite,/* handle */
1844 "base160_next", /* function name */
1845 1, /* number of args */
1846 SQLITE_ANY, /* preferred text type */
1847 NULL, /* user data */
1848 base160next_sql, /* called func */
1849 NULL, /* step func */
1850 NULL /* final func */
1851 )) != SQLITE_OK) {
1852 return ret;
1855 /* Create a function, callable from sql, to convert int to base160 */
1856 if ((ret =
1857 sqlite3_create_function(lsqlite3->sqlite,/* handle */
1858 "base160", /* function name */
1859 1, /* number of args */
1860 SQLITE_ANY, /* preferred text type */
1861 NULL, /* user data */
1862 base160_sql, /* called func */
1863 NULL, /* step func */
1864 NULL /* final func */
1865 )) != SQLITE_OK) {
1866 return ret;
1869 /* Create a function, callable from sql, to perform various comparisons */
1870 if ((ret =
1871 sqlite3_create_function(lsqlite3->sqlite, /* handle */
1872 "ldap_compare", /* function name */
1873 4, /* number of args */
1874 SQLITE_ANY, /* preferred text type */
1875 ldb , /* user data */
1876 lsqlite3_compare, /* called func */
1877 NULL, /* step func */
1878 NULL /* final func */
1879 )) != SQLITE_OK) {
1880 return ret;
1883 /* Begin a transaction */
1884 ret = sqlite3_exec(lsqlite3->sqlite, "BEGIN EXCLUSIVE;", NULL, NULL, &errmsg);
1885 if (ret != SQLITE_OK) {
1886 if (errmsg) {
1887 printf("lsqlite3: initialization error: %s\n", errmsg);
1888 free(errmsg);
1890 goto failed;
1892 rollback = 1;
1894 /* Determine if this is a new database. No tables means it is. */
1895 if (query_int(lsqlite3,
1896 &queryInt,
1897 "SELECT COUNT(*)\n"
1898 " FROM sqlite_master\n"
1899 " WHERE type = 'table';") != 0) {
1900 goto failed;
1903 if (queryInt == 0) {
1905 * Create the database schema
1907 ret = sqlite3_exec(lsqlite3->sqlite, schema, NULL, NULL, &errmsg);
1908 if (ret != SQLITE_OK) {
1909 if (errmsg) {
1910 printf("lsqlite3 initializaion error: %s\n", errmsg);
1911 free(errmsg);
1913 goto failed;
1915 } else {
1917 * Ensure that the database we opened is one of ours
1919 if (query_int(lsqlite3,
1920 &queryInt,
1921 "SELECT "
1922 " (SELECT COUNT(*) = 2"
1923 " FROM sqlite_master "
1924 " WHERE type = 'table' "
1925 " AND name IN "
1926 " ("
1927 " 'ldb_entry', "
1928 " 'ldb_object_classes' "
1929 " ) "
1930 " ) "
1931 " AND "
1932 " (SELECT 1 "
1933 " FROM ldb_info "
1934 " WHERE database_type = 'LDB' "
1935 " AND version = '1.0'"
1936 " );") != 0 ||
1937 queryInt != 1) {
1939 /* It's not one that we created. See ya! */
1940 goto failed;
1944 /* Commit the transaction */
1945 ret = sqlite3_exec(lsqlite3->sqlite, "COMMIT;", NULL, NULL, &errmsg);
1946 if (ret != SQLITE_OK) {
1947 if (errmsg) {
1948 printf("lsqlite3: iniialization error: %s\n", errmsg);
1949 free(errmsg);
1951 goto failed;
1954 return SQLITE_OK;
1956 failed:
1957 if (rollback) lsqlite3_safe_rollback(lsqlite3->sqlite);
1958 sqlite3_close(lsqlite3->sqlite);
1959 return -1;
1962 static int destructor(struct lsqlite3_private *lsqlite3)
1964 if (lsqlite3->sqlite) {
1965 sqlite3_close(lsqlite3->sqlite);
1967 return 0;
1970 static int lsql_wait(struct ldb_handle *handle, enum ldb_wait_type type)
1972 return handle->status;
1975 static int lsql_request(struct ldb_module *module, struct ldb_request *req)
1977 /* check for oustanding critical controls and return an error if found */
1979 if (req->controls != NULL) {
1980 ldb_debug(module->ldb, LDB_DEBUG_WARNING, "Controls should not reach the ldb_sqlite3 backend!\n");
1983 if (check_critical_controls(req->controls)) {
1984 return LDB_ERR_UNSUPPORTED_CRITICAL_EXTENSION;
1987 switch (req->operation) {
1989 case LDB_SEARCH:
1990 return lsql_search_bytree(module,
1991 req->op.search.base,
1992 req->op.search.scope,
1993 req->op.search.tree,
1994 req->op.search.attrs,
1995 &req->op.search.res);
1997 case LDB_ADD:
1998 return lsql_add(module, req->op.add.message);
2000 case LDB_MODIFY:
2001 return lsql_modify(module, req->op.mod.message);
2003 case LDB_DELETE:
2004 return lsql_delete(module, req->op.del.dn);
2006 case LDB_RENAME:
2007 return lsql_rename(module,
2008 req->op.rename.olddn,
2009 req->op.rename.newdn);
2011 case LDB_SEARCH:
2012 return lsql_search_async(module,
2013 req->op.search.base,
2014 req->op.search.scope,
2015 req->op.search.tree,
2016 req->op.search.attrs,
2017 req->context,
2018 req->callback,
2019 &req->handle);
2021 case LDB_ADD:
2022 return lsql_add_async(module,
2023 req->op.add.message,
2024 req->context,
2025 req->callback,
2026 &req->handle);
2028 case LDB_MODIFY:
2029 return lsql_modify_async(module,
2030 req->op.mod.message,
2031 req->context,
2032 req->callback,
2033 &req->handle);
2035 case LDB_DELETE:
2036 return lsql_delete_async(module,
2037 req->op.del.dn,
2038 req->context,
2039 req->callback,
2040 &req->handle);
2042 case LDB_RENAME:
2043 return lsql_rename_async(module,
2044 req->op.rename.olddn,
2045 req->op.rename.newdn,
2046 req->context,
2047 req->callback,
2048 &req->handle);
2050 default:
2051 return LDB_ERR_OPERATIONS_ERROR;
2057 * Table of operations for the sqlite3 backend
2059 static const struct ldb_module_ops lsqlite3_ops = {
2060 .name = "sqlite",
2061 .request = lsql_request,
2062 .start_transaction = lsql_start_trans,
2063 .end_transaction = lsql_end_trans,
2064 .del_transaction = lsql_del_trans,
2065 .wait = lsql_wait,
2069 * connect to the database
2071 static int lsqlite3_connect(struct ldb_context *ldb,
2072 const char *url,
2073 unsigned int flags,
2074 const char *options[],
2075 struct ldb_module **module)
2077 int i;
2078 int ret;
2079 struct lsqlite3_private * lsqlite3 = NULL;
2081 lsqlite3 = talloc(ldb, struct lsqlite3_private);
2082 if (!lsqlite3) {
2083 goto failed;
2086 lsqlite3->sqlite = NULL;
2087 lsqlite3->options = NULL;
2088 lsqlite3->trans_count = 0;
2090 ret = initialize(lsqlite3, ldb, url, flags);
2091 if (ret != SQLITE_OK) {
2092 goto failed;
2095 talloc_set_destructor(lsqlite3, destructor);
2099 *module = talloc(ldb, struct ldb_module);
2100 if (!module) {
2101 ldb_oom(ldb);
2102 goto failed;
2104 talloc_set_name_const(*module, "ldb_sqlite3 backend");
2105 (*module)->ldb = ldb;
2106 (*module)->prev = (*module)->next = NULL;
2107 (*module)->private_data = lsqlite3;
2108 (*module)->ops = &lsqlite3_ops;
2110 if (options) {
2112 * take a copy of the options array, so we don't have to rely
2113 * on the caller keeping it around (it might be dynamic)
2115 for (i=0;options[i];i++) ;
2117 lsqlite3->options = talloc_array(lsqlite3, char *, i+1);
2118 if (!lsqlite3->options) {
2119 goto failed;
2122 for (i=0;options[i];i++) {
2124 lsqlite3->options[i+1] = NULL;
2125 lsqlite3->options[i] =
2126 talloc_strdup(lsqlite3->options, options[i]);
2127 if (!lsqlite3->options[i]) {
2128 goto failed;
2133 return 0;
2135 failed:
2136 if (lsqlite3->sqlite != NULL) {
2137 (void) sqlite3_close(lsqlite3->sqlite);
2139 talloc_free(lsqlite3);
2140 return -1;
2143 int ldb_sqlite3_init(void)
2145 return ldb_register_backend("sqlite3", lsqlite3_connect);