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