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