r6956: added start of ldb_sqlite3 work
[kai/samba.git] / source4 / lib / ldb / ldb_sqlite3 / ldb_sqlite3.c
1 /* 
2    ldb database library
3
4    Copyright (C) Andrew Tridgell  2004
5
6      ** NOTE! The following LGPL license applies to the ldb
7      ** library. This does NOT imply that all of Samba is released
8      ** under the LGPL
9    
10    This library is free software; you can redistribute it and/or
11    modify it under the terms of the GNU Lesser General Public
12    License as published by the Free Software Foundation; either
13    version 2 of the License, or (at your option) any later version.
14
15    This library is distributed in the hope that it will be useful,
16    but WITHOUT ANY WARRANTY; without even the implied warranty of
17    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
18    Lesser General Public License for more details.
19
20    You should have received a copy of the GNU Lesser General Public
21    License along with this library; if not, write to the Free Software
22    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
23 */
24
25 /*
26  *  Name: ldb
27  *
28  *  Component: ldb sqlite backend
29  *
30  *  Description: core files for SQLITE3 backend
31  *
32  *  Author: Derrell Lipman (based on Andrew Tridgell's LDAP backend)
33  */
34
35 #include "includes.h"
36 #include "ldb/include/ldb.h"
37 #include "ldb/include/ldb_private.h"
38 #include "ldb/ldb_sqlite3/ldb_sqlite3.h"
39
40 #if 0
41 /*
42   we don't need this right now, but will once we add some backend 
43   options
44 */
45
46 /*
47   find an option in an option list (a null terminated list of strings)
48
49   this assumes the list is short. If it ever gets long then we really
50   should do this in some smarter way
51  */
52 static const char *lsqlite3_option_find(const struct lsqlite3_private *lsqlite3, const char *name)
53 {
54         int i;
55         size_t len = strlen(name);
56
57         if (!lsqlite3->options) return NULL;
58
59         for (i=0;lsqlite3->options[i];i++) {            
60                 if (strncmp(lsqlite3->options[i], name, len) == 0 &&
61                     lsqlite3->options[i][len] == '=') {
62                         return &lsqlite3->options[i][len+1];
63                 }
64         }
65
66         return NULL;
67 }
68 #endif
69
70 /*
71   rename a record
72 */
73 static int lsqlite3_rename(struct ldb_module *module, const char *olddn, const char *newdn)
74 {
75         int column;
76         struct lsqlite3_private *lsqlite3 = module->private_data;
77
78         /* ignore ltdb specials */
79         if (olddn[0] == '@' ||newdn[0] == '@') {
80                 return 0;
81         }
82
83         /* Bind old distinguished names */
84         column = sqlite3_bind_parameter_index(lsqlite3->renameDN, ":oldDN");
85         if (sqlite3_bind_text(lsqlite3->renameDN, column,
86                               olddn, strlen(olddn),
87                               SQLITE_STATIC) != SQLITE_OK) {
88                 return -1;
89         }
90
91         /* Bind new distinguished names */
92         column = sqlite3_bind_parameter_index(lsqlite3->renameDN, ":newDN");
93         if (sqlite3_bind_text(lsqlite3->renameDN, column,
94                               newdn, strlen(newdn),
95                               SQLITE_STATIC) != SQLITE_OK) {
96                 return -1;
97         }
98
99         do {
100                 lsqlite3->last_rc = sqlite3_step(lsqlite3->renameDN);
101                 (void) sqlite3_reset(lsqlite3->renameDN);
102         } while lsqlite3->last_rc == SQLITE3_BUSY;
103
104         return lsqlite3->last_rc == 0 ? 0 : -1;
105 }
106
107 /*
108   delete a record
109 */
110 static int lsqlite3_delete(struct ldb_module *module, const char *dn)
111 {
112         int ret = 0;
113         int column;
114         struct lsqlite3_private *lsqlite3 = module->private_data;
115
116         /* ignore ltdb specials */
117         if (dn[0] == '@') {
118                 return 0;
119         }
120         
121         /* Bind new distinguished names */
122         column = sqlite3_bind_parameter_index(lsqlite3->renameDN, ":dn");
123         if (sqlite3_bind_text(lsqlite3->deleteDN, column,
124                               dn, strlen(dn),
125                               SQLITE_STATIC) != SQLITE_OK) {
126                 return -1;
127         }
128
129         do {
130                 lsqlite3->last_rc = sqlite3_step(lsqlite3->deleteDN);
131                 (void) sqlite3_reset(lsqlite3->deleteDN);
132         } while lsqlite3->last_rc == SQLITE3_BUSY;
133
134         return lsqlite3->last_rc == 0 ? 0 : -1;
135 }
136
137 /*
138   free a search result
139 */
140 static int lsqlite3_search_free(struct ldb_module *module, struct ldb_message **res)
141 {
142         talloc_free(res);
143         return 0;
144 }
145
146
147 /*
148   add a single set of ldap message values to a ldb_message
149 */
150 static int lsqlite3_add_msg_attr(struct ldb_context *ldb,
151                              struct ldb_message *msg, 
152                              const char *attr, struct berval **bval)
153 {
154         int count, i;
155         struct ldb_message_element *el;
156
157         count = ldap_count_values_len(bval);
158
159         if (count <= 0) {
160                 return -1;
161         }
162
163         el = talloc_realloc(msg, msg->elements, struct ldb_message_element, 
164                               msg->num_elements + 1);
165         if (!el) {
166                 errno = ENOMEM;
167                 return -1;
168         }
169
170         msg->elements = el;
171
172         el = &msg->elements[msg->num_elements];
173
174         el->name = talloc_strdup(msg->elements, attr);
175         if (!el->name) {
176                 errno = ENOMEM;
177                 return -1;
178         }
179         el->flags = 0;
180
181         el->num_values = 0;
182         el->values = talloc_array(msg->elements, struct ldb_val, count);
183         if (!el->values) {
184                 errno = ENOMEM;
185                 return -1;
186         }
187
188         for (i=0;i<count;i++) {
189                 el->values[i].data = talloc_memdup(el->values, bval[i]->bv_val, bval[i]->bv_len);
190                 if (!el->values[i].data) {
191                         return -1;
192                 }
193                 el->values[i].length = bval[i]->bv_len;
194                 el->num_values++;
195         }
196
197         msg->num_elements++;
198
199         return 0;
200 }
201
202 /*
203   search for matching records
204 */
205 static int lsqlite3_search(struct ldb_module *module, const char *base,
206                        enum ldb_scope scope, const char *expression,
207                        const char * const *attrs, struct ldb_message ***res)
208 {
209         struct ldb_context *ldb = module->ldb;
210         struct lsqlite3_private *lsqlite3 = module->private_data;
211         int count, msg_count;
212
213         if (base == NULL) {
214                 base = "";
215         }
216
217         lsqlite3->last_rc = ldap_search_s(lsqlite3->ldap, base, (int)scope, 
218                                       expression, 
219                                       discard_const_p(char *, attrs), 
220                                       0, &ldapres);
221         if (lsqlite3->last_rc != LDAP_SUCCESS) {
222                 return -1;
223         }
224
225         count = ldap_count_entries(lsqlite3->ldap, ldapres);
226         if (count == -1 || count == 0) {
227                 ldap_msgfree(ldapres);
228                 return count;
229         }
230
231         (*res) = talloc_array(lsqlite3, struct ldb_message *, count+1);
232         if (! *res) {
233                 ldap_msgfree(ldapres);
234                 errno = ENOMEM;
235                 return -1;
236         }
237
238         (*res)[0] = NULL;
239
240         msg_count = 0;
241
242         /* loop over all messages */
243         for (msg=ldap_first_entry(lsqlite3->ldap, ldapres); 
244              msg; 
245              msg=ldap_next_entry(lsqlite3->ldap, msg)) {
246                 BerElement *berptr = NULL;
247                 char *attr, *dn;
248
249                 if (msg_count == count) {
250                         /* hmm, got too many? */
251                         ldb_debug(ldb, LDB_DEBUG_FATAL, "Fatal: ldap message count inconsistent\n");
252                         break;
253                 }
254
255                 (*res)[msg_count] = talloc(*res, struct ldb_message);
256                 if (!(*res)[msg_count]) {
257                         goto failed;
258                 }
259                 (*res)[msg_count+1] = NULL;
260
261                 dn = ldap_get_dn(lsqlite3->ldap, msg);
262                 if (!dn) {
263                         goto failed;
264                 }
265
266                 (*res)[msg_count]->dn = talloc_strdup((*res)[msg_count], dn);
267                 ldap_memfree(dn);
268                 if (!(*res)[msg_count]->dn) {
269                         goto failed;
270                 }
271
272
273                 (*res)[msg_count]->num_elements = 0;
274                 (*res)[msg_count]->elements = NULL;
275                 (*res)[msg_count]->private_data = NULL;
276
277                 /* loop over all attributes */
278                 for (attr=ldap_first_attribute(lsqlite3->ldap, msg, &berptr);
279                      attr;
280                      attr=ldap_next_attribute(lsqlite3->ldap, msg, berptr)) {
281                         struct berval **bval;
282                         bval = ldap_get_values_len(lsqlite3->ldap, msg, attr);
283
284                         if (bval) {
285                                 lsqlite3_add_msg_attr(ldb, (*res)[msg_count], attr, bval);
286                                 ldap_value_free_len(bval);
287                         }                                         
288                         
289                         ldap_memfree(attr);
290                 }
291                 if (berptr) ber_free(berptr, 0);
292
293                 msg_count++;
294         }
295
296         ldap_msgfree(ldapres);
297
298         return msg_count;
299
300 failed:
301         if (*res) lsqlite3_search_free(module, *res);
302         return -1;
303 }
304
305
306 /*
307   Issue a series of SQL statements to implement the requests in the ldb_message
308 */
309 static int lsqlite3_msg_to_sql(struct ldb_context *ldb,
310                                const struct ldb_message *msg,
311                                int modify_existing)
312 {
313         unsigned int i, j;
314         struct ldb_context *ldb = module->ldb;
315         struct lsqlite3_private *lsqlite3 = module->private_data;
316         sqlite3_stmt *stmt = NULL;
317
318         for (i=0;i<msg->num_elements;i++) {
319                 const struct ldb_message_element *el = &msg->elements[i];
320
321                 if (! modify_existing) {
322                         /* This is a new DN.  Bind new distinguished name */
323                         column =
324                                 sqlite3_bind_parameter_index(
325                                         lsqlite3->queries.newDN,
326                                         ":dn");
327                         if (sqlite3_bind_text(lsqlite3->queries.newDN, column,
328                                               msg->dn, strlen(msg->dn),
329                                               SQLITE_STATIC) != SQLITE_OK) {
330                                 return -1;
331                         }
332
333                         /* Add this new DN */
334                         do {
335                                 lsqlite3->last_rc =
336                                         sqlite3_step(lsqlite3->queries.newDN);
337                                 (void) sqlite3_reset(lsqlite3->queries.newDN);
338                         } while lsqlite3->last_rc == SQLITE_BUSY;
339                         
340                         if (lsqlite3->last_rc != SQLITE_DONE) {
341                                 return -1;
342                         }
343
344                         dn_id = last_insert_rowid(lsqlite3->sqlite3);
345
346                         stmt = lsqlite3->queries.newAttribute;
347
348                 } else {
349                         /* Get the dn_id for the specified DN */
350                         xxx;
351
352                         switch (el->flags & LDB_FLAG_MOD_MASK) {
353                         case LDB_FLAG_MOD_ADD:
354                                 stmt = lsqlite3->queries.addAttrValuePair;
355                                 break;
356                         case LDB_FLAG_MOD_DELETE:
357                                 stmt = lsqlite3->queries.deleteAttrValuePairs;
358                                 break;
359                         case LDB_FLAG_MOD_REPLACE:
360                                 stmt = lsqlite3->queries.replaceAttrValuePairs;
361                                 break;
362                         }
363                         
364                 }
365
366                 for (j=0;j<el->num_values;j++) {
367                         mods[num_mods]->mod_vals.modv_bvals[j] = talloc(mods[num_mods]->mod_vals.modv_bvals,
368                                                                           struct berval);
369                         if (!mods[num_mods]->mod_vals.modv_bvals[j]) {
370                                 goto failed;
371                         }
372                         mods[num_mods]->mod_vals.modv_bvals[j]->bv_val = el->values[j].data;
373                         mods[num_mods]->mod_vals.modv_bvals[j]->bv_len = el->values[j].length;
374                 }
375                 mods[num_mods]->mod_vals.modv_bvals[j] = NULL;
376                 num_mods++;
377         }
378
379         return mods;
380
381 failed:
382         talloc_free(mods);
383         return NULL;
384 }
385
386
387 /*
388   add a record
389 */
390 static int lsqlite3_add(struct ldb_module *module, const struct ldb_message *msg)
391 {
392         struct ldb_context *ldb = module->ldb;
393         struct lsqlite3_private *lsqlite3 = module->private_data;
394         LDAPMod **mods;
395         int ret = 0;
396
397         /* ignore ltdb specials */
398         if (msg->dn[0] == '@') {
399                 return 0;
400         }
401
402         mods = lsqlite3_msg_to_mods(ldb, msg, 0);
403
404         lsqlite3->last_rc = ldap_add_s(lsqlite3->ldap, msg->dn, mods);
405         if (lsqlite3->last_rc != LDAP_SUCCESS) {
406                 ret = -1;
407         }
408
409         talloc_free(mods);
410
411         return ret;
412 }
413
414
415 /*
416   modify a record
417 */
418 static int lsqlite3_modify(struct ldb_module *module, const struct ldb_message *msg)
419 {
420         struct ldb_context *ldb = module->ldb;
421         struct lsqlite3_private *lsqlite3 = module->private_data;
422         LDAPMod **mods;
423         int ret = 0;
424
425         /* ignore ltdb specials */
426         if (msg->dn[0] == '@') {
427                 return 0;
428         }
429
430         mods = lsqlite3_msg_to_mods(ldb, msg, 1);
431
432         lsqlite3->last_rc = ldap_modify_s(lsqlite3->ldap, msg->dn, mods);
433         if (lsqlite3->last_rc != LDAP_SUCCESS) {
434                 ret = -1;
435         }
436
437         talloc_free(mods);
438
439         return ret;
440 }
441
442 static int lsqlite3_lock(struct ldb_module *module, const char *lockname)
443 {
444         int ret = 0;
445         struct ldb_context *ldb = module->ldb;
446         struct lsqlite3_private *lsqlite3 = module->private_data;
447
448         if (lockname == NULL) {
449                 return -1;
450         }
451
452         /* If we're already locked, just update lock count */
453         if (++lsqlite3->lock_count > 1) {
454                 return -1;
455         }
456             
457         /* Write-lock (but not read-lock) the database */
458         lsqlite3->last_rc = sqlite3_step(lsqlite3->begin);
459
460         /* Ready the compiled statememt for its next use */
461         (void ) sqlite_reset(lsqlite3->begin);
462
463         return lsqlite3->last_rc == 0 ? 0 : -1;
464 }
465
466 static int lsqlite3_unlock(struct ldb_module *module, const char *lockname)
467 {
468         int ret = 0;
469         struct ldb_context *ldb = module->ldb;
470         struct lsqlite3_private *lsqlite3 = module->private_data;
471
472         if (lockname == NULL) {
473                 return -1;
474         }
475
476         /* If we're not already locked, there's nothing to do */
477         if (lsqlite3->lock_count == 0) {
478                 return 0;
479         }
480
481         /* Decrement lock count */
482         if (--lsqlite3->lock_count == 0) {
483         
484                 /* Final unlock.  Unlock the database */
485                 lsqlite3->last_rc = sqlite3_step(lsqlite3->commit);
486
487                 /* Ready the compiled statememt for its next use */
488                 (void ) sqlite_reset(lsqlite3->commit);
489         }
490
491         return lsqlite3->last_rc == 0 ? 0 : -1;
492 }
493
494 /*
495   return extended error information
496 */
497 static const char *lsqlite3_errstring(struct ldb_module *module)
498 {
499         struct lsqlite3_private *lsqlite3 = module->private_data;
500         return sqlite3_errmsg(lsqlite3->sqlite3);
501 }
502
503
504 static const struct ldb_module_ops lsqlite3_ops = {
505         "sqlite",
506         lsqlite3_search,
507         lsqlite3_search_free,
508         lsqlite3_add,
509         lsqlite3_modify,
510         lsqlite3_delete,
511         lsqlite3_rename,
512         lsqlite3_lock,
513         lsqlite3_unlock,
514         lsqlite3_errstring
515 };
516
517
518 static int lsqlite3_destructor(void *p)
519 {
520         struct lsqlite3_private *lsqlite3 = p;
521         (void) sqlite3_close(lsqlite3->sqlite3);
522         return 0;
523 }
524
525 static int lsqlite3_initialize(lsqlite3_private *lsqlite3,
526                                const char *url)
527 {
528         int bNewDatabase = False;
529         char *p;
530         char *pTail;
531         struct stat statbuf;
532         sqlite3_stmt *stmt;
533         const char *schema =
534                 "
535                 -- ------------------------------------------------------
536
537                 PRAGMA auto_vacuum=1;
538
539                 -- ------------------------------------------------------
540
541                 BEGIN EXCLUSIVE;
542
543                 -- ------------------------------------------------------
544
545                 CREATE TABLE ldb_info AS 
546                   SELECT 'LDB' AS database_type, 
547                          '1.0' AS version;
548
549                 CREATE TABLE ldb_distinguished_names 
550                 (
551                   dn_id         INTEGER PRIMARY KEY AUTOINCREMENT, 
552                   dn            TEXT UNIQUE
553                 );
554
555                 CREATE TABLE ldb_object_classes 
556                 (
557                   class_name    TEXT PRIMARY KEY,
558                   tree_key      TEXT,
559                   max_child_num INTEGER
560                 );
561
562                 CREATE TABLE ldb_dn_object_classes 
563                 (
564                   dn_id         INTEGER REFERENCES ldb_distinguished_names, 
565                   class_name    TEXT REFERENCES ldb_object_classes 
566                 );
567
568                 CREATE TABLE ldb_attributes
569                 (
570                   attr_name             TEXT PRIMARY KEY,
571                   case_insensitive_p    BOOLEAN DEFAULT FALSE,
572                   wildcard_p            BOOLEAN DEFAULT FALSE,
573                   hidden_p              BOOLEAN DEFAULT FALSE,
574                   integer_p             BOOLEAN DEFAULT FALSE
575                 );
576
577                 CREATE TABLE ldb_attr_value_pairs 
578                 (
579                   dn_id         INTEGER REFERENCES ldb_distinguished_names, 
580                   attr_name     TEXT REFERENCES ldb_attributes,
581                   attr_value    TEXT 
582                 );
583
584                 -- ------------------------------------------------------
585
586                 CREATE TRIGGER ldb_distinguished_names_delete_tr
587                   AFTER DELETE
588                   ON ldb_distinguished_names
589                   FOR EACH ROW
590                     BEGIN
591                       DELETE FROM ldb_attr_value_pairs
592                         WHERE dn_id = old.dn_id;
593                       DELETE FROM ldb_dn_object_classes
594                         WHERE dn_id = old.dn_id;
595                     END;
596
597                 CREATE TRIGGER ldb_attr_value_pairs_insert_tr
598                   BEFORE INSERT
599                   ON ldb_attr_value_pairs
600                   FOR EACH ROW
601                     BEGIN
602                       INSERT OR IGNORE INTO ldb_attributes
603                           (attr_name)
604                         VALUES
605                           (new.attr_name);
606                     END;
607
608                 CREATE TRIGGER ldb_attr_value_pairs_delete_tr
609                   AFTER DELETE
610                   ON ldb_attr_value_pairs
611                   FOR EACH ROW
612                     BEGIN
613                       DELETE FROM ldb_attributes
614                         WHERE (SELECT COUNT(*)
615                                  FROM ldb_attr_value_pairs
616                                  WHERE attr_name = old.attr_name) = 0
617                           AND attr_name = old.attr_name;
618                     END;
619
620                 -- ------------------------------------------------------
621
622                 CREATE INDEX ldb_distinguished_names_dn_idx
623                   ON ldb_distinguished_names (dn);
624
625                 CREATE INDEX ldb_object_classes_tree_key_idx
626                   ON ldb_object_classes (tree_key);
627
628
629                 CREATE INDEX ldb_dn_object_classes_dn_id_idx
630                   ON ldb_dn_object_classes (dn_id);
631
632                 CREATE INDEX ldb_dn_object_classes_class_name_idx
633                   ON ldb_dn_object_classes (class_name);
634
635
636                 CREATE INDEX ldb_attr_value_pairs_dn_id_name_case_idx
637                   ON ldb_attr_value_pairs (dn_id, attr_name);
638
639                 CREATE INDEX ldb_attr_value_pairs_dn_id_name_nocase_idx
640                   ON ldb_attr_value_pairs (dn_id, attr_name COLLATE NOCASE);
641
642                 -- ------------------------------------------------------
643
644                 /* all defaults for dn, initially */
645                 INSERT INTO ldb_attributes (attr_name)
646                   VALUES ('dn');
647
648                 /* We need an implicit "top" level object class */
649                 INSERT INTO ldb_object_classes (class_name, tree_key)
650                   SELECT 'top', /* next_tree_key(NULL) */ '0001';
651
652                 -- ------------------------------------------------------
653
654                 COMMIT;
655
656                 -- ------------------------------------------------------
657                 ";
658
659         /* Skip protocol indicator of url  */
660         if ((p = strchr(url, ':')) == NULL) {
661                 return SQLITE_MISUSE;
662         } else {
663                 ++p;
664         }
665                 
666         /*
667          * See if we'll be creating a new database, or opening an existing one
668          */
669         if ((stat(p, &statbuf) < 0 && errno == ENOENT) ||
670             statbuf.st_size == 0) {
671
672                 bNewDatabase = True;
673         }
674
675         /* Try to open the (possibly empty/non-existent) database */
676         if ((lsqlite3->last_rc = sqlite3_open(p, &lsqlite3->sqlite3)) != SQLITE_SUCCESS) {
677                 return ret;
678         }
679
680         if (bNewDatabase) {
681                 /*
682                  * Create the database schema
683                  */
684                 for (pTail = schema; pTail != NULL; ) {
685
686                         if ((lsqlite3->last_rc = sqlite3_prepare(
687                                      lsqlite3->sqlite3,
688                                      pTail,
689                                      -1,
690                                      &stmt,
691                                      &pTail)) != SQLITE_SUCCESS ||
692                             (lsqlite3->last_rc = sqlite3_step(stmt)) != SQLITE_DONE ||
693                             (lsqlite3->last_rc = sqlite_finalize(stmt)) != SQLITE_SUCCESS) {
694
695                                 (void) sqlite3_close(lsqlite3->sqlite3);
696                                 return ret;
697                         }
698                 }
699         } else {
700                 /*
701                  * Ensure that the database we opened is one of ours
702                  */
703                 if ((lsqlite3->last_rc = sqlite3_prepare(
704                              lsqlite3->sqlite3,
705                              "SELECT COUNT(*) "
706                              "  FROM sqlite_master "
707                              "  WHERE type = 'table' "
708                              "    AND name IN "
709                              "      ("
710                              "        'ldb_info', "
711                              "        'ldb_distinguished_names', "
712                              "        'ldb_object_classes', "
713                              "        'ldb_dn_object_classes', "
714                              "        'ldb_attributes', "
715                              "        'ldb_attr_value_pairs' "
716                              "      );",
717                              -1,
718                              &stmt,
719                              &pTail)) != SQLITE_SUCCESS ||
720                     (lsqlite3->last_rc = sqlite3_step(stmt)) != SQLITE_ROW ||
721                     sqlite3_column_int(stmt, 0) != 6 ||
722                     (lsqlite3->last_rc = sqlite_finalize(stmt)) != SQLITE_SUCCESS ||
723
724                     (lsqlite3->last_rc = sqlite3_prepare(
725                              lsqlite3->sqlite3,
726                              "SELECT 1 "
727                              "  FROM ldb_info "
728                              "  WHERE database_type = 'LDB' "
729                              "    AND version = '1.0';",
730                              -1,
731                              &stmt,
732                              &pTail)) != SQLITE_SUCCESS ||
733                     (lsqlite3->last_rc = sqlite3_step(stmt)) != SQLITE_ROW ||
734                     (lsqlite3->last_rc = sqlite_finalize(stmt)) != SQLITE_SUCCESS) {
735                 
736                         /* It's not one that we created.  See ya! */
737                         (void) sqlite3_close(lsqlite3->sqlite3);
738                         return SQLITE_MISUSE;
739                 }
740         }
741
742         /*
743          * Pre-compile each of the queries we'll be using.
744          */
745
746         if ((lsqlite3->last_rc = sqlite3_prepare(
747                      lsqlite3->sqlite3,
748                      "BEGIN IMMEDIATE;",
749                      -1,
750                      &lsqlite3->queries.begin,
751                      &pTail)) != SQLITE_SUCCESS ||
752
753             (lsqlite3->last_rc = sqlite3_prepare(
754                      lsqlite3->sqlite3,
755                      "COMMIT;",
756                      -1,
757                      &lsqlite3->queries.commit,
758                      &pTail)) != SQLITE_SUCCESS ||
759
760             (lsqlite3->last_rc = sqlite3_prepare(
761                      lsqlite3->sqlite3,
762                      "ROLLBACK;",
763                      -1,
764                      &lsqlite3->queries.rollback,
765                      &pTail)) != SQLITE_SUCCESS ||
766
767             (lsqlite3->last_rc = sqlite3_prepare(
768                      lsqlite3->sqlite3,
769                      "INSERT INTO ldb_distinguished_names (dn_id, dn) "
770                      "  VALUES (:dn_id, :dn);",
771                      -1,
772                      &lsqlite3->queries.newDN,
773                      &pTail)) != SQLITE_SUCCESS ||
774
775             (lsqlite3->last_rc = sqlite3_prepare(
776                      lsqlite3->sqlite3,
777                      "UPDATE ldb_distinguished_names "
778                      "  SET dn = :newDN "
779                      "  WHERE dn = :oldDN;",
780                      -1,
781                      &lsqlite3->queries.renameDN,
782                      &pTail)) != SQLITE_SUCCESS ||
783
784             (lsqlite3->last_rc = sqlite3_prepare(
785                      lsqlite3->sqlite3,
786                      "DELETE FROM ldb_distinguished_names "
787                      "  WHERE dn = :dn;",
788                      -1,
789                      &lsqlite3->queries.deleteDN,
790                      &pTail)) != SQLITE_SUCCESS ||
791
792             (lsqlite3->last_rc = sqlite3_prepare(
793                      lsqlite3->sqlite3,
794                      "INSERT OR IGNORE INTO ldb_object_classes "
795                      "    (class_name, tree_key)"
796                      "  SELECT :class_name, next_tree_key(NULL);",
797                      -1,
798                      &lsqlite3->queries.newObjectClass,
799                      &pTail)) != SQLITE_SUCCESS ||
800             
801             (lsqlite3->last_rc = sqlite3_prepare(
802                      lsqlite3->sqlite3,
803                      "INSERT OR REPLACE INTO ldb_dn_object_classes "
804                      "    (dn_id, class_name) "
805                      "  VALUES (:dn_id, :class_name);",
806                      -1,
807                      &lsqlite3->queries.assignObjectClass,
808                      &pTail)) != SQLITE_SUCCESS ||
809             
810             (lsqlite3->last_rc = sqlite3_prepare(
811                      lsqlite3->sqlite3,
812                      "INSERT OR IGNORE INTO ldb_attributes (name) "
813                      "  VALUES (:name);",
814                      -1,
815                      &lsqlite3->queries.newAttributeUseDefaults,
816                      &pTail)) != SQLITE_SUCCESS ||
817             
818             (lsqlite3->last_rc = sqlite3_prepare(
819                      lsqlite3->sqlite3,
820                      "INSERT OR REPLACE INTO ldb_attributes "
821                      "    (name, "
822                      "     case_insensitive_p, "
823                      "     wildcard_p, "
824                      "     hidden_p, "
825                      "     integer_p) "
826                      "  VALUES (:name, "
827                      "          :case_insensitive_p, "
828                      "          :wildcard_p, "
829                      "          :hidden_p, "
830                      "          :integer_p);",
831                      -1,
832                      &lsqlite3->queries.newAttribute,
833                      &pTail)) != SQLITE_SUCCESS ||
834             
835             (lsqlite3->last_rc = sqlite3_prepare(
836                      lsqlite3->sqlite3,
837                      "INSERT INTO ldb_attr_value_pairs "
838                      "    (dn_id, attr_name, attr_value) "
839                      "  VALUES (:dn_id, :attr_name, :attr_value);",
840                      -1,
841                      &lsqlite3->queries.addAttrValuePair,
842                      &pTail)) != SQLITE_SUCCESS ||
843             
844             (lsqlite3->last_rc = sqlite3_prepare(
845                      lsqlite3->sqlite3,
846                      "UPDATE ldb_attr_value_pairs "
847                      "  SET attr_value = :attr_value "
848                      "  WHERE dn_id = :dn_id "
849                      "    AND attr_name = :attr_name;",
850                      -1,
851                      &lsqlite3->queries.addAttrValuePair,
852                      &pTail)) != SQLITE_SUCCESS ||
853             
854             (lsqlite3->last_rc = sqlite3_prepare(
855                      lsqlite3->sqlite3,
856                      "DELETE FROM ldb_attr_value_pairs "
857                      "  WHERE dn_id = :dn_id "
858                      "    AND attr_name = :attr_name;"
859                      -1,
860                      &lsqlite3->queries.deleteAttrValuePair,
861                      &pTail)) != SQLITE_SUCCESS ||
862             
863             (lsqlite3->last_rc = sqlite3_prepare(
864                      lsqlite3->sqlite3,
865                      "INSERT OR REPLACE INTO ldb_object_classes "
866                      "    (class_name, tree_key) "
867                      "  SELECT :child_class, next_tree_key(:parent_class);"
868                      -1,
869                      &lsqlite3->queries.insertSubclass,
870                      &pTail)) != SQLITE_SUCCESS) {
871
872                 (void) sqlite3_close(lsqlite3->sqlite3);
873                 return ret;
874         }
875
876         return SQLITE_SUCCESS;
877 }
878
879 /*
880   connect to the database
881 */
882 struct ldb_context *lsqlite3_connect(const char *url, 
883                                  unsigned int flags, 
884                                  const char *options[])
885 {
886         struct ldb_context *ldb = NULL;
887         struct lsqlite3_private *lsqlite3 = NULL;
888         int i;
889
890         ldb = talloc(NULL, struct ldb_context);
891         if (!ldb) {
892                 errno = ENOMEM;
893                 goto failed;
894         }
895
896         lsqlite3 = talloc(ldb, struct lsqlite3_private);
897         if (!lsqlite3) {
898                 errno = ENOMEM;
899                 goto failed;
900         }
901
902         lsqlite3->sqlite3 = NULL;
903         lsqlite3->options = NULL;
904         lsqlite3->lock_count = 0;
905
906         lsqlite3->last_rc = lsqlite3_initialize(&lsqlite3->sqlite3, url);
907         if (lsqlite3->last_rc != LDAP_SUCCESS) {
908                 goto failed;
909         }
910
911         talloc_set_destructor(lsqlite3, lsqlite3_destructor);
912
913         ldb->modules = talloc(ldb, struct ldb_module);
914         if (!ldb->modules) {
915                 errno = ENOMEM;
916                 goto failed;
917         }
918         ldb->modules->ldb = ldb;
919         ldb->modules->prev = ldb->modules->next = NULL;
920         ldb->modules->private_data = lsqlite3;
921         ldb->modules->ops = &lsqlite3_ops;
922
923         if (options) {
924                 /* take a copy of the options array, so we don't have to rely
925                    on the caller keeping it around (it might be dynamic) */
926                 for (i=0;options[i];i++) ;
927
928                 lsqlite3->options = talloc_array(lsqlite3, char *, i+1);
929                 if (!lsqlite3->options) {
930                         goto failed;
931                 }
932                 
933                 for (i=0;options[i];i++) {
934                         lsqlite3->options[i+1] = NULL;
935                         lsqlite3->options[i] = talloc_strdup(lsqlite3->options, options[i]);
936                         if (!lsqlite3->options[i]) {
937                                 goto failed;
938                         }
939                 }
940         }
941
942         return ldb;
943
944 failed:
945         if (lsqlite3->sqlite3 != NULL) {
946                 (void) sqlite3_close(lsqlite3->sqlite3);
947         }
948         talloc_free(ldb);
949         return NULL;
950 }
951