r10477: expose transactions outside ldb and change the API once more
[kai/samba-autobuild/.git] / source4 / lib / ldb / ldb_sqlite3 / ldb_sqlite3.c
1 /* 
2    ldb database library
3    
4    Copyright (C) Derrell Lipman  2005
5    Copyright (C) Simo Sorce 2005
6    
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
10    
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.
15    
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.
20    
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
24 */
25
26 /*
27  *  Name: ldb
28  *
29  *  Component: ldb sqlite3 backend
30  *
31  *  Description: core files for SQLITE3 backend
32  *
33  *  Author: Derrell Lipman (based on Andrew Tridgell's LDAP backend)
34  */
35
36 #include <stdarg.h>
37 #include "includes.h"
38 #include "ldb/include/ldb.h"
39 #include "ldb/include/ldb_errors.h"
40 #include "ldb/include/ldb_private.h"
41 #include "ldb/ldb_sqlite3/ldb_sqlite3.h"
42
43 /*
44  * Macros used throughout
45  */
46
47 #ifndef FALSE
48 # define FALSE  (0)
49 # define TRUE   (! FALSE)
50 #endif
51
52 #define RESULT_ATTR_TABLE       "temp_result_attrs"
53
54 //#define TEMPTAB                 /* for testing, create non-temporary table */
55 #define TEMPTAB                 "TEMPORARY"
56
57 /*
58  * Static variables
59  */
60 sqlite3_stmt *  stmtGetEID = NULL;
61
62 static char *lsqlite3_tprintf(TALLOC_CTX *mem_ctx, const char *fmt, ...)
63 {
64         char *str, *ret;
65         va_list ap;
66
67         va_start(ap, fmt);
68         str = sqlite3_vmprintf(fmt, ap);
69         va_end(ap);
70
71         if (str == NULL) return NULL;
72
73         ret = talloc_strdup(mem_ctx, str);
74         if (ret == NULL) {
75                 sqlite3_free(str);
76                 return NULL;
77         }
78
79         sqlite3_free(str);
80         return ret;
81 }
82
83 static unsigned char        base160tab[161] = {
84         48 ,49 ,50 ,51 ,52 ,53 ,54 ,55 ,56 ,57 , /* 0-9 */
85         58 ,59 ,65 ,66 ,67 ,68 ,69 ,70 ,71 ,72 , /* : ; A-H */
86         73 ,74 ,75 ,76 ,77 ,78 ,79 ,80 ,81 ,82 , /* I-R */
87         83 ,84 ,85 ,86 ,87 ,88 ,89 ,90 ,97 ,98 , /* S-Z , a-b */
88         99 ,100,101,102,103,104,105,106,107,108, /* c-l */
89         109,110,111,112,113,114,115,116,117,118, /* m-v */
90         119,120,121,122,160,161,162,163,164,165, /* w-z, latin1 */
91         166,167,168,169,170,171,172,173,174,175, /* latin1 */
92         176,177,178,179,180,181,182,183,184,185, /* latin1 */
93         186,187,188,189,190,191,192,193,194,195, /* latin1 */
94         196,197,198,199,200,201,202,203,204,205, /* latin1 */
95         206,207,208,209,210,211,212,213,214,215, /* latin1 */
96         216,217,218,219,220,221,222,223,224,225, /* latin1 */
97         226,227,228,229,230,231,232,233,234,235, /* latin1 */
98         236,237,238,239,240,241,242,243,244,245, /* latin1 */
99         246,247,248,249,250,251,252,253,254,255, /* latin1 */
100         '\0'
101 };
102
103
104 /*
105  * base160()
106  *
107  * Convert an unsigned long integer into a base160 representation of the
108  * number.
109  *
110  * Parameters:
111  *   val --
112  *     value to be converted
113  *
114  *   result --
115  *     character array, 5 bytes long, into which the base160 representation
116  *     will be placed.  The result will be a four-digit representation of the
117  *     number (with leading zeros prepended as necessary), and null
118  *     terminated.
119  *
120  * Returns:
121  *   Nothing
122  */
123 static void
124 base160_sql(sqlite3_context * hContext,
125             int argc,
126             sqlite3_value ** argv)
127 {
128     int             i;
129     long long       val;
130     char            result[5];
131
132     val = sqlite3_value_int64(argv[0]);
133
134     for (i = 3; i >= 0; i--) {
135         
136         result[i] = base160tab[val % 160];
137         val /= 160;
138     }
139
140     result[4] = '\0';
141
142     sqlite3_result_text(hContext, result, -1, SQLITE_TRANSIENT);
143 }
144
145
146 /*
147  * base160next_sql()
148  *
149  * This function enhances sqlite by adding a "base160_next()" function which is
150  * accessible via queries.
151  *
152  * Retrieve the next-greater number in the base160 sequence for the terminal
153  * tree node (the last four digits).  Only one tree level (four digits) is
154  * operated on.
155  *
156  * Input:
157  *   A character string: either an empty string (in which case no operation is
158  *   performed), or a string of base160 digits with a length of a multiple of
159  *   four digits.
160  *
161  * Output:
162  *   Upon return, the trailing four digits (one tree level) will have been
163  *   incremented by 1.
164  */
165 static void
166 base160next_sql(sqlite3_context * hContext,
167                 int argc,
168                 sqlite3_value ** argv)
169 {
170         int                         i;
171         int                         len;
172         unsigned char *             pTab;
173         unsigned char *             pBase160 =
174                 strdup(sqlite3_value_text(argv[0]));
175         unsigned char *             pStart = pBase160;
176
177         /*
178          * We need a minimum of four digits, and we will always get a multiple
179          * of four digits.
180          */
181         if (pBase160 != NULL &&
182             (len = strlen(pBase160)) >= 4 &&
183             len % 4 == 0) {
184
185                 if (pBase160 == NULL) {
186
187                         sqlite3_result_null(hContext);
188                         return;
189                 }
190
191                 pBase160 += strlen(pBase160) - 1;
192
193                 /* We only carry through four digits: one level in the tree */
194                 for (i = 0; i < 4; i++) {
195
196                         /* What base160 value does this digit have? */
197                         pTab = strchr(base160tab, *pBase160);
198
199                         /* Is there a carry? */
200                         if (pTab < base160tab + sizeof(base160tab) - 1) {
201
202                                 /*
203                                  * Nope.  Just increment this value and we're
204                                  * done.
205                                  */
206                                 *pBase160 = *++pTab;
207                                 break;
208                         } else {
209
210                                 /*
211                                  * There's a carry.  This value gets
212                                  * base160tab[0], we decrement the buffer
213                                  * pointer to get the next higher-order digit,
214                                  * and continue in the loop.
215                                  */
216                                 *pBase160-- = base160tab[0];
217                         }
218                 }
219
220                 sqlite3_result_text(hContext,
221                                     pStart,
222                                     strlen(pStart),
223                                     free);
224         } else {
225                 sqlite3_result_value(hContext, argv[0]);
226                 if (pBase160 != NULL) {
227                         free(pBase160);
228                 }
229         }
230 }
231
232 static char *parsetree_to_sql(struct ldb_module *module,
233                               void *mem_ctx,
234                               const struct ldb_parse_tree *t)
235 {
236         const struct ldb_attrib_handler *h;
237         struct ldb_val value, subval;
238         char *wild_card_string;
239         char *child, *tmp;
240         char *ret = NULL;
241         char *attr;
242         int i;
243
244
245         switch(t->operation) {
246         case LDB_OP_AND:
247
248                 tmp = parsetree_to_sql(module, mem_ctx, t->u.list.elements[0]);
249                 if (tmp == NULL) return NULL;
250
251                 for (i = 1; i < t->u.list.num_elements; i++) {
252
253                         child = parsetree_to_sql(module, mem_ctx, t->u.list.elements[i]);
254                         if (child == NULL) return NULL;
255
256                         tmp = talloc_asprintf_append(tmp, " INTERSECT %s ", child);
257                         if (tmp == NULL) return NULL;
258                 }
259
260                 ret = talloc_asprintf(mem_ctx, "SELECT * FROM ( %s )\n", tmp);
261
262                 return ret;
263                 
264         case LDB_OP_OR:
265
266                 tmp = parsetree_to_sql(module, mem_ctx, t->u.list.elements[0]);
267                 if (tmp == NULL) return NULL;
268
269                 for (i = 1; i < t->u.list.num_elements; i++) {
270
271                         child = parsetree_to_sql(module, mem_ctx, t->u.list.elements[i]);
272                         if (child == NULL) return NULL;
273
274                         tmp = talloc_asprintf_append(tmp, " UNION %s ", child);
275                         if (tmp == NULL) return NULL;
276                 }
277
278                 return talloc_asprintf(mem_ctx, "SELECT * FROM ( %s ) ", tmp);
279
280         case LDB_OP_NOT:
281
282                 child = parsetree_to_sql(module, mem_ctx, t->u.isnot.child);
283                 if (child == NULL) return NULL;
284
285                 return talloc_asprintf(mem_ctx,
286                                         "SELECT eid FROM ldb_entry "
287                                         "WHERE eid NOT IN ( %s ) ", child);
288
289         case LDB_OP_EQUALITY:
290                 /*
291                  * For simple searches, we want to retrieve the list of EIDs that
292                  * match the criteria.
293                 */
294                 attr = ldb_casefold(mem_ctx, t->u.equality.attr);
295                 if (attr == NULL) return NULL;
296                 h = ldb_attrib_handler(module->ldb, attr);
297
298                 /* Get a canonicalised copy of the data */
299                 h->canonicalise_fn(module->ldb, mem_ctx, &(t->u.equality.value), &value);
300                 if (value.data == NULL) {
301                         return NULL;
302                 }
303
304                 if (strcasecmp(t->u.equality.attr, "objectclass") == 0) {
305                 /*
306                  * For object classes, we want to search for all objectclasses
307                  * that are subclasses as well.
308                 */
309                         return lsqlite3_tprintf(mem_ctx,
310                                         "SELECT eid  FROM ldb_attribute_values\n"
311                                         "WHERE norm_attr_name = 'OBJECTCLASS' "
312                                         "AND norm_attr_value IN\n"
313                                         "  (SELECT class_name FROM ldb_object_classes\n"
314                                         "   WHERE tree_key GLOB\n"
315                                         "     (SELECT tree_key FROM ldb_object_classes\n"
316                                         "      WHERE class_name = '%q'\n"
317                                         "     ) || '*'\n"
318                                         "  )\n", value.data);
319
320                 } else if (strcasecmp(t->u.equality.attr, "dn") == 0) {
321                         /* DN query is a special ldb case */
322                         char *cdn = ldb_dn_linearize_casefold(module->ldb,
323                                                               ldb_dn_explode(module->ldb,
324                                                               value.data));
325
326                         return lsqlite3_tprintf(mem_ctx,
327                                                 "SELECT eid FROM ldb_entry "
328                                                 "WHERE norm_dn = '%q'", cdn);
329
330                 } else {
331                         /* A normal query. */
332                         return lsqlite3_tprintf(mem_ctx,
333                                                 "SELECT eid FROM ldb_attribute_values "
334                                                 "WHERE norm_attr_name = '%q' "
335                                                 "AND norm_attr_value = '%q'",
336                                                 attr,
337                                                 value.data);
338
339                 }
340
341         case LDB_OP_SUBSTRING:
342
343                 wild_card_string = talloc_strdup(mem_ctx,
344                                         (t->u.substring.start_with_wildcard)?"*":"");
345                 if (wild_card_string == NULL) return NULL;
346
347                 for (i = 0; t->u.substring.chunks[i]; i++) {
348                         wild_card_string = talloc_asprintf_append(wild_card_string, "%s*",
349                                                         t->u.substring.chunks[i]->data);
350                         if (wild_card_string == NULL) return NULL;
351                 }
352
353                 if ( ! t->u.substring.end_with_wildcard ) {
354                         /* remove last wildcard */
355                         wild_card_string[strlen(wild_card_string) - 1] = '\0';
356                 }
357
358                 attr = ldb_casefold(mem_ctx, t->u.substring.attr);
359                 if (attr == NULL) return NULL;
360                 h = ldb_attrib_handler(module->ldb, attr);
361
362                 subval.data = wild_card_string;
363                 subval.length = strlen(wild_card_string) + 1;
364
365                 /* Get a canonicalised copy of the data */
366                 h->canonicalise_fn(module->ldb, mem_ctx, &(subval), &value);
367                 if (value.data == NULL) {
368                         return NULL;
369                 }
370
371                 return lsqlite3_tprintf(mem_ctx,
372                                         "SELECT eid FROM ldb_attribute_values "
373                                         "WHERE norm_attr_name = '%q' "
374                                         "AND norm_attr_value GLOB '%q'",
375                                         attr,
376                                         value.data);
377
378         case LDB_OP_GREATER:
379                 attr = ldb_casefold(mem_ctx, t->u.equality.attr);
380                 if (attr == NULL) return NULL;
381                 h = ldb_attrib_handler(module->ldb, attr);
382
383                 /* Get a canonicalised copy of the data */
384                 h->canonicalise_fn(module->ldb, mem_ctx, &(t->u.equality.value), &value);
385                 if (value.data == NULL) {
386                         return NULL;
387                 }
388
389                 return lsqlite3_tprintf(mem_ctx,
390                                         "SELECT eid FROM ldb_attribute_values "
391                                         "WHERE norm_attr_name = '%q' "
392                                         "AND ldap_compare(norm_attr_value, '>=', '%q', '%q') ",
393                                         attr,
394                                         value.data,
395                                         attr);
396
397         case LDB_OP_LESS:
398                 attr = ldb_casefold(mem_ctx, t->u.equality.attr);
399                 if (attr == NULL) return NULL;
400                 h = ldb_attrib_handler(module->ldb, attr);
401
402                 /* Get a canonicalised copy of the data */
403                 h->canonicalise_fn(module->ldb, mem_ctx, &(t->u.equality.value), &value);
404                 if (value.data == NULL) {
405                         return NULL;
406                 }
407
408                 return lsqlite3_tprintf(mem_ctx,
409                                         "SELECT eid FROM ldb_attribute_values "
410                                         "WHERE norm_attr_name = '%q' "
411                                         "AND ldap_compare(norm_attr_value, '<=', '%q', '%q') ",
412                                         attr,
413                                         value.data,
414                                         attr);
415
416         case LDB_OP_PRESENT:
417                 if (strcasecmp(t->u.present.attr, "dn") == 0) {
418                         return talloc_strdup(mem_ctx, "SELECT eid FROM ldb_entry");
419                 }
420
421                 attr = ldb_casefold(mem_ctx, t->u.present.attr);
422                 if (attr == NULL) return NULL;
423
424                 return lsqlite3_tprintf(mem_ctx,
425                                         "SELECT eid FROM ldb_attribute_values "
426                                         "WHERE norm_attr_name = '%q' ",
427                                         attr);
428
429         case LDB_OP_APPROX:
430                 attr = ldb_casefold(mem_ctx, t->u.equality.attr);
431                 if (attr == NULL) return NULL;
432                 h = ldb_attrib_handler(module->ldb, attr);
433
434                 /* Get a canonicalised copy of the data */
435                 h->canonicalise_fn(module->ldb, mem_ctx, &(t->u.equality.value), &value);
436                 if (value.data == NULL) {
437                         return NULL;
438                 }
439
440                 return lsqlite3_tprintf(mem_ctx,
441                                         "SELECT eid FROM ldb_attribute_values "
442                                         "WHERE norm_attr_name = '%q' "
443                                         "AND ldap_compare(norm_attr_value, '~%', 'q', '%q') ",
444                                         attr,
445                                         value.data,
446                                         attr);
447                 
448         case LDB_OP_EXTENDED:
449 #warning  "work out how to handle bitops"
450                 return NULL;
451
452         default:
453                 break;
454         };
455
456         /* should never occur */
457         abort();
458         return NULL;
459 }
460
461 /*
462  * query_int()
463  *
464  * This function is used for the common case of queries that return a single
465  * integer value.
466  *
467  * NOTE: If more than one value is returned by the query, all but the first
468  * one will be ignored.
469  */
470 static int
471 query_int(const struct lsqlite3_private * lsqlite3,
472           long long * pRet,
473           const char * pSql,
474           ...)
475 {
476         int             ret;
477         int             bLoop;
478         char *          p;
479         sqlite3_stmt *  pStmt;
480         va_list         args;
481         
482         /* Begin access to variable argument list */
483         va_start(args, pSql);
484         
485         /* Format the query */
486         if ((p = sqlite3_vmprintf(pSql, args)) == NULL) {
487                 return SQLITE_NOMEM;
488         }
489         
490         /*
491          * Prepare and execute the SQL statement.  Loop allows retrying on
492          * certain errors, e.g. SQLITE_SCHEMA occurs if the schema changes,
493          * requiring retrying the operation.
494          */
495         for (bLoop = TRUE; bLoop; ) {
496                 
497                 /* Compile the SQL statement into sqlite virtual machine */
498                 if ((ret = sqlite3_prepare(lsqlite3->sqlite,
499                                            p,
500                                            -1,
501                                            &pStmt,
502                                            NULL)) == SQLITE_SCHEMA) {
503                         if (stmtGetEID != NULL) {
504                                 sqlite3_finalize(stmtGetEID);
505                                 stmtGetEID = NULL;
506                         }
507                         continue;
508                 } else if (ret != SQLITE_OK) {
509                         break;
510                 }
511                 
512                 /* One row expected */
513                 if ((ret = sqlite3_step(pStmt)) == SQLITE_SCHEMA) {
514                         if (stmtGetEID != NULL) {
515                                 sqlite3_finalize(stmtGetEID);
516                                 stmtGetEID = NULL;
517                         }
518                         (void) sqlite3_finalize(pStmt);
519                         continue;
520                 } else if (ret != SQLITE_ROW) {
521                         (void) sqlite3_finalize(pStmt);
522                         break;
523                 }
524                 
525                 /* Get the value to be returned */
526                 *pRet = sqlite3_column_int64(pStmt, 0);
527                 
528                 /* Free the virtual machine */
529                 if ((ret = sqlite3_finalize(pStmt)) == SQLITE_SCHEMA) {
530                         if (stmtGetEID != NULL) {
531                                 sqlite3_finalize(stmtGetEID);
532                                 stmtGetEID = NULL;
533                         }
534                         continue;
535                 } else if (ret != SQLITE_OK) {
536                         (void) sqlite3_finalize(pStmt);
537                         break;
538                 }
539                 
540                 /*
541                  * Normal condition is only one time through loop.  Loop is
542                  * rerun in error conditions, via "continue", above.
543                  */
544                 bLoop = FALSE;
545         }
546         
547         /* All done with variable argument list */
548         va_end(args);
549         
550
551         /* Free the memory we allocated for our query string */
552         sqlite3_free(p);
553         
554         return ret;
555 }
556
557 /*
558  * This is a bad hack to support ldap style comparisons whithin sqlite.
559  * val is the attribute in the row currently under test
560  * func is the desired test "<=" ">=" "~" ":"
561  * cmp is the value to compare against (eg: "test")
562  * attr is the attribute name the value of which we want to test
563  */
564
565 static void lsqlite3_compare(sqlite3_context *ctx, int argc,
566                                         sqlite3_value **argv)
567 {
568         struct ldb_context *ldb = (struct ldb_context *)sqlite3_user_data(ctx);
569         const unsigned char *val = sqlite3_value_text(argv[0]);
570         const unsigned char *func = sqlite3_value_text(argv[1]);
571         const unsigned char *cmp = sqlite3_value_text(argv[2]);
572         const unsigned char *attr = sqlite3_value_text(argv[3]);
573         const struct ldb_attrib_handler *h;
574         struct ldb_val valX;
575         struct ldb_val valY;
576         int ret;
577
578         switch (func[0]) {
579         /* greater */
580         case '>': /* >= */
581                 h = ldb_attrib_handler(ldb, attr);
582                 valX.data = cmp;
583                 valX.length = strlen(cmp);
584                 valY.data = val;
585                 valY.length = strlen(val);
586                 ret = h->comparison_fn(ldb, ldb, &valY, &valX);
587                 if (ret >= 0)
588                         sqlite3_result_int(ctx, 1);
589                 else
590                         sqlite3_result_int(ctx, 0);
591                 return;
592
593         /* lesser */
594         case '<': /* <= */
595                 h = ldb_attrib_handler(ldb, attr);
596                 valX.data = cmp;
597                 valX.length = strlen(cmp);
598                 valY.data = val;
599                 valY.length = strlen(val);
600                 ret = h->comparison_fn(ldb, ldb, &valY, &valX);
601                 if (ret <= 0)
602                         sqlite3_result_int(ctx, 1);
603                 else
604                         sqlite3_result_int(ctx, 0);
605                 return;
606
607         /* approx */
608         case '~':
609                 /* TODO */
610                 sqlite3_result_int(ctx, 0);
611                 return;
612
613         /* bitops */
614         case ':':
615                 /* TODO */
616                 sqlite3_result_int(ctx, 0);
617                 return;
618
619         default:
620                 break;
621         }
622
623         sqlite3_result_error(ctx, "Value must start with a special operation char (<>~:)!", -1);
624         return;
625 }
626
627
628 /* rename a record */
629 static int lsqlite3_safe_rollback(sqlite3 *sqlite)
630 {
631         char *errmsg;
632         int ret;
633
634         /* execute */
635         ret = sqlite3_exec(sqlite, "ROLLBACK;", NULL, NULL, &errmsg);
636         if (ret != SQLITE_OK) {
637                 if (errmsg) {
638                         printf("lsqlite3_safe_rollback: Error: %s\n", errmsg);
639                         free(errmsg);
640                 }
641                 return -1;
642         }
643
644         return 0;
645 }
646
647 /* return an eid as result */
648 static int lsqlite3_eid_callback(void *result, int col_num, char **cols, char **names)
649 {
650         long long *eid = (long long *)result;
651
652         if (col_num != 1) return SQLITE_ABORT;
653         if (strcasecmp(names[0], "eid") != 0) return SQLITE_ABORT;
654
655         *eid = atoll(cols[0]);
656         return SQLITE_OK;
657 }
658
659 struct lsqlite3_msgs {
660         int count;
661         struct ldb_message **msgs;
662         long long current_eid;
663         const char * const * attrs;
664         TALLOC_CTX *mem_ctx;
665 };
666
667 /*
668  * add a single set of ldap message values to a ldb_message
669  */
670
671 static int lsqlite3_search_callback(void *result, int col_num, char **cols, char **names)
672 {
673         struct lsqlite3_msgs *msgs = (struct lsqlite3_msgs *)result;
674         struct ldb_message *msg;
675         long long eid;
676         int i;
677
678         /* eid, dn, attr_name, attr_value */
679         if (col_num != 4) return SQLITE_ABORT;
680
681         eid = atoll(cols[0]);
682
683         if (eid != msgs->current_eid) {
684                 msgs->msgs = talloc_realloc(msgs->mem_ctx,
685                                             msgs->msgs,
686                                             struct ldb_message *,
687                                             msgs->count + 2);
688                 if (msgs->msgs == NULL) return SQLITE_ABORT;
689
690                 msgs->msgs[msgs->count] = talloc(msgs->msgs, struct ldb_message);
691                 if (msgs->msgs[msgs->count] == NULL) return SQLITE_ABORT;
692
693                 msgs->msgs[msgs->count]->dn = NULL;
694                 msgs->msgs[msgs->count]->num_elements = 0;
695                 msgs->msgs[msgs->count]->elements = NULL;
696                 msgs->msgs[msgs->count]->private_data = NULL;
697
698                 msgs->count++;
699                 msgs->current_eid = eid;
700         }
701
702         msg = msgs->msgs[msgs->count -1];
703
704         if (msg->dn == NULL) {
705                 msg->dn = ldb_dn_explode(msg, cols[1]);
706                 if (msg->dn == NULL) return SQLITE_ABORT;
707         }
708
709         if (msgs->attrs) {
710                 int found = 0;
711                 for (i = 0; msgs->attrs[i]; i++) {
712                         if (strcasecmp(cols[2], msgs->attrs[i]) == 0) {
713                                 found = 1;
714                                 break;
715                         }
716                 }
717                 if (!found) return 0;
718         }
719
720         msg->elements = talloc_realloc(msg,
721                                        msg->elements,
722                                        struct ldb_message_element,
723                                        msg->num_elements + 1);
724         if (msg->elements == NULL) return SQLITE_ABORT;
725
726         msg->elements[msg->num_elements].flags = 0;
727         msg->elements[msg->num_elements].name = talloc_strdup(msg->elements, cols[2]);
728         if (msg->elements[msg->num_elements].name == NULL) return SQLITE_ABORT;
729
730         msg->elements[msg->num_elements].num_values = 1;
731         msg->elements[msg->num_elements].values = talloc_array(msg->elements,
732                                                                 struct ldb_val, 1);
733         if (msg->elements[msg->num_elements].values == NULL) return SQLITE_ABORT;
734
735         msg->elements[msg->num_elements].values[0].length = strlen(cols[3]);
736         msg->elements[msg->num_elements].values[0].data = talloc_strdup(msg->elements, cols[3]);
737         if (msg->elements[msg->num_elements].values[0].data == NULL) return SQLITE_ABORT;
738
739         msg->num_elements++;
740
741         return SQLITE_OK;
742 }
743
744
745 /*
746  * lsqlite3_get_eid()
747  * lsqlite3_get_eid_ndn()
748  *
749  * These functions are used for the very common case of retrieving an EID value
750  * given a (normalized) DN.
751  */
752
753 static long long lsqlite3_get_eid_ndn(sqlite3 *sqlite, void *mem_ctx, const char *norm_dn)
754 {
755         char *errmsg;
756         char *query;
757         long long eid = -1;
758         long long ret;
759
760         /* get object eid */
761         query = lsqlite3_tprintf(mem_ctx, "SELECT eid "
762                                           "FROM ldb_entry "
763                                           "WHERE norm_dn = '%q';", norm_dn);
764         if (query == NULL) return -1;
765
766         ret = sqlite3_exec(sqlite, query, lsqlite3_eid_callback, &eid, &errmsg);
767         if (ret != SQLITE_OK) {
768                 if (errmsg) {
769                         printf("lsqlite3_get_eid: Fatal Error: %s\n", errmsg);
770                         free(errmsg);
771                 }
772                 return -1;
773         }
774
775         return eid;
776 }
777
778 static long long lsqlite3_get_eid(struct ldb_module *module, const struct ldb_dn *dn)
779 {
780         TALLOC_CTX *local_ctx;
781         struct lsqlite3_private *lsqlite3 = module->private_data;
782         long long eid = -1;
783         char *cdn;
784
785         /* ignore ltdb specials */
786         if (ldb_dn_is_special(dn)) {
787                 return -1;
788         }
789
790         /* create a local ctx */
791         local_ctx = talloc_named(lsqlite3, 0, "lsqlite3_get_eid local context");
792         if (local_ctx == NULL) {
793                 return -1;
794         }
795
796         cdn = ldb_dn_linearize(local_ctx, ldb_dn_casefold(module->ldb, dn));
797         if (!cdn) goto done;
798
799         eid = lsqlite3_get_eid_ndn(lsqlite3->sqlite, local_ctx, cdn);
800
801 done:
802         talloc_free(local_ctx);
803         return eid;
804 }
805
806 /*
807  * Interface functions referenced by lsqlite3_ops
808  */
809
810 /* search for matching records, by tree */
811 static int lsqlite3_search_bytree(struct ldb_module * module, const struct ldb_dn* basedn,
812                                   enum ldb_scope scope, struct ldb_parse_tree * tree,
813                                   const char * const * attrs, struct ldb_message *** res)
814 {
815         TALLOC_CTX *local_ctx;
816         struct lsqlite3_private *lsqlite3 = module->private_data;
817         struct lsqlite3_msgs msgs;
818         char *norm_basedn;
819         char *sqlfilter;
820         char *errmsg;
821         char *query;
822         int ret, i;
823
824         /* create a local ctx */
825         local_ctx = talloc_named(lsqlite3, 0, "lsqlite3_search_by_tree local context");
826         if (local_ctx == NULL) {
827                 return -1;
828         }
829
830         if (basedn) {
831                 norm_basedn = ldb_dn_linearize(local_ctx, ldb_dn_casefold(module->ldb, basedn));
832                 if (norm_basedn == NULL) {
833                         ret = LDB_ERR_INVALID_DN_SYNTAX;
834                         goto failed;
835                 }
836         } else norm_basedn = talloc_strdup(local_ctx, "");
837
838         if (*norm_basedn == '\0' &&
839                 (scope == LDB_SCOPE_BASE || scope == LDB_SCOPE_ONELEVEL)) {
840                         ret = LDB_ERR_UNWILLING_TO_PERFORM;
841                         goto failed;
842                 }
843
844         /* Convert filter into a series of SQL conditions (constraints) */
845         sqlfilter = parsetree_to_sql(module, local_ctx, tree);
846         
847         switch(scope) {
848         case LDB_SCOPE_DEFAULT:
849         case LDB_SCOPE_SUBTREE:
850                 if (*norm_basedn != '\0') {
851                         query = lsqlite3_tprintf(local_ctx,
852                                 "SELECT entry.eid,\n"
853                                 "       entry.dn,\n"
854                                 "       av.attr_name,\n"
855                                 "       av.attr_value\n"
856                                 "  FROM ldb_entry AS entry\n"
857
858                                 "  LEFT OUTER JOIN ldb_attribute_values AS av\n"
859                                 "    ON av.eid = entry.eid\n"
860
861                                 "  WHERE entry.eid IN\n"
862                                 "    (SELECT DISTINCT ldb_entry.eid\n"
863                                 "       FROM ldb_entry\n"
864                                 "       WHERE (ldb_entry.norm_dn GLOB('*,%q')\n"
865                                 "       OR ldb_entry.norm_dn = '%q')\n"
866                                 "       AND ldb_entry.eid IN\n"
867                                 "         (%s)\n"
868                                 "    )\n"
869
870                                 "  ORDER BY entry.eid ASC;",
871                                 norm_basedn,
872                                 norm_basedn,
873                                 sqlfilter);
874                 } else {
875                         query = lsqlite3_tprintf(local_ctx,
876                                 "SELECT entry.eid,\n"
877                                 "       entry.dn,\n"
878                                 "       av.attr_name,\n"
879                                 "       av.attr_value\n"
880                                 "  FROM ldb_entry AS entry\n"
881
882                                 "  LEFT OUTER JOIN ldb_attribute_values AS av\n"
883                                 "    ON av.eid = entry.eid\n"
884
885                                 "  WHERE entry.eid IN\n"
886                                 "    (SELECT DISTINCT ldb_entry.eid\n"
887                                 "       FROM ldb_entry\n"
888                                 "       WHERE ldb_entry.eid IN\n"
889                                 "         (%s)\n"
890                                 "    )\n"
891
892                                 "  ORDER BY entry.eid ASC;",
893                                 sqlfilter);
894                 }
895
896                 break;
897                 
898         case LDB_SCOPE_BASE:
899                 query = lsqlite3_tprintf(local_ctx,
900                         "SELECT entry.eid,\n"
901                         "       entry.dn,\n"
902                         "       av.attr_name,\n"
903                         "       av.attr_value\n"
904                         "  FROM ldb_entry AS entry\n"
905
906                         "  LEFT OUTER JOIN ldb_attribute_values AS av\n"
907                         "    ON av.eid = entry.eid\n"
908
909                         "  WHERE entry.eid IN\n"
910                         "    (SELECT DISTINCT ldb_entry.eid\n"
911                         "       FROM ldb_entry\n"
912                         "       WHERE ldb_entry.norm_dn = '%q'\n"
913                         "         AND ldb_entry.eid IN\n"
914                         "           (%s)\n"
915                         "    )\n"
916
917                         "  ORDER BY entry.eid ASC;",
918                         norm_basedn,
919                         sqlfilter);
920                 break;
921                 
922         case LDB_SCOPE_ONELEVEL:
923                 query = lsqlite3_tprintf(local_ctx,
924                         "SELECT entry.eid,\n"
925                         "       entry.dn,\n"
926                         "       av.attr_name,\n"
927                         "       av.attr_value\n"
928                         "  FROM ldb_entry AS entry\n"
929
930                         "  LEFT OUTER JOIN ldb_attribute_values AS av\n"
931                         "    ON av.eid = entry.eid\n"
932
933                         "  WHERE entry.eid IN\n"
934                         "    (SELECT DISTINCT ldb_entry.eid\n"
935                         "       FROM ldb_entry\n"
936                         "       WHERE norm_dn GLOB('*,%q')\n"
937                         "         AND NOT norm_dn GLOB('*,*,%q')\n"
938                         "         AND ldb_entry.eid IN\n(%s)\n"
939                         "    )\n"
940
941                         "  ORDER BY entry.eid ASC;",
942                         norm_basedn,
943                         norm_basedn,
944                         sqlfilter);
945                 break;
946         }
947
948         if (query == NULL) {
949                 ret = LDB_ERR_OTHER;
950                 goto failed;
951         }
952
953         /* * /
954         printf ("%s\n", query);
955         / * */
956
957         msgs.msgs = NULL;
958         msgs.count = 0;
959         msgs.current_eid = 0;
960         msgs.mem_ctx = local_ctx;
961         msgs.attrs = attrs;
962
963         ret = sqlite3_exec(lsqlite3->sqlite, query, lsqlite3_search_callback, &msgs, &errmsg);
964         if (ret != SQLITE_OK) {
965                 if (errmsg) {
966                         ldb_set_errstring(module, talloc_strdup(module, errmsg));
967                         free(errmsg);
968                 }
969                 ret = LDB_ERR_OTHER;
970                 goto failed;
971         }
972
973         for (i = 0; i < msgs.count; i++) {
974                 msgs.msgs[i] = ldb_msg_canonicalize(module->ldb, msgs.msgs[i]);
975                 if (msgs.msgs[i] ==  NULL) {
976                         ret = LDB_ERR_OTHER;
977                         goto failed;
978                 }
979         }
980
981         *res = talloc_steal(module, msgs.msgs);
982         ret = msgs.count;
983
984         talloc_free(local_ctx);
985         return ret;
986
987 /* If error, return error code; otherwise return number of results */
988 failed:
989         talloc_free(local_ctx);
990         return -1;
991 }
992
993 /* search for matching records, by expression */
994 static int lsqlite3_search(struct ldb_module * module, const struct ldb_dn *basedn,
995                            enum ldb_scope scope, const char * expression,
996                            const char * const *attrs, struct ldb_message *** res)
997 {
998         struct ldb_parse_tree * tree;
999         int ret;
1000         
1001         /* Handle tdb specials */
1002         if (ldb_dn_is_special(basedn)) {
1003 #warning "handle tdb specials"
1004                 return 0;
1005         }
1006
1007 #if 0 
1008 /* (|(objectclass=*)(dn=*)) is  passed by the command line tool now instead */
1009         /* Handle the special case of requesting all */
1010         if (pExpression != NULL && *pExpression == '\0') {
1011                 pExpression = "dn=*";
1012         }
1013 #endif
1014
1015         /* Parse the filter expression into a tree we can work with */
1016         if ((tree = ldb_parse_tree(module->ldb, expression)) == NULL) {
1017                 return -1;
1018         }
1019         
1020         /* Now use the bytree function for the remainder of processing */
1021         ret = lsqlite3_search_bytree(module, basedn, scope, tree, attrs, res);
1022         
1023         /* Free the parse tree */
1024         talloc_free(tree);
1025         
1026         /* All done. */
1027         return ret;
1028 }
1029
1030
1031 /* add a record */
1032 static int lsqlite3_add(struct ldb_module *module, const struct ldb_message *msg)
1033 {
1034         TALLOC_CTX *local_ctx;
1035         struct lsqlite3_private *lsqlite3 = module->private_data;
1036         long long eid;
1037         char *dn, *ndn;
1038         char *errmsg;
1039         char *query;
1040         int ret;
1041         int i;
1042         
1043         /* create a local ctx */
1044         local_ctx = talloc_named(lsqlite3, 0, "lsqlite3_add local context");
1045         if (local_ctx == NULL) {
1046                 return LDB_ERR_OTHER;
1047         }
1048
1049         /* See if this is an ltdb special */
1050         if (ldb_dn_is_special(msg->dn)) {
1051                 struct ldb_dn *c;
1052
1053                 c = ldb_dn_explode(local_ctx, "@SUBCLASSES");
1054                 if (ldb_dn_compare(module->ldb, msg->dn, c) == 0) {
1055 #warning "insert subclasses into object class tree"
1056                         ret = LDB_ERR_UNWILLING_TO_PERFORM;
1057                         goto failed;
1058                 }
1059
1060 /*
1061                 c = ldb_dn_explode(local_ctx, "@INDEXLIST");
1062                 if (ldb_dn_compare(module->ldb, msg->dn, c) == 0) {
1063 #warning "should we handle indexes somehow ?"
1064                         goto failed;
1065                 }
1066 */
1067                 /* Others are implicitly ignored */
1068                 return LDB_SUCCESS;
1069         }
1070
1071         /* create linearized and normalized dns */
1072         dn = ldb_dn_linearize(local_ctx, msg->dn);
1073         ndn = ldb_dn_linearize(local_ctx, ldb_dn_casefold(module->ldb, msg->dn));
1074         if (dn == NULL || ndn == NULL) {
1075                 ret = LDB_ERR_OTHER;
1076                 goto failed;
1077         }
1078
1079         query = lsqlite3_tprintf(local_ctx,
1080                                    /* Add new entry */
1081                                    "INSERT OR ABORT INTO ldb_entry "
1082                                    "('dn', 'norm_dn') "
1083                                    "VALUES ('%q', '%q');",
1084                                 dn, ndn);
1085         if (query == NULL) {
1086                 ret = LDB_ERR_OTHER;
1087                 goto failed;
1088         }
1089
1090         ret = sqlite3_exec(lsqlite3->sqlite, query, NULL, NULL, &errmsg);
1091         if (ret != SQLITE_OK) {
1092                 if (errmsg) {
1093                         ldb_set_errstring(module, talloc_strdup(module, errmsg));
1094                         free(errmsg);
1095                 }
1096                 ret = LDB_ERR_OTHER;
1097                 goto failed;
1098         }
1099
1100         eid = lsqlite3_get_eid_ndn(lsqlite3->sqlite, local_ctx, ndn);
1101         if (eid == -1) {
1102                 ret = LDB_ERR_OTHER;
1103                 goto failed;
1104         }
1105
1106         for (i = 0; i < msg->num_elements; i++) {
1107                 const struct ldb_message_element *el = &msg->elements[i];
1108                 const struct ldb_attrib_handler *h;
1109                 char *attr;
1110                 int j;
1111
1112                 /* Get a case-folded copy of the attribute name */
1113                 attr = ldb_casefold(local_ctx, el->name);
1114                 if (attr == NULL) {
1115                         ret = LDB_ERR_OTHER;
1116                         goto failed;
1117                 }
1118
1119                 h = ldb_attrib_handler(module->ldb, el->name);
1120
1121                 /* For each value of the specified attribute name... */
1122                 for (j = 0; j < el->num_values; j++) {
1123                         struct ldb_val value;
1124                         char *insert;
1125
1126                         /* Get a canonicalised copy of the data */
1127                         h->canonicalise_fn(module->ldb, local_ctx, &(el->values[j]), &value);
1128                         if (value.data == NULL) {
1129                                 ret = LDB_ERR_OTHER;
1130                                 goto failed;
1131                         }
1132
1133                         insert = lsqlite3_tprintf(local_ctx,
1134                                         "INSERT OR ROLLBACK INTO ldb_attribute_values "
1135                                         "('eid', 'attr_name', 'norm_attr_name',"
1136                                         " 'attr_value', 'norm_attr_value') "
1137                                         "VALUES ('%lld', '%q', '%q', '%q', '%q');",
1138                                         eid, el->name, attr,
1139                                         el->values[j].data, value.data);
1140                         if (insert == NULL) {
1141                                 ret = LDB_ERR_OTHER;
1142                                 goto failed;
1143                         }
1144
1145                         ret = sqlite3_exec(lsqlite3->sqlite, insert, NULL, NULL, &errmsg);
1146                         if (ret != SQLITE_OK) {
1147                                 if (errmsg) {
1148                                         ldb_set_errstring(module, talloc_strdup(module, errmsg));
1149                                         free(errmsg);
1150                                 }
1151                                 ret = LDB_ERR_OTHER;
1152                                 goto failed;
1153                         }
1154                 }
1155         }
1156
1157         talloc_free(local_ctx);
1158         return LDB_SUCCESS;
1159
1160 failed:
1161         talloc_free(local_ctx);
1162         return ret;
1163 }
1164
1165
1166 /* modify a record */
1167 static int lsqlite3_modify(struct ldb_module *module, const struct ldb_message *msg)
1168 {
1169         TALLOC_CTX *local_ctx;
1170         struct lsqlite3_private *lsqlite3 = module->private_data;
1171         long long eid;
1172         char *errmsg;
1173         int ret;
1174         int i;
1175         
1176         /* create a local ctx */
1177         local_ctx = talloc_named(lsqlite3, 0, "lsqlite3_modify local context");
1178         if (local_ctx == NULL) {
1179                 return LDB_ERR_OTHER;
1180         }
1181
1182         /* See if this is an ltdb special */
1183         if (ldb_dn_is_special(msg->dn)) {
1184                 struct ldb_dn *c;
1185
1186                 c = ldb_dn_explode(local_ctx, "@SUBCLASSES");
1187                 if (ldb_dn_compare(module->ldb, msg->dn, c) == 0) {
1188 #warning "modify subclasses into object class tree"
1189                         ret = LDB_ERR_UNWILLING_TO_PERFORM;
1190                         goto failed;
1191                 }
1192
1193                 /* Others are implicitly ignored */
1194                 return LDB_SUCCESS;
1195         }
1196
1197         eid = lsqlite3_get_eid(module, msg->dn);
1198         if (eid == -1) {
1199                 ret = LDB_ERR_OTHER;
1200                 goto failed;
1201         }
1202
1203         for (i = 0; i < msg->num_elements; i++) {
1204                 const struct ldb_message_element *el = &msg->elements[i];
1205                 const struct ldb_attrib_handler *h;
1206                 int flags = el->flags & LDB_FLAG_MOD_MASK;
1207                 char *attr;
1208                 char *mod;
1209                 int j;
1210
1211                 /* Get a case-folded copy of the attribute name */
1212                 attr = ldb_casefold(local_ctx, el->name);
1213                 if (attr == NULL) {
1214                         ret = LDB_ERR_OTHER;
1215                         goto failed;
1216                 }
1217
1218                 h = ldb_attrib_handler(module->ldb, el->name);
1219
1220                 switch (flags) {
1221
1222                 case LDB_FLAG_MOD_REPLACE:
1223                         
1224                         /* remove all attributes before adding the replacements */
1225                         mod = lsqlite3_tprintf(local_ctx,
1226                                                 "DELETE FROM ldb_attribute_values "
1227                                                 "WHERE eid = '%lld' "
1228                                                 "AND norm_attr_name = '%q';",
1229                                                 eid, attr);
1230                         if (mod == NULL) {
1231                                 ret = LDB_ERR_OTHER;
1232                                 goto failed;
1233                         }
1234
1235                         ret = sqlite3_exec(lsqlite3->sqlite, mod, NULL, NULL, &errmsg);
1236                         if (ret != SQLITE_OK) {
1237                                 if (errmsg) {
1238                                         ldb_set_errstring(module, talloc_strdup(module, errmsg));
1239                                         free(errmsg);
1240                                 }
1241                                 ret = LDB_ERR_OTHER;
1242                                 goto failed;
1243                         }
1244
1245                         /* MISSING break is INTENTIONAL */
1246
1247                 case LDB_FLAG_MOD_ADD:
1248 #warning "We should throw an error if no value is provided!"
1249                         /* For each value of the specified attribute name... */
1250                         for (j = 0; j < el->num_values; j++) {
1251                                 struct ldb_val value;
1252
1253                                 /* Get a canonicalised copy of the data */
1254                                 h->canonicalise_fn(module->ldb, local_ctx, &(el->values[j]), &value);
1255                                 if (value.data == NULL) {
1256                                         ret = LDB_ERR_OTHER;
1257                                         goto failed;
1258                                 }
1259
1260                                 mod = lsqlite3_tprintf(local_ctx,
1261                                         "INSERT OR ROLLBACK INTO ldb_attribute_values "
1262                                         "('eid', 'attr_name', 'norm_attr_name',"
1263                                         " 'attr_value', 'norm_attr_value') "
1264                                         "VALUES ('%lld', '%q', '%q', '%q', '%q');",
1265                                         eid, el->name, attr,
1266                                         el->values[j].data, value.data);
1267
1268                                 if (mod == NULL) {
1269                                         ret = LDB_ERR_OTHER;
1270                                         goto failed;
1271                                 }
1272
1273                                 ret = sqlite3_exec(lsqlite3->sqlite, mod, NULL, NULL, &errmsg);
1274                                 if (ret != SQLITE_OK) {
1275                                         if (errmsg) {
1276                                                 ldb_set_errstring(module, talloc_strdup(module, errmsg));
1277                                                 free(errmsg);
1278                                         }
1279                                         ret = LDB_ERR_OTHER;
1280                                         goto failed;
1281                                 }
1282                         }
1283
1284                         break;
1285
1286                 case LDB_FLAG_MOD_DELETE:
1287 #warning "We should throw an error if the attribute we are trying to delete does not exist!"
1288                         if (el->num_values == 0) {
1289                                 mod = lsqlite3_tprintf(local_ctx,
1290                                                         "DELETE FROM ldb_attribute_values "
1291                                                         "WHERE eid = '%lld' "
1292                                                         "AND norm_attr_name = '%q';",
1293                                                         eid, attr);
1294                                 if (mod == NULL) {
1295                                         ret = LDB_ERR_OTHER;
1296                                         goto failed;
1297                                 }
1298
1299                                 ret = sqlite3_exec(lsqlite3->sqlite, mod, NULL, NULL, &errmsg);
1300                                 if (ret != SQLITE_OK) {
1301                                         if (errmsg) {
1302                                                 ldb_set_errstring(module, talloc_strdup(module, errmsg));
1303                                                 free(errmsg);
1304                                         }
1305                                         ret = LDB_ERR_OTHER;
1306                                         goto failed;
1307                                 }
1308                         }
1309
1310                         /* For each value of the specified attribute name... */
1311                         for (j = 0; j < el->num_values; j++) {
1312                                 struct ldb_val value;
1313
1314                                 /* Get a canonicalised copy of the data */
1315                                 h->canonicalise_fn(module->ldb, local_ctx, &(el->values[j]), &value);
1316                                 if (value.data == NULL) {
1317                                         ret = LDB_ERR_OTHER;
1318                                         goto failed;
1319                                 }
1320
1321                                 mod = lsqlite3_tprintf(local_ctx,
1322                                         "DELETE FROM ldb_attribute_values "
1323                                         "WHERE eid = '%lld' "
1324                                         "AND norm_attr_name = '%q' "
1325                                         "AND norm_attr_value = '%q';",
1326                                         eid, attr, value.data);
1327
1328                                 if (mod == NULL) {
1329                                         ret = LDB_ERR_OTHER;
1330                                         goto failed;
1331                                 }
1332
1333                                 ret = sqlite3_exec(lsqlite3->sqlite, mod, NULL, NULL, &errmsg);
1334                                 if (ret != SQLITE_OK) {
1335                                         if (errmsg) {
1336                                                 ldb_set_errstring(module, talloc_strdup(module, errmsg));
1337                                                 free(errmsg);
1338                                         }
1339                                         ret = LDB_ERR_OTHER;
1340                                         goto failed;
1341                                 }
1342                         }
1343
1344                         break;
1345                 }
1346         }
1347
1348         talloc_free(local_ctx);
1349         return LDB_SUCCESS;
1350
1351 failed:
1352         talloc_free(local_ctx);
1353         return ret;
1354 }
1355
1356 /* delete a record */
1357 static int lsqlite3_delete(struct ldb_module *module, const struct ldb_dn *dn)
1358 {
1359         TALLOC_CTX *local_ctx;
1360         struct lsqlite3_private *lsqlite3 = module->private_data;
1361         long long eid;
1362         char *errmsg;
1363         char *query;
1364         int ret;
1365
1366         /* ignore ltdb specials */
1367         if (ldb_dn_is_special(dn)) {
1368                 return LDB_SUCCESS;
1369         }
1370
1371         /* create a local ctx */
1372         local_ctx = talloc_named(lsqlite3, 0, "lsqlite3_delete local context");
1373         if (local_ctx == NULL) {
1374                 return LDB_ERR_OTHER;
1375         }
1376
1377         eid = lsqlite3_get_eid(module, dn);
1378         if (eid == -1) {
1379                 ret = LDB_ERR_OTHER;
1380                 goto failed;
1381         }
1382
1383         query = lsqlite3_tprintf(local_ctx,
1384                                    /* Delete entry */
1385                                    "DELETE FROM ldb_entry WHERE eid = %lld; "
1386                                    /* Delete attributes */
1387                                    "DELETE FROM ldb_attribute_values WHERE eid = %lld; ",
1388                                 eid, eid);
1389         if (query == NULL) {
1390                 ret = LDB_ERR_OTHER;
1391                 goto failed;
1392         }
1393
1394         ret = sqlite3_exec(lsqlite3->sqlite, query, NULL, NULL, &errmsg);
1395         if (ret != SQLITE_OK) {
1396                 if (errmsg) {
1397                         ldb_set_errstring(module, talloc_strdup(module, errmsg));
1398                         free(errmsg);
1399                 }
1400                 ret = LDB_ERR_OTHER;
1401                 goto failed;
1402         }
1403
1404         talloc_free(local_ctx);
1405         return LDB_SUCCESS;
1406
1407 failed:
1408         talloc_free(local_ctx);
1409         return ret;
1410 }
1411
1412 /* rename a record */
1413 static int lsqlite3_rename(struct ldb_module *module, const struct ldb_dn *olddn, const struct ldb_dn *newdn)
1414 {
1415         TALLOC_CTX *local_ctx;
1416         struct lsqlite3_private *lsqlite3 = module->private_data;
1417         char *new_dn, *new_cdn, *old_cdn;
1418         char *errmsg;
1419         char *query;
1420         int ret;
1421
1422         /* ignore ltdb specials */
1423         if (ldb_dn_is_special(olddn) || ldb_dn_is_special(newdn)) {
1424                 return LDB_SUCCESS;
1425         }
1426
1427         /* create a local ctx */
1428         local_ctx = talloc_named(lsqlite3, 0, "lsqlite3_rename local context");
1429         if (local_ctx == NULL) {
1430                 return LDB_ERR_OTHER;
1431         }
1432
1433         /* create linearized and normalized dns */
1434         old_cdn = ldb_dn_linearize(local_ctx, ldb_dn_casefold(module->ldb, olddn));
1435         new_cdn = ldb_dn_linearize(local_ctx, ldb_dn_casefold(module->ldb, newdn));
1436         new_dn = ldb_dn_linearize(local_ctx, newdn);
1437         if (old_cdn == NULL || new_cdn == NULL || new_dn == NULL) {
1438                 ret = LDB_ERR_OTHER;
1439                 goto failed;
1440         }
1441
1442         /* build the SQL query */
1443         query = lsqlite3_tprintf(local_ctx,
1444                                  "UPDATE ldb_entry SET dn = '%q', norm_dn = '%q' "
1445                                  "WHERE norm_dn = '%q';",
1446                                  new_dn, new_cdn, old_cdn);
1447         if (query == NULL) {
1448                 ret = LDB_ERR_OTHER;
1449                 goto failed;
1450         }
1451
1452         /* execute */
1453         ret = sqlite3_exec(lsqlite3->sqlite, query, NULL, NULL, &errmsg);
1454         if (ret != SQLITE_OK) {
1455                 if (errmsg) {
1456                         ldb_set_errstring(module, talloc_strdup(module, errmsg));
1457                         free(errmsg);
1458                 }
1459                 ret = LDB_ERR_OTHER;
1460                 goto failed;
1461         }
1462
1463         /* clean up and exit */
1464         talloc_free(local_ctx);
1465         return LDB_SUCCESS;
1466
1467 failed:
1468         talloc_free(local_ctx);
1469         return ret;
1470 }
1471
1472 static int lsqlite3_start_trans(struct ldb_module * module)
1473 {
1474         int ret;
1475         char *errmsg;
1476         struct lsqlite3_private *   lsqlite3 = module->private_data;
1477
1478         if (lsqlite3->trans_count == 0) {
1479                 ret = sqlite3_exec(lsqlite3->sqlite, "BEGIN IMMEDIATE;", NULL, NULL, &errmsg);
1480                 if (ret != SQLITE_OK) {
1481                         if (errmsg) {
1482                                 printf("lsqlite3_start_trans: error: %s\n", errmsg);
1483                                 free(errmsg);
1484                         }
1485                         return -1;
1486                 }
1487         };
1488
1489         lsqlite3->trans_count++;
1490
1491         return 0;
1492 }
1493
1494 static int lsqlite3_end_trans(struct ldb_module *module)
1495 {
1496         int ret;
1497         char *errmsg;
1498         struct lsqlite3_private *lsqlite3 = module->private_data;
1499
1500         if (lsqlite3->trans_count > 0) {
1501                 lsqlite3->trans_count--;
1502         } else return -1;
1503
1504         if (lsqlite3->trans_count == 0) {
1505                 ret = sqlite3_exec(lsqlite3->sqlite, "COMMIT;", NULL, NULL, &errmsg);
1506                 if (ret != SQLITE_OK) {
1507                         if (errmsg) {
1508                                 printf("lsqlite3_end_trans: error: %s\n", errmsg);
1509                                 free(errmsg);
1510                         }
1511                         return -1;
1512                 }
1513         }
1514
1515         return 0;
1516 }
1517
1518 static int lsqlite3_del_trans(struct ldb_module *module)
1519 {
1520         struct lsqlite3_private *lsqlite3 = module->private_data;
1521
1522         if (lsqlite3->trans_count > 0) {
1523                 lsqlite3->trans_count--;
1524         } else return -1;
1525
1526         if (lsqlite3->trans_count == 0) {
1527                 return lsqlite3_safe_rollback(lsqlite3->sqlite);
1528         }
1529
1530         return -1;
1531 }
1532
1533 /*
1534  * Static functions
1535  */
1536
1537 static int initialize(struct lsqlite3_private *lsqlite3,
1538                       struct ldb_context *ldb, const char *url, int flags)
1539 {
1540         TALLOC_CTX *local_ctx;
1541         long long queryInt;
1542         int rollback = 0;
1543         char *errmsg;
1544         char *schema;
1545         int ret;
1546
1547         /* create a local ctx */
1548         local_ctx = talloc_named(lsqlite3, 0, "lsqlite3_rename local context");
1549         if (local_ctx == NULL) {
1550                 return -1;
1551         }
1552
1553         schema = lsqlite3_tprintf(local_ctx,
1554                 
1555                 
1556                 "CREATE TABLE ldb_info AS "
1557                 "  SELECT 'LDB' AS database_type,"
1558                 "         '1.0' AS version;"
1559                 
1560                 /*
1561                  * The entry table holds the information about an entry. 
1562                  * This table is used to obtain the EID of the entry and to 
1563                  * support scope=one and scope=base.  The parent and child
1564                  * table is included in the entry table since all the other
1565                  * attributes are dependent on EID.
1566                  */
1567                 "CREATE TABLE ldb_entry "
1568                 "("
1569                 "  eid     INTEGER PRIMARY KEY AUTOINCREMENT,"
1570                 "  dn      TEXT UNIQUE NOT NULL,"
1571                 "  norm_dn TEXT UNIQUE NOT NULL"
1572                 ");"
1573                 
1574
1575                 "CREATE TABLE ldb_object_classes"
1576                 "("
1577                 "  class_name            TEXT PRIMARY KEY,"
1578                 "  parent_class_name     TEXT,"
1579                 "  tree_key              TEXT UNIQUE,"
1580                 "  max_child_num         INTEGER DEFAULT 0"
1581                 ");"
1582                 
1583                 /*
1584                  * We keep a full listing of attribute/value pairs here
1585                  */
1586                 "CREATE TABLE ldb_attribute_values"
1587                 "("
1588                 "  eid             INTEGER REFERENCES ldb_entry,"
1589                 "  attr_name       TEXT,"
1590                 "  norm_attr_name  TEXT,"
1591                 "  attr_value      TEXT,"
1592                 "  norm_attr_value TEXT "
1593                 ");"
1594                 
1595                
1596                 /*
1597                  * Indexes
1598                  */
1599                 "CREATE INDEX ldb_attribute_values_eid_idx "
1600                 "  ON ldb_attribute_values (eid);"
1601                 
1602                 "CREATE INDEX ldb_attribute_values_name_value_idx "
1603                 "  ON ldb_attribute_values (attr_name, norm_attr_value);"
1604                 
1605                 
1606
1607                 /*
1608                  * Triggers
1609                  */
1610  
1611                 "CREATE TRIGGER ldb_object_classes_insert_tr"
1612                 "  AFTER INSERT"
1613                 "  ON ldb_object_classes"
1614                 "  FOR EACH ROW"
1615                 "    BEGIN"
1616                 "      UPDATE ldb_object_classes"
1617                 "        SET tree_key = COALESCE(tree_key, "
1618                 "              ("
1619                 "                SELECT tree_key || "
1620                 "                       (SELECT base160(max_child_num + 1)"
1621                 "                                FROM ldb_object_classes"
1622                 "                                WHERE class_name = "
1623                 "                                      new.parent_class_name)"
1624                 "                  FROM ldb_object_classes "
1625                 "                  WHERE class_name = new.parent_class_name "
1626                 "              ));"
1627                 "      UPDATE ldb_object_classes "
1628                 "        SET max_child_num = max_child_num + 1"
1629                 "        WHERE class_name = new.parent_class_name;"
1630                 "    END;"
1631
1632                 /*
1633                  * Table initialization
1634                  */
1635
1636                 "INSERT INTO ldb_object_classes "
1637                 "    (class_name, tree_key) "
1638                 "  VALUES "
1639                 "    ('TOP', '0001');");
1640         
1641         /* Skip protocol indicator of url  */
1642         if (strncmp(url, "sqlite://", 9) != 0) {
1643                 return SQLITE_MISUSE;
1644         }
1645         
1646         /* Update pointer to just after the protocol indicator */
1647         url += 9;
1648         
1649         /* Try to open the (possibly empty/non-existent) database */
1650         if ((ret = sqlite3_open(url, &lsqlite3->sqlite)) != SQLITE_OK) {
1651                 return ret;
1652         }
1653         
1654         /* In case this is a new database, enable auto_vacuum */
1655         ret = sqlite3_exec(lsqlite3->sqlite, "PRAGMA auto_vacuum = 1;", NULL, NULL, &errmsg);
1656         if (ret != SQLITE_OK) {
1657                 if (errmsg) {
1658                         printf("lsqlite3 initializaion error: %s\n", errmsg);
1659                         free(errmsg);
1660                 }
1661                 goto failed;
1662         }
1663         
1664         if (flags & LDB_FLG_NOSYNC) {
1665                 /* DANGEROUS */
1666                 ret = sqlite3_exec(lsqlite3->sqlite, "PRAGMA synchronous = OFF;", NULL, NULL, &errmsg);
1667                 if (ret != SQLITE_OK) {
1668                         if (errmsg) {
1669                                 printf("lsqlite3 initializaion error: %s\n", errmsg);
1670                                 free(errmsg);
1671                         }
1672                         goto failed;
1673                 }
1674         }
1675         
1676         /* */
1677         
1678         /* Establish a busy timeout of 30 seconds */
1679         if ((ret = sqlite3_busy_timeout(lsqlite3->sqlite,
1680                                         30000)) != SQLITE_OK) {
1681                 return ret;
1682         }
1683
1684         /* Create a function, callable from sql, to increment a tree_key */
1685         if ((ret =
1686              sqlite3_create_function(lsqlite3->sqlite,/* handle */
1687                                      "base160_next",  /* function name */
1688                                      1,               /* number of args */
1689                                      SQLITE_ANY,      /* preferred text type */
1690                                      NULL,            /* user data */
1691                                      base160next_sql, /* called func */
1692                                      NULL,            /* step func */
1693                                      NULL             /* final func */
1694                      )) != SQLITE_OK) {
1695                 return ret;
1696         }
1697
1698         /* Create a function, callable from sql, to convert int to base160 */
1699         if ((ret =
1700              sqlite3_create_function(lsqlite3->sqlite,/* handle */
1701                                      "base160",       /* function name */
1702                                      1,               /* number of args */
1703                                      SQLITE_ANY,      /* preferred text type */
1704                                      NULL,            /* user data */
1705                                      base160_sql,     /* called func */
1706                                      NULL,            /* step func */
1707                                      NULL             /* final func */
1708                      )) != SQLITE_OK) {
1709                 return ret;
1710         }
1711
1712         /* Create a function, callable from sql, to perform various comparisons */
1713         if ((ret =
1714              sqlite3_create_function(lsqlite3->sqlite, /* handle */
1715                                      "ldap_compare",   /* function name */
1716                                      4,                /* number of args */
1717                                      SQLITE_ANY,       /* preferred text type */
1718                                      ldb  ,            /* user data */
1719                                      lsqlite3_compare, /* called func */
1720                                      NULL,             /* step func */
1721                                      NULL              /* final func */
1722                      )) != SQLITE_OK) {
1723                 return ret;
1724         }
1725
1726         /* Begin a transaction */
1727         ret = sqlite3_exec(lsqlite3->sqlite, "BEGIN EXCLUSIVE;", NULL, NULL, &errmsg);
1728         if (ret != SQLITE_OK) {
1729                 if (errmsg) {
1730                         printf("lsqlite3: initialization error: %s\n", errmsg);
1731                         free(errmsg);
1732                 }
1733                 goto failed;
1734         }
1735         rollback = 1;
1736  
1737         /* Determine if this is a new database.  No tables means it is. */
1738         if (query_int(lsqlite3,
1739                       &queryInt,
1740                       "SELECT COUNT(*)\n"
1741                       "  FROM sqlite_master\n"
1742                       "  WHERE type = 'table';") != 0) {
1743                 goto failed;
1744         }
1745         
1746         if (queryInt == 0) {
1747                 /*
1748                  * Create the database schema
1749                  */
1750                 ret = sqlite3_exec(lsqlite3->sqlite, schema, NULL, NULL, &errmsg);
1751                 if (ret != SQLITE_OK) {
1752                         if (errmsg) {
1753                                 printf("lsqlite3 initializaion error: %s\n", errmsg);
1754                                 free(errmsg);
1755                         }
1756                         goto failed;
1757                 }
1758         } else {
1759                 /*
1760                  * Ensure that the database we opened is one of ours
1761                  */
1762                 if (query_int(lsqlite3,
1763                               &queryInt,
1764                               "SELECT "
1765                               "  (SELECT COUNT(*) = 2"
1766                               "     FROM sqlite_master "
1767                               "     WHERE type = 'table' "
1768                               "       AND name IN "
1769                               "         ("
1770                               "           'ldb_entry', "
1771                               "           'ldb_object_classes' "
1772                               "         ) "
1773                               "  ) "
1774                               "  AND "
1775                               "  (SELECT 1 "
1776                               "     FROM ldb_info "
1777                               "     WHERE database_type = 'LDB' "
1778                               "       AND version = '1.0'"
1779                               "  );") != 0 ||
1780                     queryInt != 1) {
1781                         
1782                         /* It's not one that we created.  See ya! */
1783                         goto failed;
1784                 }
1785         }
1786         
1787         /* Commit the transaction */
1788         ret = sqlite3_exec(lsqlite3->sqlite, "COMMIT;", NULL, NULL, &errmsg);
1789         if (ret != SQLITE_OK) {
1790                 if (errmsg) {
1791                         printf("lsqlite3: iniialization error: %s\n", errmsg);
1792                         free(errmsg);
1793                 }
1794                 goto failed;
1795         }
1796  
1797         return SQLITE_OK;
1798
1799 failed:
1800         if (rollback) lsqlite3_safe_rollback(lsqlite3->sqlite); 
1801         sqlite3_close(lsqlite3->sqlite);
1802         return -1;
1803 }
1804
1805 static int
1806 destructor(void *p)
1807 {
1808         struct lsqlite3_private *lsqlite3 = p;
1809         
1810         if (lsqlite3->sqlite) {
1811                 sqlite3_close(lsqlite3->sqlite);
1812         }
1813         return 0;
1814 }
1815
1816
1817
1818 /*
1819  * Table of operations for the sqlite3 backend
1820  */
1821 static const struct ldb_module_ops lsqlite3_ops = {
1822         .name              = "sqlite",
1823         .search            = lsqlite3_search,
1824         .search_bytree     = lsqlite3_search_bytree,
1825         .add_record        = lsqlite3_add,
1826         .modify_record     = lsqlite3_modify,
1827         .delete_record     = lsqlite3_delete,
1828         .rename_record     = lsqlite3_rename,
1829         .start_transaction = lsqlite3_start_trans,
1830         .end_transaction   = lsqlite3_end_trans,
1831         .del_transaction   = lsqlite3_del_trans
1832 };
1833
1834 /*
1835  * connect to the database
1836  */
1837 int lsqlite3_connect(struct ldb_context *ldb,
1838                      const char *url, 
1839                      unsigned int flags, 
1840                      const char *options[])
1841 {
1842         int                         i;
1843         int                         ret;
1844         struct lsqlite3_private *   lsqlite3 = NULL;
1845         
1846         lsqlite3 = talloc(ldb, struct lsqlite3_private);
1847         if (!lsqlite3) {
1848                 goto failed;
1849         }
1850         
1851         lsqlite3->sqlite = NULL;
1852         lsqlite3->options = NULL;
1853         lsqlite3->trans_count = 0;
1854         
1855         ret = initialize(lsqlite3, ldb, url, flags);
1856         if (ret != SQLITE_OK) {
1857                 goto failed;
1858         }
1859         
1860         talloc_set_destructor(lsqlite3, destructor);
1861         
1862         ldb->modules = talloc(ldb, struct ldb_module);
1863         if (!ldb->modules) {
1864                 goto failed;
1865         }
1866         ldb->modules->ldb = ldb;
1867         ldb->modules->prev = ldb->modules->next = NULL;
1868         ldb->modules->private_data = lsqlite3;
1869         ldb->modules->ops = &lsqlite3_ops;
1870         
1871         if (options) {
1872                 /*
1873                  * take a copy of the options array, so we don't have to rely
1874                  * on the caller keeping it around (it might be dynamic)
1875                  */
1876                 for (i=0;options[i];i++) ;
1877                 
1878                 lsqlite3->options = talloc_array(lsqlite3, char *, i+1);
1879                 if (!lsqlite3->options) {
1880                         goto failed;
1881                 }
1882                 
1883                 for (i=0;options[i];i++) {
1884                         
1885                         lsqlite3->options[i+1] = NULL;
1886                         lsqlite3->options[i] =
1887                                 talloc_strdup(lsqlite3->options, options[i]);
1888                         if (!lsqlite3->options[i]) {
1889                                 goto failed;
1890                         }
1891                 }
1892         }
1893         
1894         return 0;
1895         
1896 failed:
1897         if (lsqlite3->sqlite != NULL) {
1898                 (void) sqlite3_close(lsqlite3->sqlite);
1899         }
1900         talloc_free(lsqlite3);
1901         return -1;
1902 }
1903