4 Copyright (C) Derrell Lipman 2005
6 ** NOTE! The following LGPL license applies to the ldb
7 ** library. This does NOT imply that all of Samba is released
10 This library is free software; you can redistribute it and/or
11 modify it under the terms of the GNU Lesser General Public
12 License as published by the Free Software Foundation; either
13 version 2 of the License, or (at your option) any later version.
15 This library is distributed in the hope that it will be useful,
16 but WITHOUT ANY WARRANTY; without even the implied warranty of
17 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
18 Lesser General Public License for more details.
20 You should have received a copy of the GNU Lesser General Public
21 License along with this library; if not, write to the Free Software
22 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
28 * Component: ldb sqlite3 backend
30 * Description: core files for SQLITE3 backend
32 * Author: Derrell Lipman (based on Andrew Tridgell's LDAP backend)
37 #include "ldb/include/ldb.h"
38 #include "ldb/include/ldb_private.h"
39 #include "ldb/include/ldb_explode_dn.h"
40 #include "ldb/ldb_sqlite3/ldb_sqlite3.h"
43 * Macros used throughout
48 # define TRUE (! FALSE)
51 #define FILTER_ATTR_TABLE "temp_filter_attrs"
52 #define RESULT_ATTR_TABLE "temp_result_attrs"
54 #define QUERY_NOROWS(lsqlite3, bRollbackOnError, sql...) \
56 if (query_norows(lsqlite3, sql) != 0) { \
57 if (bRollbackOnError) { \
58 query_norows(lsqlite3, \
65 #define QUERY_INT(lsqlite3, result_var, bRollbackOnError, sql...) \
67 if (query_int(lsqlite3, &result_var, sql) != 0) { \
68 if (bRollbackOnError) { \
69 query_norows(lsqlite3, \
80 static int lsqlite3_debug = TRUE;
84 * Forward declarations
87 lsqlite3_rename(struct ldb_module * module,
92 lsqlite3_delete(struct ldb_module *module,
96 lsqlite3_search_bytree(struct ldb_module * module,
99 struct ldb_parse_tree * pTree,
100 const char * const * attrs,
101 struct ldb_message *** pppRes);
104 lsqlite3_search(struct ldb_module * module,
105 const char * pBaseDN,
106 enum ldb_scope scope,
107 const char * pExpression,
108 const char * const attrs[],
109 struct ldb_message *** pppRes);
112 lsqlite3_add(struct ldb_module *module,
113 const struct ldb_message *msg);
116 lsqlite3_modify(struct ldb_module *module,
117 const struct ldb_message *msg);
120 lsqlite3_lock(struct ldb_module *module,
121 const char *lockname);
124 lsqlite3_unlock(struct ldb_module *module,
125 const char *lockname);
128 lsqlite3_errstring(struct ldb_module *module);
131 initialize(struct lsqlite3_private *lsqlite3,
138 query_norows(const struct lsqlite3_private *lsqlite3,
143 query_int(const struct lsqlite3_private * lsqlite3,
148 static int case_fold_attr_required(void * hUserData,
152 add_msg_attr(void * hTalloc,
155 const char * pAttrName,
156 const char * pAttrValue,
159 struct ldb_message *** pppRes);
162 parsetree_to_sql(struct ldb_module *module,
164 const struct ldb_parse_tree *t);
167 parsetree_to_attrlist(struct lsqlite3_private * lsqlite3,
168 const struct ldb_parse_tree * t);
171 build_attr_table_list(void * hTalloc,
172 struct lsqlite3_private * lsqlite3);
175 msg_to_sql(struct ldb_module * module,
176 const struct ldb_message * msg,
181 new_dn(struct ldb_module * module,
186 new_attr(struct ldb_module * module,
191 * Table of operations for the sqlite3 backend
193 static const struct ldb_module_ops lsqlite3_ops = {
195 .search = lsqlite3_search,
196 .search_bytree = lsqlite3_search_bytree,
197 .add_record = lsqlite3_add,
198 .modify_record = lsqlite3_modify,
199 .delete_record = lsqlite3_delete,
200 .rename_record = lsqlite3_rename,
201 .named_lock = lsqlite3_lock,
202 .named_unlock = lsqlite3_unlock,
203 .errstring = lsqlite3_errstring
215 * connect to the database
218 lsqlite3_connect(const char *url,
220 const char *options[])
224 struct ldb_context * ldb = NULL;
225 struct lsqlite3_private * lsqlite3 = NULL;
227 ldb = talloc(NULL, struct ldb_context);
232 lsqlite3 = talloc(ldb, struct lsqlite3_private);
237 lsqlite3->sqlite = NULL;
238 lsqlite3->options = NULL;
239 lsqlite3->lock_count = 0;
241 ret = initialize(lsqlite3, url);
242 if (ret != SQLITE_OK) {
246 talloc_set_destructor(lsqlite3, destructor);
248 ldb->modules = talloc(ldb, struct ldb_module);
252 ldb->modules->ldb = ldb;
253 ldb->modules->prev = ldb->modules->next = NULL;
254 ldb->modules->private_data = lsqlite3;
255 ldb->modules->ops = &lsqlite3_ops;
259 * take a copy of the options array, so we don't have to rely
260 * on the caller keeping it around (it might be dynamic)
262 for (i=0;options[i];i++) ;
264 lsqlite3->options = talloc_array(lsqlite3, char *, i+1);
265 if (!lsqlite3->options) {
269 for (i=0;options[i];i++) {
271 lsqlite3->options[i+1] = NULL;
272 lsqlite3->options[i] =
273 talloc_strdup(lsqlite3->options, options[i]);
274 if (!lsqlite3->options[i]) {
283 if (lsqlite3->sqlite != NULL) {
284 (void) sqlite3_close(lsqlite3->sqlite);
292 * Interface functions referenced by lsqlite3_ops
295 /* rename a record */
297 lsqlite3_rename(struct ldb_module * module,
301 /* ignore ltdb specials */
302 if (olddn[0] == '@' ||newdn[0] == '@') {
306 #warning "lsqlite3_rename() is not yet supported"
311 /* delete a record */
313 lsqlite3_delete(struct ldb_module *module,
316 struct lsqlite3_private * lsqlite3 = module->private_data;
318 /* ignore ltdb specials */
323 /* Begin a transaction */
324 QUERY_NOROWS(lsqlite3, FALSE, "BEGIN EXCLUSIVE;");
327 #warning "lsqlite3_delete() is not yet supported"
329 /* Commit the transaction */
330 QUERY_NOROWS(lsqlite3, TRUE, "COMMIT;");
335 /* search for matching records, by tree */
337 lsqlite3_search_bytree(struct ldb_module * module,
338 const char * pBaseDN,
339 enum ldb_scope scope,
340 struct ldb_parse_tree * pTree,
341 const char * const * attrs,
342 struct ldb_message *** pppRes)
350 char * pSqlConstraints;
352 char * hTalloc = NULL;
354 const char * pAttrName;
355 const char * pAttrValue;
356 const char * pResultAttrList;
357 const char * const * pRequestedAttrs;
358 sqlite3_stmt * pStmt;
359 struct lsqlite3_private * lsqlite3 = module->private_data;
361 if (pBaseDN == NULL) {
365 /* Begin a transaction */
366 QUERY_NOROWS(lsqlite3, FALSE, "BEGIN IMMEDIATE;");
369 * Obtain the eid of the base DN
371 if ((ret = query_int(lsqlite3,
374 " FROM ldb_attr_DN\n"
375 " WHERE attr_value = %Q;",
376 pBaseDN)) == SQLITE_DONE) {
377 QUERY_NOROWS(lsqlite3, FALSE, "ROLLBACK;");
379 } else if (ret != SQLITE_OK) {
380 QUERY_NOROWS(lsqlite3, FALSE, "ROLLBACK;");
384 /* Allocate a temporary talloc context */
385 if ((hTalloc = talloc_new(module->ldb)) == NULL) {
391 /* Convert filter into a series of SQL conditions (constraints) */
392 pSqlConstraints = parsetree_to_sql(module, hTalloc, pTree);
394 /* Ensure we're starting with an empty result attribute table */
395 QUERY_NOROWS(lsqlite3,
397 "DELETE FROM " RESULT_ATTR_TABLE "\n"
398 " WHERE 1;");/* avoid a schema change with WHERE 1 */
400 /* Initially, we don't know what the requested attributes are */
402 /* but they didn't give us any so we'll retrieve all of 'em */
403 pResultAttrList = "";
405 /* Discover the list of attributes */
406 pResultAttrList = NULL;
409 /* Insert the list of requested attributes into this table */
410 for (pRequestedAttrs = (const char * const *) attrs;
411 pRequestedAttrs != NULL && *pRequestedAttrs != NULL;
414 /* If any attribute in the list is "*" then... */
415 if (strcmp(*pRequestedAttrs, "*") == 0) {
416 /* we want all attribute types */
417 pResultAttrList = "";
421 /* otherwise, add this name to the resuult list */
422 QUERY_NOROWS(lsqlite3,
425 " INTO " RESULT_ATTR_TABLE "\n"
433 /* If we didn't get a "*" for all attributes in the result list... */
434 if (pResultAttrList == NULL) {
435 /* ... then we'll use the result attribute table */
437 " AND av.attr_name IN\n"
438 " (SELECT attr_name\n"
439 " FROM " RESULT_ATTR_TABLE ") ";
442 /* Ensure we're starting with an empty filter attribute table */
443 QUERY_NOROWS(lsqlite3,
445 "DELETE FROM " FILTER_ATTR_TABLE "\n"
446 " WHERE 1;");/* avoid a schema change with WHERE 1 */
449 * Create a table of unique attribute names for our extra table list
451 if ((ret = parsetree_to_attrlist(lsqlite3, pTree)) != 0) {
457 * Build the attribute table list from the list of unique names.
460 if ((pTableList = build_attr_table_list(hTalloc, lsqlite3)) == NULL) {
466 case LDB_SCOPE_DEFAULT:
467 case LDB_SCOPE_SUBTREE:
468 pSql = sqlite3_mprintf(
469 "SELECT entry.eid,\n"
473 " FROM ldb_entry AS entry,\n"
474 " ldb_attribute_values AS av\n"
475 " WHERE entry.eid IN\n"
476 " (SELECT DISTINCT ldb_entry.eid\n"
479 " WHERE ldb_descendants.aeid = %lld\n"
480 " AND ldb_entry.eid = ldb_descendants.deid\n"
481 " AND ldb_entry.eid IN\n%s\n"
483 " AND av.eid = entry.eid\n"
485 " ORDER BY av.eid, av.attr_name;",
492 pSql = sqlite3_mprintf(
493 "SELECT entry.eid,\n"
497 " FROM ldb_entry AS entry,\n"
498 " ldb_attribute_values AS av\n"
499 " WHERE entry.eid IN\n"
500 " (SELECT DISTINCT ldb_entry.eid\n"
502 " WHERE ldb_entry.eid = %lld\n"
503 " AND ldb_entry.eid IN\n%s\n"
505 " AND av.eid = entry.eid\n"
507 " ORDER BY av.eid, av.attr_name;",
513 case LDB_SCOPE_ONELEVEL:
514 pSql = sqlite3_mprintf(
515 "SELECT entry.eid,\n"
519 " FROM ldb_entry AS entry,\n"
520 " ldb_attribute_values AS av\n"
521 " WHERE entry.eid IN\n"
522 " (SELECT DISTINCT ldb_entry.eid\n"
523 " FROM ldb_entry AS pchild\n"
524 " WHERE ldb_entry.eid = pchild.eid\n"
525 " AND pchild.peid = %lld\n"
526 " AND ldb_entry.eid IN\n%s\n"
528 " AND av.eid = entry.eid\n"
530 " ORDER BY av.eid, av.attr_name;\n",
537 if (lsqlite3_debug) {
538 printf("%s\n", pSql);
542 * Prepare and execute the SQL statement. Loop allows retrying on
543 * certain errors, e.g. SQLITE_SCHEMA occurs if the schema changes,
544 * requiring retrying the operation.
546 for (bLoop = TRUE; bLoop; ) {
547 /* There are no allocate message structures yet */
549 if (pppRes != NULL) {
553 /* Compile the SQL statement into sqlite virtual machine */
554 if ((ret = sqlite3_prepare(lsqlite3->sqlite,
558 NULL)) == SQLITE_SCHEMA) {
559 if (pppRes != NULL && *pppRes != NULL) {
560 talloc_free(*pppRes);
563 } else if (ret != SQLITE_OK) {
568 /* Initially, we have no previous eid */
571 /* Loop through the returned rows */
572 for (ret = SQLITE_ROW; ret == SQLITE_ROW; ) {
574 /* Get the next row */
575 if ((ret = sqlite3_step(pStmt)) == SQLITE_ROW) {
577 /* Get the values from this row */
578 eid = sqlite3_column_int64(pStmt, 0);
579 pDN = sqlite3_column_text(pStmt, 1);
580 pAttrName = sqlite3_column_text(pStmt, 2);
581 pAttrValue = sqlite3_column_text(pStmt, 3);
583 /* Add this result to the result set */
584 if ((ret = add_msg_attr(hTalloc,
593 (void) sqlite3_finalize(pStmt);
600 if (ret == SQLITE_SCHEMA) {
601 (void) sqlite3_finalize(pStmt);
602 if (pppRes != NULL && *pppRes != NULL) {
603 talloc_free(*pppRes);
606 } else if (ret != SQLITE_DONE) {
607 (void) sqlite3_finalize(pStmt);
612 /* Free the virtual machine */
613 if ((ret = sqlite3_finalize(pStmt)) == SQLITE_SCHEMA) {
614 (void) sqlite3_finalize(pStmt);
615 if (pppRes != NULL && *pppRes != NULL) {
616 talloc_free(*pppRes);
619 } else if (ret != SQLITE_OK) {
620 (void) sqlite3_finalize(pStmt);
626 * Normal condition is only one time through loop. Loop is
627 * rerun in error conditions, via "continue", above.
633 /* End the transaction */
634 QUERY_NOROWS(lsqlite3, FALSE, "END TRANSACTION;");
636 /* We're alll done with this query */
639 /* Were there any results? */
640 if (ret != 0 || allocated == 0) {
641 /* Nope. We can free the results. */
642 if (pppRes != NULL && *pppRes != NULL) {
643 talloc_free(*pppRes);
648 /* Clean up our temporary tables */
649 QUERY_NOROWS(lsqlite3,
651 "DELETE FROM " RESULT_ATTR_TABLE "\n"
652 " WHERE 1;");/* avoid a schema change with WHERE 1 */
654 QUERY_NOROWS(lsqlite3,
656 "DELETE FROM " FILTER_ATTR_TABLE "\n"
657 " WHERE 1;");/* avoid a schema change with WHERE 1 */
660 if (hTalloc != NULL) {
661 talloc_free(hTalloc);
664 /* If error, return error code; otherwise return number of results */
665 return ret == 0 ? allocated : ret;
668 /* search for matching records, by expression */
670 lsqlite3_search(struct ldb_module * module,
671 const char * pBaseDN,
672 enum ldb_scope scope,
673 const char * pExpression,
674 const char * const * attrs,
675 struct ldb_message *** pppRes)
678 struct ldb_parse_tree * pTree;
680 /* Parse the filter expression into a tree we can work with */
681 if ((pTree = ldb_parse_tree(module->ldb, pExpression)) == NULL) {
685 /* Now use the bytree function for the remainder of processing */
686 ret = lsqlite3_search_bytree(module, pBaseDN, scope,
687 pTree, attrs, pppRes);
689 /* Free the parse tree */
699 lsqlite3_add(struct ldb_module *module,
700 const struct ldb_message *msg)
703 struct lsqlite3_private * lsqlite3 = module->private_data;
705 /* ignore ltdb specials */
706 if (msg->dn[0] == '@') {
710 /* Begin a transaction */
711 QUERY_NOROWS(lsqlite3, FALSE, "BEGIN EXCLUSIVE;");
714 * Build any portions of the directory tree that don't exist. If the
715 * final component already exists, it's an error.
717 if (new_dn(module, msg->dn, &eid) != 0) {
718 QUERY_NOROWS(lsqlite3, FALSE, "ROLLBACK;");
722 /* Add attributes to this new entry */
723 if (msg_to_sql(module, msg, eid, FALSE) != 0) {
724 QUERY_NOROWS(lsqlite3, FALSE, "ROLLBACK;");
728 /* Everything worked. Commit it! */
729 QUERY_NOROWS(lsqlite3, TRUE, "COMMIT;");
734 /* modify a record */
736 lsqlite3_modify(struct ldb_module *module,
737 const struct ldb_message *msg)
739 struct lsqlite3_private * lsqlite3 = module->private_data;
741 /* ignore ltdb specials */
742 if (msg->dn[0] == '@') {
746 /* Begin a transaction */
747 QUERY_NOROWS(lsqlite3, FALSE, "BEGIN EXCLUSIVE;");
749 #warning "modify() not yet implemented"
751 /* Everything worked. Commit it! */
752 QUERY_NOROWS(lsqlite3, TRUE, "COMMIT;");
756 /* obtain a named lock */
758 lsqlite3_lock(struct ldb_module *module,
759 const char *lockname)
761 if (lockname == NULL) {
765 /* TODO implement a local locking mechanism here */
770 /* release a named lock */
772 lsqlite3_unlock(struct ldb_module *module,
773 const char *lockname)
775 if (lockname == NULL) {
779 /* TODO implement a local locking mechanism here */
784 /* return extended error information */
786 lsqlite3_errstring(struct ldb_module *module)
788 struct lsqlite3_private * lsqlite3 = module->private_data;
790 return sqlite3_errmsg(lsqlite3->sqlite);
801 initialize(struct lsqlite3_private *lsqlite3,
808 const char * schema =
811 "CREATE TABLE ldb_info AS "
812 " SELECT 'LDB' AS database_type,"
816 * The entry table holds the information about an entry.
817 * This table is used to obtain the EID of the entry and to
818 * support scope=one and scope=base. The parent and child
819 * table is included in the entry table since all the other
820 * attributes are dependent on EID.
822 "CREATE TABLE ldb_entry "
824 " eid INTEGER PRIMARY KEY,"
825 " peid INTEGER REFERENCES ldb_entry,"
827 " create_timestamp INTEGER,"
828 " modify_timestamp INTEGER"
833 * The purpose of the descendant table is to support the
834 * subtree search feature. For each LDB entry with a unique
835 * ID (AEID), this table contains the unique identifiers
836 * (DEID) of the descendant entries.
838 * For evern entry in the directory, a row exists in this
839 * table for each of its ancestors including itself. The
840 * size of the table depends on the depth of each entry. In
841 * the worst case, if all the entries were at the same
842 * depth, the number of rows in the table is O(nm) where
843 * n is the number of nodes in the directory and m is the
846 "CREATE TABLE ldb_descendants "
848 " aeid INTEGER REFERENCES ldb_entry,"
849 " deid INTEGER REFERENCES ldb_entry"
853 "CREATE TABLE ldb_object_classes"
855 " class_name TEXT PRIMARY KEY,"
856 " tree_key TEXT UNIQUE"
860 * We keep a full listing of attribute/value pairs here
862 "CREATE TABLE ldb_attribute_values"
864 " eid INTEGER REFERENCES ldb_entry,"
870 * There is one attribute table per searchable attribute.
873 "CREATE TABLE ldb_attr_ATTRIBUTE_NAME"
875 " eid INTEGER REFERENCES ldb_entry,"
881 * We pre-create the dn attribute table
883 "CREATE TABLE ldb_attr_DN"
885 " eid INTEGER REFERENCES ldb_entry,"
891 * We pre-create the objectclass attribute table
893 "CREATE TABLE ldb_attr_OBJECTCLASS"
895 " eid INTEGER REFERENCES ldb_entry,"
909 "CREATE TRIGGER ldb_entry_insert_tr"
915 " SET create_timestamp = strftime('%s', 'now'),"
916 " modify_timestamp = strftime('%s', 'now')"
917 " WHERE eid = new.eid;"
920 "CREATE TRIGGER ldb_entry_update_tr"
926 " SET modify_timestamp = strftime('%s', 'now')"
927 " WHERE eid = old.eid;"
931 * Table initialization
935 "INSERT INTO ldb_entry "
940 /* And the root node "dn" attribute */
941 "INSERT INTO ldb_attr_DN "
942 " (eid, attr_value) "
948 /* Skip protocol indicator of url */
949 if (strncmp(url, "sqlite://", 9) != 0) {
950 return SQLITE_MISUSE;
953 /* Update pointer to just after the protocol indicator */
956 /* Try to open the (possibly empty/non-existent) database */
957 if ((ret = sqlite3_open(url, &lsqlite3->sqlite)) != SQLITE_OK) {
961 /* In case this is a new database, enable auto_vacuum */
962 QUERY_NOROWS(lsqlite3, FALSE, "PRAGMA auto_vacuum=1;");
964 /* Begin a transaction */
965 QUERY_NOROWS(lsqlite3, FALSE, "BEGIN EXCLUSIVE;");
967 /* Determine if this is a new database. No tables means it is. */
972 " FROM sqlite_master\n"
973 " WHERE type = 'table';");
977 * Create the database schema
979 for (pTail = discard_const_p(char, schema);
980 pTail != NULL && *pTail != '\0';
983 if (lsqlite3_debug) {
984 printf("Execute first query in:\n%s\n", pTail);
987 if ((ret = sqlite3_prepare(
992 &pTail)) != SQLITE_OK ||
993 (ret = sqlite3_step(stmt)) != SQLITE_DONE ||
994 (ret = sqlite3_finalize(stmt)) != SQLITE_OK) {
996 QUERY_NOROWS(lsqlite3, FALSE, "ROLLBACK;");
997 (void) sqlite3_close(lsqlite3->sqlite);
1003 * Ensure that the database we opened is one of ours
1005 if (query_int(lsqlite3,
1008 " (SELECT COUNT(*) = 3"
1009 " FROM sqlite_master "
1010 " WHERE type = 'table' "
1014 " 'ldb_descendants', "
1015 " 'ldb_object_classes' "
1021 " WHERE database_type = 'LDB' "
1022 " AND version = '1.0'"
1026 /* It's not one that we created. See ya! */
1027 QUERY_NOROWS(lsqlite3, FALSE, "ROLLBACK;");
1028 (void) sqlite3_close(lsqlite3->sqlite);
1029 return SQLITE_MISUSE;
1034 * Create a temporary table to hold attributes requested in the result
1037 QUERY_NOROWS(lsqlite3,
1039 "CREATE TEMPORARY TABLE " RESULT_ATTR_TABLE "\n"
1041 " attr_name TEXT PRIMARY KEY\n"
1045 * Create a temporary table to hold the attributes used by filters
1048 QUERY_NOROWS(lsqlite3,
1050 "CREATE TEMPORARY TABLE " FILTER_ATTR_TABLE "\n"
1052 " attr_name TEXT PRIMARY KEY\n"
1055 /* Commit the transaction */
1056 QUERY_NOROWS(lsqlite3, FALSE, "COMMIT;");
1064 struct lsqlite3_private * lsqlite3 = p;
1066 (void) sqlite3_close(lsqlite3->sqlite);
1074 * This function is used for queries that are not expected to return any rows,
1075 * e.g. BEGIN, COMMIT, ROLLBACK, CREATE TABLE, INSERT, UPDATE, DELETE, etc.
1076 * There are no provisions here for returning data from rows in a table, so do
1077 * not pass SELECT queries to this function.
1080 query_norows(const struct lsqlite3_private *lsqlite3,
1087 sqlite3_stmt * pStmt;
1090 /* Begin access to variable argument list */
1091 va_start(args, pSql);
1093 /* Format the query */
1094 if ((p = sqlite3_vmprintf(pSql, args)) == NULL) {
1098 if (lsqlite3_debug) {
1103 * Prepare and execute the SQL statement. Loop allows retrying on
1104 * certain errors, e.g. SQLITE_SCHEMA occurs if the schema changes,
1105 * requiring retrying the operation.
1107 for (bLoop = TRUE; bLoop; ) {
1109 /* Compile the SQL statement into sqlite virtual machine */
1110 if ((ret = sqlite3_prepare(lsqlite3->sqlite,
1114 NULL)) == SQLITE_SCHEMA) {
1116 } else if (ret != SQLITE_OK) {
1121 /* No rows expected, so just step through machine code once */
1122 if ((ret = sqlite3_step(pStmt)) == SQLITE_SCHEMA) {
1123 (void) sqlite3_finalize(pStmt);
1125 } else if (ret != SQLITE_DONE) {
1126 (void) sqlite3_finalize(pStmt);
1131 /* Free the virtual machine */
1132 if ((ret = sqlite3_finalize(pStmt)) == SQLITE_SCHEMA) {
1133 (void) sqlite3_finalize(pStmt);
1135 } else if (ret != SQLITE_OK) {
1136 (void) sqlite3_finalize(pStmt);
1142 * Normal condition is only one time through loop. Loop is
1143 * rerun in error conditions, via "continue", above.
1149 /* All done with variable argument list */
1152 /* Free the memory we allocated for our query string */
1162 * This function is used for the common case of queries that return a single
1165 * NOTE: If more than one value is returned by the query, all but the first
1166 * one will be ignored.
1169 query_int(const struct lsqlite3_private * lsqlite3,
1177 sqlite3_stmt * pStmt;
1180 /* Begin access to variable argument list */
1181 va_start(args, pSql);
1183 /* Format the query */
1184 if ((p = sqlite3_vmprintf(pSql, args)) == NULL) {
1185 return SQLITE_NOMEM;
1188 if (lsqlite3_debug) {
1193 * Prepare and execute the SQL statement. Loop allows retrying on
1194 * certain errors, e.g. SQLITE_SCHEMA occurs if the schema changes,
1195 * requiring retrying the operation.
1197 for (bLoop = TRUE; bLoop; ) {
1199 /* Compile the SQL statement into sqlite virtual machine */
1200 if ((ret = sqlite3_prepare(lsqlite3->sqlite,
1204 NULL)) == SQLITE_SCHEMA) {
1206 } else if (ret != SQLITE_OK) {
1210 /* One row expected */
1211 if ((ret = sqlite3_step(pStmt)) == SQLITE_SCHEMA) {
1212 (void) sqlite3_finalize(pStmt);
1214 } else if (ret != SQLITE_ROW) {
1215 (void) sqlite3_finalize(pStmt);
1219 /* Get the value to be returned */
1220 *pRet = sqlite3_column_int64(pStmt, 0);
1222 /* Free the virtual machine */
1223 if ((ret = sqlite3_finalize(pStmt)) == SQLITE_SCHEMA) {
1224 (void) sqlite3_finalize(pStmt);
1226 } else if (ret != SQLITE_OK) {
1227 (void) sqlite3_finalize(pStmt);
1232 * Normal condition is only one time through loop. Loop is
1233 * rerun in error conditions, via "continue", above.
1238 /* All done with variable argument list */
1241 /* Free the memory we allocated for our query string */
1249 callback function used in call to ldb_dn_fold() for determining whether an
1250 attribute type requires case folding.
1253 case_fold_attr_required(void * hUserData,
1256 // struct ldb_module * module = hUserData;
1258 #warning "currently, all attributes require case folding"
1264 * add a single set of ldap message values to a ldb_message
1268 add_msg_attr(void * hTalloc,
1271 const char * pAttrName,
1272 const char * pAttrValue,
1275 struct ldb_message *** pppRes)
1278 struct ldb_message * msg;
1279 struct ldb_message_element * el;
1281 /* Is this a different EID than the previous one? */
1282 if (eid != prevEID) {
1283 /* Yup. Add another result to the result array */
1284 if ((x = talloc_realloc(hTalloc,
1285 *pAllocated == 0 ? NULL : pppRes,
1286 struct ldb_message *,
1287 *pAllocated + 1)) == NULL) {
1292 /* Save the new result list */
1295 /* We've allocated one more result */
1298 /* Ensure that the message is initialized */
1301 msg->num_elements = 0;
1302 msg->elements = NULL;
1303 msg->private_data = NULL;
1305 /* Same EID. Point to the previous most-recent message */
1306 msg = *pppRes[*pAllocated - 1];
1310 * Point to the most recent previous element. (If there are none,
1311 * this will point to non-allocated memory, but the pointer will never
1314 el = &msg->elements[msg->num_elements - 1];
1316 /* See if the most recent previous element has the same attr_name */
1317 if (msg->num_elements == 0 || strcmp(el->name, pAttrName) != 0) {
1319 /* It's a new attr_name. Allocate another message element */
1320 if ((el = talloc_realloc(msg,
1322 struct ldb_message_element,
1323 msg->num_elements + 1)) == NULL) {
1327 /* Save the new element */
1330 /* There's now one additional element */
1331 msg->num_elements++;
1333 /* Save the attribute name */
1335 talloc_strdup(msg->elements, pAttrName)) == NULL) {
1343 /* Initialize number of attribute values for this type */
1348 /* Increase the value array size by 1 */
1351 el->num_values == 0 ? NULL : el->values,
1353 el->num_values)) == NULL) {
1357 /* Save the new attribute value length */
1358 el->values[el->num_values].length = strlen(pAttrValue) + 1;
1360 /* Copy the new attribute value */
1361 if (talloc_memdup(el->values[el->num_values].data,
1363 el->values[el->num_values].length) == NULL) {
1367 /* We now have one additional value of this type */
1374 parsetree_to_sql(struct ldb_module *module,
1376 const struct ldb_parse_tree *t)
1385 switch(t->operation) {
1389 case LDB_OP_EXTENDED:
1390 #warning "work out how to handle bitops"
1394 ret = parsetree_to_sql(module,
1396 t->u.list.elements[0]);
1398 for (i = 1; i < t->u.list.num_elements; i++) {
1403 t->u.list.elements[i]);
1404 ret = talloc_asprintf_append(ret,
1412 ret = talloc_asprintf("(\n"
1424 t->u.list.elements[0]);
1426 for (i = 1; i < t->u.list.num_elements; i++) {
1431 t->u.list.elements[i]);
1432 ret = talloc_asprintf_append(ret,
1439 ret = talloc_asprintf("(\n"
1452 ret = talloc_asprintf(hTalloc,
1456 " WHERE eid NOT IN %s\n"
1463 /* should never occur */
1467 /* Get a case-folded copy of the attribute name */
1468 pAttrName = ldb_casefold((struct ldb_context *) module,
1472 * For simple searches, we want to retrieve the list of EIDs that
1473 * match the criteria. We accomplish this by searching the
1474 * appropriate table, ldb_attr_<attributeName>, for the eid
1475 * corresponding to all matching values.
1477 if (t->u.simple.value.length == 1 &&
1478 (*(const char *) t->u.simple.value.data) == '*') {
1480 * Special case for "attr_name=*". In this case, we want the
1481 * eid corresponding to all values in the specified attribute
1484 if ((p = sqlite3_mprintf("(\n"
1486 " FROM ldb_attr_%q\n"
1488 pAttrName)) == NULL) {
1492 if (lsqlite3_debug) {
1496 ret = talloc_strdup(hTalloc, p);
1499 } else if (strcasecmp(t->u.simple.attr, "objectclass") == 0) {
1501 * For object classes, we want to search for all objectclasses
1502 * that are subclasses as well.
1504 if ((p = sqlite3_mprintf(
1507 " FROM ldb_attr_OBJECTCLASS\n"
1508 " WHERE attr_name IN\n"
1509 " (SELECT class_name\n"
1510 " FROM ldb_objectclasses\n"
1511 " WHERE tree_key GLOB\n"
1512 " (SELECT tree_key\n"
1513 " FROM ldb_objectclasses\n"
1514 " WHERE class_name = %Q) || '*')\n"
1516 t->u.simple.value.data)) == NULL) {
1520 if (lsqlite3_debug) {
1524 ret = talloc_strdup(hTalloc, p);
1528 /* A normal query. */
1529 if ((p = sqlite3_mprintf("(\n"
1531 " FROM ldb_attr_%q\n"
1532 " WHERE attr_value = %Q\n"
1535 t->u.simple.value.data)) == NULL) {
1539 if (lsqlite3_debug) {
1543 ret = talloc_strdup(hTalloc, p);
1551 parsetree_to_attrlist(struct lsqlite3_private * lsqlite3,
1552 const struct ldb_parse_tree * t)
1556 switch(t->operation) {
1560 case LDB_OP_EXTENDED:
1561 #warning "work out how to handle bitops"
1565 if (parsetree_to_attrlist(
1567 t->u.list.elements[0]) != 0) {
1571 for (i = 1; i < t->u.list.num_elements; i++) {
1572 if (parsetree_to_attrlist(
1574 t->u.list.elements[i]) != 0) {
1582 if (parsetree_to_attrlist(
1584 t->u.list.elements[0]) != 0) {
1588 for (i = 1; i < t->u.list.num_elements; i++) {
1589 if (parsetree_to_attrlist(
1591 t->u.list.elements[i]) != 0) {
1599 if (parsetree_to_attrlist(lsqlite3,
1600 t->u.not.child) != 0) {
1607 /* should never occur */
1611 QUERY_NOROWS(lsqlite3,
1613 "INSERT OR IGNORE INTO " FILTER_ATTR_TABLE "\n"
1623 * Use the already-generated FILTER_ATTR_TABLE to create a list of attribute
1624 * table names that will be used in search queries.
1627 build_attr_table_list(void * hTalloc,
1628 struct lsqlite3_private * lsqlite3)
1635 sqlite3_stmt * pStmt;
1638 * Prepare and execute the SQL statement. Loop allows retrying on
1639 * certain errors, e.g. SQLITE_SCHEMA occurs if the schema changes,
1640 * requiring retrying the operation.
1642 for (bLoop = TRUE; bLoop; ) {
1643 /* Initialize a string to which we'll append each table name */
1644 if ((pTableList = talloc_strdup(hTalloc, "")) == NULL) {
1648 /* Compile the SQL statement into sqlite virtual machine */
1649 if ((ret = sqlite3_prepare(lsqlite3->sqlite,
1651 " FROM " FILTER_ATTR_TABLE ";",
1654 NULL)) == SQLITE_SCHEMA) {
1656 } else if (ret != SQLITE_OK) {
1661 /* Loop through the returned rows */
1662 for (ret = SQLITE_ROW; ret == SQLITE_ROW; ) {
1664 /* Get the next row */
1665 if ((ret = sqlite3_step(pStmt)) == SQLITE_ROW) {
1668 * Get value from this row and append to table
1671 p = discard_const_p(char,
1672 sqlite3_column_text(pStmt,
1678 sqlite3_column_text(pStmt, 0));
1680 /* Append it to the table list */
1681 if ((p = talloc_asprintf(
1684 *pTableList == '\0' ? "" : ",",
1685 pAttrName)) == NULL) {
1687 talloc_free(pTableList);
1691 /* We have a new table list */
1692 talloc_free(pTableList);
1697 if (ret == SQLITE_SCHEMA) {
1698 talloc_free(pTableList);
1702 /* Free the virtual machine */
1703 if ((ret = sqlite3_finalize(pStmt)) == SQLITE_SCHEMA) {
1704 (void) sqlite3_finalize(pStmt);
1706 } else if (ret != SQLITE_OK) {
1707 (void) sqlite3_finalize(pStmt);
1713 * Normal condition is only one time through loop. Loop is
1714 * rerun in error conditions, via "continue", above.
1721 talloc_free(pTableList);
1730 * Issue a series of SQL statements to implement the ADD/MODIFY/DELETE
1731 * requests in the ldb_message
1734 msg_to_sql(struct ldb_module * module,
1735 const struct ldb_message * msg,
1743 struct lsqlite3_private * lsqlite3 = module->private_data;
1745 for (i = 0; i < msg->num_elements; i++) {
1746 const struct ldb_message_element *el = &msg->elements[i];
1749 flags = LDB_FLAG_MOD_ADD;
1751 flags = el->flags & LDB_FLAG_MOD_MASK;
1754 /* Get a case-folded copy of the attribute name */
1755 pAttrName = ldb_casefold((struct ldb_context *) module,
1758 if (flags == LDB_FLAG_MOD_ADD) {
1759 /* Create the attribute table if it doesn't exist */
1760 if (new_attr(module, pAttrName) != 0) {
1765 /* For each value of the specified attribute name... */
1766 for (j = 0; j < el->num_values; j++) {
1768 /* ... bind the attribute value, if necessary */
1770 case LDB_FLAG_MOD_ADD:
1771 QUERY_NOROWS(lsqlite3,
1773 "INSERT INTO ldb_attr_%q\n"
1774 " (eid, attr_value)\n"
1778 eid, el->values[j].data);
1779 QUERY_NOROWS(lsqlite3,
1781 "INSERT INTO ldb_attribute_values"
1782 " (eid, attr_name, attr_value)"
1787 el->values[j].data);
1791 case LDB_FLAG_MOD_REPLACE:
1792 QUERY_NOROWS(lsqlite3,
1794 "UPDATE ldb_attr_%q\n"
1795 " SET attr_value = %Q\n"
1796 " WHERE eid = %lld;",
1800 QUERY_NOROWS(lsqlite3,
1802 "UPDATE ldb_attribute_values "
1803 " SET attr_value = %Q "
1804 " WHERE eid = %lld "
1805 " AND attr_name = %Q;",
1811 case LDB_FLAG_MOD_DELETE:
1812 /* No additional parameters to this query */
1813 QUERY_NOROWS(lsqlite3,
1815 "DELETE FROM ldb_attr_%q\n"
1816 " WHERE eid = %lld\n"
1817 " AND attr_value = %Q;",
1820 el->values[j].data);
1821 QUERY_NOROWS(lsqlite3,
1823 "DELETE FROM ldb_attribute_values"
1824 " WHERE eid = %lld "
1825 " AND attr_name = %Q "
1826 " AND attr_value = %Q;",
1829 el->values[j].data);
1841 new_dn(struct ldb_module * module,
1850 struct ldb_dn * pExplodedDN;
1851 struct ldb_dn_component * pComponent;
1852 struct ldb_context * ldb = module->ldb;
1853 struct lsqlite3_private * lsqlite3 = module->private_data;
1855 /* Explode and normalize the DN */
1860 case_fold_attr_required)) == NULL) {
1864 /* Allocate a string to hold the partial DN of each component */
1865 if ((pPartialDN = talloc_strdup(ldb, "")) == NULL) {
1869 /* For each component of the DN (starting with the last one)... */
1871 for (nComponent = pExplodedDN->comp_num - 1, bFirst = TRUE;
1873 nComponent--, bFirst = FALSE) {
1875 /* Point to the component */
1876 pComponent = pExplodedDN->components[nComponent];
1878 /* Add this component on to the partial DN to date */
1879 if ((p = talloc_asprintf(ldb,
1881 pComponent->component,
1883 pPartialDN)) == NULL) {
1887 /* No need for the old partial DN any more */
1888 talloc_free(pPartialDN);
1890 /* Save the new partial DN */
1894 * Ensure that an entry is in the ldb_entry table for this
1895 * component. Any component other than the last one
1896 * (component 0) may already exist. It is an error if
1897 * component 0 (the full DN requested to be be inserted)
1900 QUERY_NOROWS(lsqlite3,
1902 "INSERT %s INTO ldb_entry\n"
1906 nComponent == 0 ? "" : "OR IGNORE",
1909 /* Get the EID of the just inserted row (the next parent) */
1910 eid = sqlite3_last_insert_rowid(lsqlite3->sqlite);
1912 /* If this is the final component, also add DN attribute */
1913 if (nComponent == 0) {
1914 QUERY_NOROWS(lsqlite3,
1916 "INSERT %s INTO ldb_attr_DN\n"
1917 " (eid, attr_value) "
1920 nComponent == 0 ? "" : "OR IGNORE",
1925 /* Give 'em what they came for! */
1933 new_attr(struct ldb_module * module,
1937 struct lsqlite3_private * lsqlite3 = module->private_data;
1941 * pAttrName is assumed to already be case-folded here!
1944 /* See if the table already exists */
1948 "SELECT COUNT(*) <> 0\n"
1949 " FROM sqlite_master\n"
1950 " WHERE type = 'table'\n"
1951 " AND tbl_name = 'ldb_attr_%q';",
1956 /* Nope. Create the table */
1957 QUERY_NOROWS(lsqlite3,
1959 "CREATE TABLE ldb_attr_%q\n"
1961 " eid INTEGER REFERENCES ldb_entry,\n"
1962 " attr_value TEXT\n"