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);
170 #ifdef NEED_TABLE_LIST
172 build_attr_table_list(void * hTalloc,
173 struct lsqlite3_private * lsqlite3);
177 msg_to_sql(struct ldb_module * module,
178 const struct ldb_message * msg,
183 new_dn(struct ldb_module * module,
188 new_attr(struct ldb_module * module,
193 * Table of operations for the sqlite3 backend
195 static const struct ldb_module_ops lsqlite3_ops = {
197 .search = lsqlite3_search,
198 .search_bytree = lsqlite3_search_bytree,
199 .add_record = lsqlite3_add,
200 .modify_record = lsqlite3_modify,
201 .delete_record = lsqlite3_delete,
202 .rename_record = lsqlite3_rename,
203 .named_lock = lsqlite3_lock,
204 .named_unlock = lsqlite3_unlock,
205 .errstring = lsqlite3_errstring
217 * connect to the database
219 int lsqlite3_connect(struct ldb_context *ldb,
222 const char *options[])
226 struct ldb_context * ldb = NULL;
227 struct lsqlite3_private * lsqlite3 = NULL;
229 lsqlite3 = talloc(ldb, struct lsqlite3_private);
234 lsqlite3->sqlite = NULL;
235 lsqlite3->options = NULL;
236 lsqlite3->lock_count = 0;
238 ret = initialize(lsqlite3, url);
239 if (ret != SQLITE_OK) {
243 talloc_set_destructor(lsqlite3, destructor);
245 ldb->modules = talloc(ldb, struct ldb_module);
249 ldb->modules->ldb = ldb;
250 ldb->modules->prev = ldb->modules->next = NULL;
251 ldb->modules->private_data = lsqlite3;
252 ldb->modules->ops = &lsqlite3_ops;
256 * take a copy of the options array, so we don't have to rely
257 * on the caller keeping it around (it might be dynamic)
259 for (i=0;options[i];i++) ;
261 lsqlite3->options = talloc_array(lsqlite3, char *, i+1);
262 if (!lsqlite3->options) {
266 for (i=0;options[i];i++) {
268 lsqlite3->options[i+1] = NULL;
269 lsqlite3->options[i] =
270 talloc_strdup(lsqlite3->options, options[i]);
271 if (!lsqlite3->options[i]) {
280 if (lsqlite3->sqlite != NULL) {
281 (void) sqlite3_close(lsqlite3->sqlite);
283 talloc_free(lsqlite3);
289 * Interface functions referenced by lsqlite3_ops
292 /* rename a record */
294 lsqlite3_rename(struct ldb_module * module,
298 struct lsqlite3_private * lsqlite3 = module->private_data;
300 /* Case-fold each of the DNs */
301 pOldDN = ldb_dn_fold(module->ldb, pOldDN,
302 module, case_fold_attr_required);
303 pNewDN = ldb_dn_fold(module->ldb, pNewDN,
304 module, case_fold_attr_required);
306 QUERY_NOROWS(lsqlite3,
316 /* delete a record */
318 lsqlite3_delete(struct ldb_module * module,
325 const char * pAttrName;
326 sqlite3_stmt * pStmt;
327 struct lsqlite3_private * lsqlite3 = module->private_data;
329 /* Begin a transaction */
330 QUERY_NOROWS(lsqlite3, FALSE, "BEGIN EXCLUSIVE;");
332 /* Determine the eid of the DN being deleted */
341 /* Obtain the list of attribute names in use by this DN */
342 if ((pSql = talloc_asprintf(module->ldb,
344 " FROM ldb_attribute_values "
345 " WHERE eid = %lld;",
351 * Prepare and execute the SQL statement. Loop allows retrying on
352 * certain errors, e.g. SQLITE_SCHEMA occurs if the schema changes,
353 * requiring retrying the operation.
355 for (bLoop = TRUE; bLoop; ) {
356 /* Compile the SQL statement into sqlite virtual machine */
357 if ((ret = sqlite3_prepare(lsqlite3->sqlite,
361 NULL)) == SQLITE_SCHEMA) {
363 } else if (ret != SQLITE_OK) {
368 /* Loop through the returned rows */
369 for (ret = SQLITE_ROW; ret == SQLITE_ROW; ) {
371 /* Get the next row */
372 if ((ret = sqlite3_step(pStmt)) == SQLITE_ROW) {
374 /* Get the values from this row */
375 pAttrName = sqlite3_column_text(pStmt, 0);
378 * Delete any entries from the specified
379 * attribute table that pertain to this eid.
381 QUERY_NOROWS(lsqlite3,
383 "DELETE FROM ldb_attr_%q "
384 " WHERE eid = %lld;",
389 if (ret == SQLITE_SCHEMA) {
390 (void) sqlite3_finalize(pStmt);
392 } else if (ret != SQLITE_DONE) {
393 (void) sqlite3_finalize(pStmt);
398 /* Free the virtual machine */
399 if ((ret = sqlite3_finalize(pStmt)) == SQLITE_SCHEMA) {
400 (void) sqlite3_finalize(pStmt);
402 } else if (ret != SQLITE_OK) {
403 (void) sqlite3_finalize(pStmt);
409 * Normal condition is only one time through loop. Loop is
410 * rerun in error conditions, via "continue", above.
416 /* Delete the descendants records */
417 QUERY_NOROWS(lsqlite3,
419 "DELETE FROM ldb_descendants "
420 " WHERE deid = %lld;",
423 /* Delete attribute/value table entries pertaining to this DN */
424 QUERY_NOROWS(lsqlite3,
426 "DELETE FROM ldb_attribute_value "
427 " WHERE eid = %lld;",
430 /* Commit the transaction */
431 QUERY_NOROWS(lsqlite3, TRUE, "COMMIT;");
436 /* search for matching records, by tree */
438 lsqlite3_search_bytree(struct ldb_module * module,
439 const char * pBaseDN,
440 enum ldb_scope scope,
441 struct ldb_parse_tree * pTree,
442 const char * const * attrs,
443 struct ldb_message *** pppRes)
451 char * pSqlConstraints;
452 #ifdef NEED_TABLE_LIST
455 char * hTalloc = NULL;
457 const char * pAttrName;
458 const char * pAttrValue;
459 const char * pResultAttrList;
460 const char * const * pRequestedAttrs;
461 sqlite3_stmt * pStmt;
462 struct lsqlite3_private * lsqlite3 = module->private_data;
464 if (pBaseDN == NULL) {
468 /* Allocate a temporary talloc context */
469 if ((hTalloc = talloc_new(module->ldb)) == NULL) {
473 /* Case-fold the base DN */
474 if ((pBaseDN = ldb_dn_fold(hTalloc, pBaseDN,
475 module, case_fold_attr_required)) == NULL) {
476 talloc_free(hTalloc);
480 /* Begin a transaction */
481 QUERY_NOROWS(lsqlite3, FALSE, "BEGIN IMMEDIATE;");
484 * Obtain the eid of the base DN
486 if ((ret = query_int(lsqlite3,
489 " FROM ldb_attr_DN\n"
490 " WHERE attr_value = %Q;",
491 pBaseDN)) == SQLITE_DONE) {
492 QUERY_NOROWS(lsqlite3, FALSE, "ROLLBACK;");
493 talloc_free(hTalloc);
495 } else if (ret != SQLITE_OK) {
496 QUERY_NOROWS(lsqlite3, FALSE, "ROLLBACK;");
497 talloc_free(hTalloc);
501 /* Convert filter into a series of SQL conditions (constraints) */
502 pSqlConstraints = parsetree_to_sql(module, hTalloc, pTree);
504 /* Ensure we're starting with an empty result attribute table */
505 QUERY_NOROWS(lsqlite3,
507 "DELETE FROM " RESULT_ATTR_TABLE "\n"
508 " WHERE 1;");/* avoid a schema change with WHERE 1 */
510 /* Initially, we don't know what the requested attributes are */
512 /* but they didn't give us any so we'll retrieve all of 'em */
513 pResultAttrList = "";
515 /* Discover the list of attributes */
516 pResultAttrList = NULL;
519 /* Insert the list of requested attributes into this table */
520 for (pRequestedAttrs = (const char * const *) attrs;
521 pRequestedAttrs != NULL && *pRequestedAttrs != NULL;
524 /* If any attribute in the list is "*" then... */
525 if (strcmp(*pRequestedAttrs, "*") == 0) {
526 /* we want all attribute types */
527 pResultAttrList = "";
531 /* otherwise, add this name to the resuult list */
532 QUERY_NOROWS(lsqlite3,
535 " INTO " RESULT_ATTR_TABLE "\n"
543 /* If we didn't get a "*" for all attributes in the result list... */
544 if (pResultAttrList == NULL) {
545 /* ... then we'll use the result attribute table */
547 " AND av.attr_name IN\n"
548 " (SELECT attr_name\n"
549 " FROM " RESULT_ATTR_TABLE ") ";
552 /* Ensure we're starting with an empty filter attribute table */
553 QUERY_NOROWS(lsqlite3,
555 "DELETE FROM " FILTER_ATTR_TABLE "\n"
556 " WHERE 1;");/* avoid a schema change with WHERE 1 */
559 * Create a table of unique attribute names for our extra table list
561 if ((ret = parsetree_to_attrlist(lsqlite3, pTree)) != 0) {
566 #ifdef NEED_TABLE_LIST
568 * Build the attribute table list from the list of unique names.
570 if ((pTableList = build_attr_table_list(hTalloc, lsqlite3)) == NULL) {
577 case LDB_SCOPE_DEFAULT:
578 case LDB_SCOPE_SUBTREE:
579 pSql = sqlite3_mprintf(
580 "SELECT entry.eid,\n"
584 " FROM ldb_entry AS entry,\n"
585 " ldb_attribute_values AS av\n"
586 " WHERE entry.eid IN\n"
587 " (SELECT DISTINCT ldb_entry.eid\n"
590 " WHERE ldb_descendants.aeid = %lld\n"
591 " AND ldb_entry.eid = ldb_descendants.deid\n"
592 " AND ldb_entry.eid IN\n%s\n"
594 " AND av.eid = entry.eid\n"
596 " ORDER BY av.eid, av.attr_name;",
603 pSql = sqlite3_mprintf(
604 "SELECT entry.eid,\n"
608 " FROM ldb_entry AS entry,\n"
609 " ldb_attribute_values AS av\n"
610 " WHERE entry.eid IN\n"
611 " (SELECT DISTINCT ldb_entry.eid\n"
613 " WHERE ldb_entry.eid = %lld\n"
614 " AND ldb_entry.eid IN\n%s\n"
616 " AND av.eid = entry.eid\n"
618 " ORDER BY av.eid, av.attr_name;",
624 case LDB_SCOPE_ONELEVEL:
625 pSql = sqlite3_mprintf(
626 "SELECT entry.eid,\n"
630 " FROM ldb_entry AS entry,\n"
631 " ldb_attribute_values AS av\n"
632 " WHERE entry.eid IN\n"
633 " (SELECT DISTINCT ldb_entry.eid\n"
634 " FROM ldb_entry AS pchild\n"
635 " WHERE ldb_entry.eid = pchild.eid\n"
636 " AND pchild.peid = %lld\n"
637 " AND ldb_entry.eid IN\n%s\n"
639 " AND av.eid = entry.eid\n"
641 " ORDER BY av.eid, av.attr_name;\n",
653 if (lsqlite3_debug) {
654 printf("%s\n", pSql);
658 * Prepare and execute the SQL statement. Loop allows retrying on
659 * certain errors, e.g. SQLITE_SCHEMA occurs if the schema changes,
660 * requiring retrying the operation.
662 for (bLoop = TRUE; bLoop; ) {
663 /* There are no allocate message structures yet */
665 if (pppRes != NULL) {
669 /* Compile the SQL statement into sqlite virtual machine */
670 if ((ret = sqlite3_prepare(lsqlite3->sqlite,
674 NULL)) == SQLITE_SCHEMA) {
675 if (pppRes != NULL && *pppRes != NULL) {
676 talloc_free(*pppRes);
679 } else if (ret != SQLITE_OK) {
684 /* Initially, we have no previous eid */
687 /* Loop through the returned rows */
688 for (ret = SQLITE_ROW; ret == SQLITE_ROW; ) {
690 /* Get the next row */
691 if ((ret = sqlite3_step(pStmt)) == SQLITE_ROW) {
693 /* Get the values from this row */
694 eid = sqlite3_column_int64(pStmt, 0);
695 pDN = sqlite3_column_text(pStmt, 1);
696 pAttrName = sqlite3_column_text(pStmt, 2);
697 pAttrValue = sqlite3_column_text(pStmt, 3);
699 /* Add this result to the result set */
700 if ((ret = add_msg_attr(hTalloc,
709 (void) sqlite3_finalize(pStmt);
716 if (ret == SQLITE_SCHEMA) {
717 (void) sqlite3_finalize(pStmt);
718 if (pppRes != NULL && *pppRes != NULL) {
719 talloc_free(*pppRes);
722 } else if (ret != SQLITE_DONE) {
723 (void) sqlite3_finalize(pStmt);
728 /* Free the virtual machine */
729 if ((ret = sqlite3_finalize(pStmt)) == SQLITE_SCHEMA) {
730 (void) sqlite3_finalize(pStmt);
731 if (pppRes != NULL && *pppRes != NULL) {
732 talloc_free(*pppRes);
735 } else if (ret != SQLITE_OK) {
736 (void) sqlite3_finalize(pStmt);
742 * Normal condition is only one time through loop. Loop is
743 * rerun in error conditions, via "continue", above.
749 /* We're alll done with this query */
752 /* End the transaction */
753 QUERY_NOROWS(lsqlite3, FALSE, "END TRANSACTION;");
755 /* Were there any results? */
756 if (ret != 0 || allocated == 0) {
757 /* Nope. We can free the results. */
758 if (pppRes != NULL && *pppRes != NULL) {
759 talloc_free(*pppRes);
764 /* Clean up our temporary tables */
765 QUERY_NOROWS(lsqlite3,
767 "DELETE FROM " RESULT_ATTR_TABLE "\n"
768 " WHERE 1;");/* avoid a schema change with WHERE 1 */
770 QUERY_NOROWS(lsqlite3,
772 "DELETE FROM " FILTER_ATTR_TABLE "\n"
773 " WHERE 1;");/* avoid a schema change with WHERE 1 */
776 if (hTalloc != NULL) {
777 talloc_free(hTalloc);
780 /* If error, return error code; otherwise return number of results */
781 return ret == 0 ? allocated : ret;
784 /* search for matching records, by expression */
786 lsqlite3_search(struct ldb_module * module,
787 const char * pBaseDN,
788 enum ldb_scope scope,
789 const char * pExpression,
790 const char * const * attrs,
791 struct ldb_message *** pppRes)
794 struct ldb_parse_tree * pTree;
796 /* Parse the filter expression into a tree we can work with */
797 if ((pTree = ldb_parse_tree(module->ldb, pExpression)) == NULL) {
801 /* Now use the bytree function for the remainder of processing */
802 ret = lsqlite3_search_bytree(module, pBaseDN, scope,
803 pTree, attrs, pppRes);
805 /* Free the parse tree */
815 lsqlite3_add(struct ldb_module *module,
816 const struct ldb_message *msg)
819 struct lsqlite3_private * lsqlite3 = module->private_data;
821 /* ignore ltdb specials */
822 if (msg->dn[0] == '@') {
826 /* Begin a transaction */
827 QUERY_NOROWS(lsqlite3, FALSE, "BEGIN EXCLUSIVE;");
830 * Build any portions of the directory tree that don't exist. If the
831 * final component already exists, it's an error.
833 if (new_dn(module, msg->dn, &eid) != 0) {
834 QUERY_NOROWS(lsqlite3, FALSE, "ROLLBACK;");
838 /* Add attributes to this new entry */
839 if (msg_to_sql(module, msg, eid, FALSE) != 0) {
840 QUERY_NOROWS(lsqlite3, FALSE, "ROLLBACK;");
844 /* Everything worked. Commit it! */
845 QUERY_NOROWS(lsqlite3, TRUE, "COMMIT;");
850 /* modify a record */
852 lsqlite3_modify(struct ldb_module * module,
853 const struct ldb_message * msg)
857 struct lsqlite3_private * lsqlite3 = module->private_data;
859 /* ignore ltdb specials */
860 if (msg->dn[0] == '@') {
864 /* Begin a transaction */
865 QUERY_NOROWS(lsqlite3, FALSE, "BEGIN EXCLUSIVE;");
867 /* Case-fold the DN so we can compare it to what's in the database */
868 pDN = ldb_dn_fold(module->ldb, msg->dn,
869 module, case_fold_attr_required);
871 /* Determine the eid of the DN being deleted */
880 /* Apply the message attributes */
881 if (msg_to_sql(module, msg, eid, TRUE) != 0) {
882 QUERY_NOROWS(lsqlite3, FALSE, "ROLLBACK;");
887 /* Everything worked. Commit it! */
888 QUERY_NOROWS(lsqlite3, TRUE, "COMMIT;");
892 /* obtain a named lock */
894 lsqlite3_lock(struct ldb_module *module,
895 const char *lockname)
897 if (lockname == NULL) {
901 /* TODO implement a local locking mechanism here */
906 /* release a named lock */
908 lsqlite3_unlock(struct ldb_module *module,
909 const char *lockname)
911 if (lockname == NULL) {
915 /* TODO implement a local locking mechanism here */
920 /* return extended error information */
922 lsqlite3_errstring(struct ldb_module *module)
924 struct lsqlite3_private * lsqlite3 = module->private_data;
926 return sqlite3_errmsg(lsqlite3->sqlite);
937 initialize(struct lsqlite3_private *lsqlite3,
944 const char * schema =
947 "CREATE TABLE ldb_info AS "
948 " SELECT 'LDB' AS database_type,"
952 * The entry table holds the information about an entry.
953 * This table is used to obtain the EID of the entry and to
954 * support scope=one and scope=base. The parent and child
955 * table is included in the entry table since all the other
956 * attributes are dependent on EID.
958 "CREATE TABLE ldb_entry "
960 " eid INTEGER PRIMARY KEY,"
961 " peid INTEGER REFERENCES ldb_entry,"
963 " create_timestamp INTEGER,"
964 " modify_timestamp INTEGER"
969 * The purpose of the descendant table is to support the
970 * subtree search feature. For each LDB entry with a unique
971 * ID (AEID), this table contains the unique identifiers
972 * (DEID) of the descendant entries.
974 * For evern entry in the directory, a row exists in this
975 * table for each of its ancestors including itself. The
976 * size of the table depends on the depth of each entry. In
977 * the worst case, if all the entries were at the same
978 * depth, the number of rows in the table is O(nm) where
979 * n is the number of nodes in the directory and m is the
982 "CREATE TABLE ldb_descendants "
984 " aeid INTEGER REFERENCES ldb_entry,"
985 " deid INTEGER REFERENCES ldb_entry"
989 "CREATE TABLE ldb_object_classes"
991 " class_name TEXT PRIMARY KEY,"
992 " tree_key TEXT UNIQUE"
996 * We keep a full listing of attribute/value pairs here
998 "CREATE TABLE ldb_attribute_values"
1000 " eid INTEGER REFERENCES ldb_entry,"
1006 * There is one attribute table per searchable attribute.
1009 "CREATE TABLE ldb_attr_ATTRIBUTE_NAME"
1011 " eid INTEGER REFERENCES ldb_entry,"
1017 * We pre-create the dn attribute table
1019 "CREATE TABLE ldb_attr_DN"
1021 " eid INTEGER REFERENCES ldb_entry,"
1027 * We pre-create the objectclass attribute table
1029 "CREATE TABLE ldb_attr_OBJECTCLASS"
1031 " eid INTEGER REFERENCES ldb_entry,"
1045 "CREATE TRIGGER ldb_entry_insert_tr"
1051 " SET create_timestamp = strftime('%s', 'now'),"
1052 " modify_timestamp = strftime('%s', 'now')"
1053 " WHERE eid = new.eid;"
1056 "CREATE TRIGGER ldb_entry_update_tr"
1062 " SET modify_timestamp = strftime('%s', 'now')"
1063 " WHERE eid = old.eid;"
1067 * Table initialization
1071 "INSERT INTO ldb_entry "
1076 /* And the root node "dn" attribute */
1077 "INSERT INTO ldb_attr_DN "
1078 " (eid, attr_value) "
1084 /* Skip protocol indicator of url */
1085 if (strncmp(url, "sqlite://", 9) != 0) {
1086 return SQLITE_MISUSE;
1089 /* Update pointer to just after the protocol indicator */
1092 /* Try to open the (possibly empty/non-existent) database */
1093 if ((ret = sqlite3_open(url, &lsqlite3->sqlite)) != SQLITE_OK) {
1097 /* In case this is a new database, enable auto_vacuum */
1098 QUERY_NOROWS(lsqlite3, FALSE, "PRAGMA auto_vacuum=1;");
1100 /* Begin a transaction */
1101 QUERY_NOROWS(lsqlite3, FALSE, "BEGIN EXCLUSIVE;");
1103 /* Determine if this is a new database. No tables means it is. */
1108 " FROM sqlite_master\n"
1109 " WHERE type = 'table';");
1111 if (queryInt == 0) {
1113 * Create the database schema
1115 for (pTail = discard_const_p(char, schema);
1116 pTail != NULL && *pTail != '\0';
1119 if (lsqlite3_debug) {
1120 printf("Execute first query in:\n%s\n", pTail);
1123 if ((ret = sqlite3_prepare(
1128 &pTail)) != SQLITE_OK ||
1129 (ret = sqlite3_step(stmt)) != SQLITE_DONE ||
1130 (ret = sqlite3_finalize(stmt)) != SQLITE_OK) {
1132 QUERY_NOROWS(lsqlite3, FALSE, "ROLLBACK;");
1133 (void) sqlite3_close(lsqlite3->sqlite);
1139 * Ensure that the database we opened is one of ours
1141 if (query_int(lsqlite3,
1144 " (SELECT COUNT(*) = 3"
1145 " FROM sqlite_master "
1146 " WHERE type = 'table' "
1150 " 'ldb_descendants', "
1151 " 'ldb_object_classes' "
1157 " WHERE database_type = 'LDB' "
1158 " AND version = '1.0'"
1162 /* It's not one that we created. See ya! */
1163 QUERY_NOROWS(lsqlite3, FALSE, "ROLLBACK;");
1164 (void) sqlite3_close(lsqlite3->sqlite);
1165 return SQLITE_MISUSE;
1170 * Create a temporary table to hold attributes requested in the result
1173 QUERY_NOROWS(lsqlite3,
1175 "CREATE TEMPORARY TABLE " RESULT_ATTR_TABLE "\n"
1177 " attr_name TEXT PRIMARY KEY\n"
1181 * Create a temporary table to hold the attributes used by filters
1184 QUERY_NOROWS(lsqlite3,
1186 "CREATE TEMPORARY TABLE " FILTER_ATTR_TABLE "\n"
1188 " attr_name TEXT PRIMARY KEY\n"
1191 /* Commit the transaction */
1192 QUERY_NOROWS(lsqlite3, FALSE, "COMMIT;");
1200 struct lsqlite3_private * lsqlite3 = p;
1202 if (lsqlite3->sqlite) {
1203 sqlite3_close(lsqlite3->sqlite);
1212 * This function is used for queries that are not expected to return any rows,
1213 * e.g. BEGIN, COMMIT, ROLLBACK, CREATE TABLE, INSERT, UPDATE, DELETE, etc.
1214 * There are no provisions here for returning data from rows in a table, so do
1215 * not pass SELECT queries to this function.
1218 query_norows(const struct lsqlite3_private *lsqlite3,
1225 sqlite3_stmt * pStmt;
1228 /* Begin access to variable argument list */
1229 va_start(args, pSql);
1231 /* Format the query */
1232 if ((p = sqlite3_vmprintf(pSql, args)) == NULL) {
1236 if (lsqlite3_debug) {
1241 * Prepare and execute the SQL statement. Loop allows retrying on
1242 * certain errors, e.g. SQLITE_SCHEMA occurs if the schema changes,
1243 * requiring retrying the operation.
1245 for (bLoop = TRUE; bLoop; ) {
1247 /* Compile the SQL statement into sqlite virtual machine */
1248 if ((ret = sqlite3_prepare(lsqlite3->sqlite,
1252 NULL)) == SQLITE_SCHEMA) {
1254 } else if (ret != SQLITE_OK) {
1259 /* No rows expected, so just step through machine code once */
1260 if ((ret = sqlite3_step(pStmt)) == SQLITE_SCHEMA) {
1261 (void) sqlite3_finalize(pStmt);
1263 } else if (ret != SQLITE_DONE) {
1264 (void) sqlite3_finalize(pStmt);
1269 /* Free the virtual machine */
1270 if ((ret = sqlite3_finalize(pStmt)) == SQLITE_SCHEMA) {
1271 (void) sqlite3_finalize(pStmt);
1273 } else if (ret != SQLITE_OK) {
1274 (void) sqlite3_finalize(pStmt);
1280 * Normal condition is only one time through loop. Loop is
1281 * rerun in error conditions, via "continue", above.
1287 /* All done with variable argument list */
1290 /* Free the memory we allocated for our query string */
1300 * This function is used for the common case of queries that return a single
1303 * NOTE: If more than one value is returned by the query, all but the first
1304 * one will be ignored.
1307 query_int(const struct lsqlite3_private * lsqlite3,
1315 sqlite3_stmt * pStmt;
1318 /* Begin access to variable argument list */
1319 va_start(args, pSql);
1321 /* Format the query */
1322 if ((p = sqlite3_vmprintf(pSql, args)) == NULL) {
1323 return SQLITE_NOMEM;
1326 if (lsqlite3_debug) {
1331 * Prepare and execute the SQL statement. Loop allows retrying on
1332 * certain errors, e.g. SQLITE_SCHEMA occurs if the schema changes,
1333 * requiring retrying the operation.
1335 for (bLoop = TRUE; bLoop; ) {
1337 /* Compile the SQL statement into sqlite virtual machine */
1338 if ((ret = sqlite3_prepare(lsqlite3->sqlite,
1342 NULL)) == SQLITE_SCHEMA) {
1344 } else if (ret != SQLITE_OK) {
1348 /* One row expected */
1349 if ((ret = sqlite3_step(pStmt)) == SQLITE_SCHEMA) {
1350 (void) sqlite3_finalize(pStmt);
1352 } else if (ret != SQLITE_ROW) {
1353 (void) sqlite3_finalize(pStmt);
1357 /* Get the value to be returned */
1358 *pRet = sqlite3_column_int64(pStmt, 0);
1360 /* Free the virtual machine */
1361 if ((ret = sqlite3_finalize(pStmt)) == SQLITE_SCHEMA) {
1362 (void) sqlite3_finalize(pStmt);
1364 } else if (ret != SQLITE_OK) {
1365 (void) sqlite3_finalize(pStmt);
1370 * Normal condition is only one time through loop. Loop is
1371 * rerun in error conditions, via "continue", above.
1376 /* All done with variable argument list */
1379 /* Free the memory we allocated for our query string */
1387 callback function used in call to ldb_dn_fold() for determining whether an
1388 attribute type requires case folding.
1391 case_fold_attr_required(void * hUserData,
1394 // struct ldb_module * module = hUserData;
1396 #warning "currently, all attributes require case folding"
1402 * add a single set of ldap message values to a ldb_message
1406 add_msg_attr(void * hTalloc,
1409 const char * pAttrName,
1410 const char * pAttrValue,
1413 struct ldb_message *** pppRes)
1416 struct ldb_message * msg;
1417 struct ldb_message_element * el;
1419 /* Is this a different EID than the previous one? */
1420 if (eid != prevEID) {
1421 /* Yup. Add another result to the result array */
1422 if ((x = talloc_realloc(hTalloc,
1423 *pAllocated == 0 ? NULL : pppRes,
1424 struct ldb_message *,
1425 *pAllocated + 1)) == NULL) {
1430 /* Save the new result list */
1433 /* We've allocated one more result */
1436 /* Ensure that the message is initialized */
1439 msg->num_elements = 0;
1440 msg->elements = NULL;
1441 msg->private_data = NULL;
1443 /* Same EID. Point to the previous most-recent message */
1444 msg = *pppRes[*pAllocated - 1];
1448 * Point to the most recent previous element. (If there are none,
1449 * this will point to non-allocated memory, but the pointer will never
1452 el = &msg->elements[msg->num_elements - 1];
1454 /* See if the most recent previous element has the same attr_name */
1455 if (msg->num_elements == 0 || strcmp(el->name, pAttrName) != 0) {
1457 /* It's a new attr_name. Allocate another message element */
1458 if ((el = talloc_realloc(msg,
1460 struct ldb_message_element,
1461 msg->num_elements + 1)) == NULL) {
1465 /* Save the new element */
1468 /* There's now one additional element */
1469 msg->num_elements++;
1471 /* Save the attribute name */
1473 talloc_strdup(msg->elements, pAttrName)) == NULL) {
1481 /* Initialize number of attribute values for this type */
1486 /* Increase the value array size by 1 */
1489 el->num_values == 0 ? NULL : el->values,
1491 el->num_values)) == NULL) {
1495 /* Save the new attribute value length */
1496 el->values[el->num_values].length = strlen(pAttrValue) + 1;
1498 /* Copy the new attribute value */
1499 if (talloc_memdup(el->values[el->num_values].data,
1501 el->values[el->num_values].length) == NULL) {
1505 /* We now have one additional value of this type */
1512 parsetree_to_sql(struct ldb_module *module,
1514 const struct ldb_parse_tree *t)
1523 switch(t->operation) {
1527 case LDB_OP_EXTENDED:
1528 #warning "work out how to handle bitops"
1532 ret = parsetree_to_sql(module,
1534 t->u.list.elements[0]);
1536 for (i = 1; i < t->u.list.num_elements; i++) {
1541 t->u.list.elements[i]);
1542 ret = talloc_asprintf_append(ret,
1550 ret = talloc_asprintf(hTalloc,
1563 t->u.list.elements[0]);
1565 for (i = 1; i < t->u.list.num_elements; i++) {
1570 t->u.list.elements[i]);
1571 ret = talloc_asprintf_append(ret,
1578 ret = talloc_asprintf(hTalloc,
1592 ret = talloc_asprintf(hTalloc,
1596 " WHERE eid NOT IN %s\n"
1603 /* should never occur */
1607 /* Get a case-folded copy of the attribute name */
1608 pAttrName = ldb_casefold((struct ldb_context *) module,
1612 * For simple searches, we want to retrieve the list of EIDs that
1613 * match the criteria. We accomplish this by searching the
1614 * appropriate table, ldb_attr_<attributeName>, for the eid
1615 * corresponding to all matching values.
1617 if (t->u.simple.value.length == 1 &&
1618 (*(const char *) t->u.simple.value.data) == '*') {
1620 * Special case for "attr_name=*". In this case, we want the
1621 * eid corresponding to all values in the specified attribute
1624 if ((p = sqlite3_mprintf("(\n"
1626 " FROM ldb_attr_%q\n"
1628 pAttrName)) == NULL) {
1632 if (lsqlite3_debug) {
1636 ret = talloc_strdup(hTalloc, p);
1639 } else if (strcasecmp(t->u.simple.attr, "objectclass") == 0) {
1641 * For object classes, we want to search for all objectclasses
1642 * that are subclasses as well.
1644 if ((p = sqlite3_mprintf(
1647 " FROM ldb_attr_OBJECTCLASS\n"
1648 " WHERE attr_name IN\n"
1649 " (SELECT class_name\n"
1650 " FROM ldb_objectclasses\n"
1651 " WHERE tree_key GLOB\n"
1652 " (SELECT tree_key\n"
1653 " FROM ldb_objectclasses\n"
1654 " WHERE class_name = %Q) || '*')\n"
1656 t->u.simple.value.data)) == NULL) {
1660 if (lsqlite3_debug) {
1664 ret = talloc_strdup(hTalloc, p);
1668 /* A normal query. */
1669 if ((p = sqlite3_mprintf("(\n"
1671 " FROM ldb_attr_%q\n"
1672 " WHERE attr_value = %Q\n"
1675 t->u.simple.value.data)) == NULL) {
1679 if (lsqlite3_debug) {
1683 ret = talloc_strdup(hTalloc, p);
1692 parsetree_to_attrlist(struct lsqlite3_private * lsqlite3,
1693 const struct ldb_parse_tree * t)
1697 switch(t->operation) {
1701 case LDB_OP_EXTENDED:
1702 #warning "work out how to handle bitops"
1706 if (parsetree_to_attrlist(
1708 t->u.list.elements[0]) != 0) {
1712 for (i = 1; i < t->u.list.num_elements; i++) {
1713 if (parsetree_to_attrlist(
1715 t->u.list.elements[i]) != 0) {
1723 if (parsetree_to_attrlist(
1725 t->u.list.elements[0]) != 0) {
1729 for (i = 1; i < t->u.list.num_elements; i++) {
1730 if (parsetree_to_attrlist(
1732 t->u.list.elements[i]) != 0) {
1740 if (parsetree_to_attrlist(lsqlite3,
1741 t->u.not.child) != 0) {
1748 /* should never occur */
1752 QUERY_NOROWS(lsqlite3,
1754 "INSERT OR IGNORE INTO " FILTER_ATTR_TABLE "\n"
1763 #ifdef NEED_TABLE_LIST
1765 * Use the already-generated FILTER_ATTR_TABLE to create a list of attribute
1766 * table names that will be used in search queries.
1769 build_attr_table_list(void * hTalloc,
1770 struct lsqlite3_private * lsqlite3)
1777 sqlite3_stmt * pStmt;
1780 * Prepare and execute the SQL statement. Loop allows retrying on
1781 * certain errors, e.g. SQLITE_SCHEMA occurs if the schema changes,
1782 * requiring retrying the operation.
1784 for (bLoop = TRUE; bLoop; ) {
1785 /* Initialize a string to which we'll append each table name */
1786 if ((pTableList = talloc_strdup(hTalloc, "")) == NULL) {
1790 /* Compile the SQL statement into sqlite virtual machine */
1791 if ((ret = sqlite3_prepare(lsqlite3->sqlite,
1793 " FROM " FILTER_ATTR_TABLE ";",
1796 NULL)) == SQLITE_SCHEMA) {
1798 } else if (ret != SQLITE_OK) {
1803 /* Loop through the returned rows */
1804 for (ret = SQLITE_ROW; ret == SQLITE_ROW; ) {
1806 /* Get the next row */
1807 if ((ret = sqlite3_step(pStmt)) == SQLITE_ROW) {
1810 * Get value from this row and append to table
1813 p = discard_const_p(char,
1814 sqlite3_column_text(pStmt,
1820 sqlite3_column_text(pStmt, 0));
1822 /* Append it to the table list */
1823 if ((p = talloc_asprintf(
1826 *pTableList == '\0' ? "" : ",",
1827 pAttrName)) == NULL) {
1829 talloc_free(pTableList);
1833 /* We have a new table list */
1834 talloc_free(pTableList);
1839 if (ret == SQLITE_SCHEMA) {
1840 talloc_free(pTableList);
1844 /* Free the virtual machine */
1845 if ((ret = sqlite3_finalize(pStmt)) == SQLITE_SCHEMA) {
1846 (void) sqlite3_finalize(pStmt);
1848 } else if (ret != SQLITE_OK) {
1849 (void) sqlite3_finalize(pStmt);
1855 * Normal condition is only one time through loop. Loop is
1856 * rerun in error conditions, via "continue", above.
1863 talloc_free(pTableList);
1873 * Issue a series of SQL statements to implement the ADD/MODIFY/DELETE
1874 * requests in the ldb_message
1877 msg_to_sql(struct ldb_module * module,
1878 const struct ldb_message * msg,
1886 struct lsqlite3_private * lsqlite3 = module->private_data;
1888 for (i = 0; i < msg->num_elements; i++) {
1889 const struct ldb_message_element *el = &msg->elements[i];
1892 flags = LDB_FLAG_MOD_ADD;
1894 flags = el->flags & LDB_FLAG_MOD_MASK;
1897 /* Get a case-folded copy of the attribute name */
1898 pAttrName = ldb_casefold((struct ldb_context *) module,
1901 if (flags == LDB_FLAG_MOD_ADD) {
1902 /* Create the attribute table if it doesn't exist */
1903 if (new_attr(module, pAttrName) != 0) {
1908 /* For each value of the specified attribute name... */
1909 for (j = 0; j < el->num_values; j++) {
1911 /* ... bind the attribute value, if necessary */
1913 case LDB_FLAG_MOD_ADD:
1914 QUERY_NOROWS(lsqlite3,
1916 "INSERT INTO ldb_attr_%q\n"
1917 " (eid, attr_value)\n"
1921 eid, el->values[j].data);
1922 QUERY_NOROWS(lsqlite3,
1924 "INSERT INTO ldb_attribute_values"
1925 " (eid, attr_name, attr_value)"
1930 el->values[j].data);
1934 case LDB_FLAG_MOD_REPLACE:
1935 QUERY_NOROWS(lsqlite3,
1937 "UPDATE ldb_attr_%q\n"
1938 " SET attr_value = %Q\n"
1939 " WHERE eid = %lld;",
1943 QUERY_NOROWS(lsqlite3,
1945 "UPDATE ldb_attribute_values "
1946 " SET attr_value = %Q "
1947 " WHERE eid = %lld "
1948 " AND attr_name = %Q;",
1954 case LDB_FLAG_MOD_DELETE:
1955 /* No additional parameters to this query */
1956 QUERY_NOROWS(lsqlite3,
1958 "DELETE FROM ldb_attr_%q\n"
1959 " WHERE eid = %lld\n"
1960 " AND attr_value = %Q;",
1963 el->values[j].data);
1964 QUERY_NOROWS(lsqlite3,
1966 "DELETE FROM ldb_attribute_values"
1967 " WHERE eid = %lld "
1968 " AND attr_name = %Q "
1969 " AND attr_value = %Q;",
1972 el->values[j].data);
1984 new_dn(struct ldb_module * module,
1994 struct ldb_dn * pExplodedDN;
1995 struct ldb_dn_component * pComponent;
1996 struct ldb_context * ldb = module->ldb;
1997 struct lsqlite3_private * lsqlite3 = module->private_data;
1999 /* Explode and normalize the DN */
2004 case_fold_attr_required)) == NULL) {
2008 /* Allocate a string to hold the partial DN of each component */
2009 if ((pPartialDN = talloc_strdup(ldb, "")) == NULL) {
2013 /* For each component of the DN (starting with the last one)... */
2015 for (nComponent = pExplodedDN->comp_num - 1, bFirst = TRUE;
2017 nComponent--, bFirst = FALSE) {
2019 /* Point to the component */
2020 pComponent = pExplodedDN->components[nComponent];
2022 /* Add this component on to the partial DN to date */
2023 if ((p = talloc_asprintf(ldb,
2025 pComponent->component,
2027 pPartialDN)) == NULL) {
2031 /* No need for the old partial DN any more */
2032 talloc_free(pPartialDN);
2034 /* Save the new partial DN */
2038 * Ensure that an entry is in the ldb_entry table for this
2039 * component. Any component other than the last one
2040 * (component 0) may already exist. It is an error if
2041 * component 0 (the full DN requested to be be inserted)
2044 QUERY_NOROWS(lsqlite3,
2046 "INSERT %s INTO ldb_entry\n"
2050 nComponent == 0 ? "" : "OR IGNORE",
2053 /* Save the parent EID */
2056 /* Get the EID of the just inserted row */
2057 eid = sqlite3_last_insert_rowid(lsqlite3->sqlite);
2060 * Popoulate the descendant table
2063 /* This table has an entry for itself as well as descendants */
2064 QUERY_NOROWS(lsqlite3,
2066 "INSERT INTO ldb_descendants "
2072 /* Now insert rows for all of our ancestors */
2073 QUERY_NOROWS(lsqlite3,
2075 "INSERT INTO ldb_descendants "
2077 " SELECT aeid, %lld "
2078 " FROM ldb_descendants "
2079 " WHERE aeid = %lld;",
2082 /* If this is the final component, also add DN attribute */
2083 if (nComponent == 0) {
2084 QUERY_NOROWS(lsqlite3,
2086 "INSERT %s INTO ldb_attr_DN\n"
2087 " (eid, attr_value) "
2090 nComponent == 0 ? "" : "OR IGNORE",
2095 /* Give 'em what they came for! */
2103 new_attr(struct ldb_module * module,
2107 struct lsqlite3_private * lsqlite3 = module->private_data;
2111 * pAttrName is assumed to already be case-folded here!
2114 /* See if the table already exists */
2118 "SELECT COUNT(*) <> 0\n"
2119 " FROM sqlite_master\n"
2120 " WHERE type = 'table'\n"
2121 " AND tbl_name = 'ldb_attr_%q';",
2126 /* Nope. Create the table */
2127 QUERY_NOROWS(lsqlite3,
2129 "CREATE TABLE ldb_attr_%q\n"
2131 " eid INTEGER REFERENCES ldb_entry,\n"
2132 " attr_value TEXT\n"