r7276: - moved static tdb function ltdb_dn_fold() into common/ so that it can be
[ira/wip.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 sqlite3 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 #define QUERY(lsqlite3, pppValues, pNumRows, bRollbackOnError, sql...)  \
41     do                                                                  \
42     {                                                                   \
43             if (query(lsqlite3, pppValues, pNumRows, sql) != 0) {       \
44                 if (bRollbackOnError) {                                 \
45                         query(lsqlite3, NULL, NULL, "ROLLBACK;");       \
46                 }                                                       \
47                 return -1;                                              \
48         }                                                               \
49     } while (0)
50
51
52 #if 0
53 /*
54  * we don't need this right now, but will once we add some backend options
55  *
56  * find an option in an option list (a null terminated list of strings)
57  *
58  * this assumes the list is short. If it ever gets long then we really should
59  * do this in some smarter way
60  */
61 static const char *
62 lsqlite3_option_find(const struct lsqlite3_private *lsqlite3,
63                      const char *name)
64 {
65         int                 i;
66         size_t              len = strlen(name);
67
68         if (!lsqlite3->options) return NULL;
69
70         for (i=0;lsqlite3->options[i];i++) {            
71                 if (strncmp(lsqlite3->options[i], name, len) == 0 &&
72                     lsqlite3->options[i][len] == '=') {
73                         return &lsqlite3->options[i][len+1];
74                 }
75         }
76
77         return NULL;
78 }
79 #endif
80
81 /*
82  * rename a record
83  */
84 static int
85 lsqlite3_rename(struct ldb_module *module,
86                 const char *olddn,
87                 const char *newdn)
88 {
89         int                         column;
90         struct lsqlite3_private *   lsqlite3 = module->private_data;
91
92         /* ignore ltdb specials */
93         if (olddn[0] == '@' ||newdn[0] == '@') {
94                 return 0;
95         }
96
97 #warning "rename() is not yet supported"
98         return -1;
99 }
100
101 /*
102  * delete a record
103  */
104 static int
105 lsqlite3_delete(struct ldb_module *module,
106                 const char *dn)
107 {
108         int                         ret = 0;
109         int                         column;
110         struct lsqlite3_private *   lsqlite3 = module->private_data;
111
112         /* ignore ltdb specials */
113         if (dn[0] == '@') {
114                 return 0;
115         }
116         
117         return -1;
118 }
119
120 /*
121  * free a search result
122  */
123 static int
124 lsqlite3_search_free(struct ldb_module *module,
125                      struct ldb_message **res)
126 {
127         talloc_free(res);
128         return 0;
129 }
130
131
132 /*
133  * add a single set of ldap message values to a ldb_message
134  */
135 static int
136 lsqlite3_add_msg_attr(struct ldb_context *ldb,
137                       struct ldb_message *msg, 
138                       const char *attr,
139                       struct berval **bval)
140 {
141         int                          i;
142         int                          count;
143         struct ldb_message_element * el;
144
145         count = ldap_count_values_len(bval);
146
147         if (count <= 0) {
148                 return -1;
149         }
150
151         el = talloc_realloc(msg, msg->elements, struct ldb_message_element, 
152                               msg->num_elements + 1);
153         if (!el) {
154                 errno = ENOMEM;
155                 return -1;
156         }
157
158         msg->elements = el;
159
160         el = &msg->elements[msg->num_elements];
161
162         el->name = talloc_strdup(msg->elements, attr);
163         if (!el->name) {
164                 errno = ENOMEM;
165                 return -1;
166         }
167         el->flags = 0;
168
169         el->num_values = 0;
170         el->values = talloc_array(msg->elements, struct ldb_val, count);
171         if (!el->values) {
172                 errno = ENOMEM;
173                 return -1;
174         }
175
176         for (i=0;i<count;i++) {
177                 el->values[i].data = talloc_memdup(el->values, bval[i]->bv_val, bval[i]->bv_len);
178                 if (!el->values[i].data) {
179                         return -1;
180                 }
181                 el->values[i].length = bval[i]->bv_len;
182                 el->num_values++;
183         }
184
185         msg->num_elements++;
186
187         return 0;
188 }
189
190 /*
191  * search for matching records
192  */
193 static int
194 lsqlite3_search(struct ldb_module *module,
195                 const char *base,
196                 enum ldb_scope scope,
197                 const char *expression,
198                 const char * const *attrs,
199                 struct ldb_message ***res)
200 {
201         int                       count;
202         int                       msg_count;
203         struct ldb_context *      ldb = module->ldb;
204         struct lsqlite3_private * lsqlite3 = module->private_data;
205
206         if (base == NULL) {
207                 base = "";
208         }
209
210         lsqlite3->last_rc = ldap_search_s(lsqlite3->ldap, base, (int)scope, 
211                                       expression, 
212                                       discard_const_p(char *, attrs), 
213                                       0, &ldapres);
214         if (lsqlite3->last_rc != LDAP_SUCCESS) {
215                 return -1;
216         }
217
218         count = ldap_count_entries(lsqlite3->ldap, ldapres);
219         if (count == -1 || count == 0) {
220                 ldap_msgfree(ldapres);
221                 return count;
222         }
223
224         (*res) = talloc_array(lsqlite3, struct ldb_message *, count+1);
225         if (! *res) {
226                 ldap_msgfree(ldapres);
227                 errno = ENOMEM;
228                 return -1;
229         }
230
231         (*res)[0] = NULL;
232
233         msg_count = 0;
234
235         /* loop over all messages */
236         for (msg=ldap_first_entry(lsqlite3->ldap, ldapres); 
237              msg; 
238              msg=ldap_next_entry(lsqlite3->ldap, msg)) {
239                 BerElement *berptr = NULL;
240                 char *attr, *dn;
241
242                 if (msg_count == count) {
243                         /* hmm, got too many? */
244                         ldb_debug(ldb, LDB_DEBUG_FATAL, "Fatal: ldap message count inconsistent\n");
245                         break;
246                 }
247
248                 (*res)[msg_count] = talloc(*res, struct ldb_message);
249                 if (!(*res)[msg_count]) {
250                         goto failed;
251                 }
252                 (*res)[msg_count+1] = NULL;
253
254                 dn = ldap_get_dn(lsqlite3->ldap, msg);
255                 if (!dn) {
256                         goto failed;
257                 }
258
259                 (*res)[msg_count]->dn = talloc_strdup((*res)[msg_count], dn);
260                 ldap_memfree(dn);
261                 if (!(*res)[msg_count]->dn) {
262                         goto failed;
263                 }
264
265
266                 (*res)[msg_count]->num_elements = 0;
267                 (*res)[msg_count]->elements = NULL;
268                 (*res)[msg_count]->private_data = NULL;
269
270                 /* loop over all attributes */
271                 for (attr=ldap_first_attribute(lsqlite3->ldap, msg, &berptr);
272                      attr;
273                      attr=ldap_next_attribute(lsqlite3->ldap, msg, berptr)) {
274                         struct berval **bval;
275                         bval = ldap_get_values_len(lsqlite3->ldap, msg, attr);
276
277                         if (bval) {
278                                 lsqlite3_add_msg_attr(ldb, (*res)[msg_count], attr, bval);
279                                 ldap_value_free_len(bval);
280                         }                                         
281                         
282                         ldap_memfree(attr);
283                 }
284                 if (berptr) ber_free(berptr, 0);
285
286                 msg_count++;
287         }
288
289         ldap_msgfree(ldapres);
290
291         return msg_count;
292
293 failed:
294         if (*res) lsqlite3_search_free(module, *res);
295         return -1;
296 }
297
298
299 /*
300  * Issue a series of SQL statements to implement the ADD/MODIFY/DELETE
301  * requests in the ldb_message
302  */
303 static int
304 lsqlite3_msg_to_sql(struct ldb_module *module,
305                     const struct ldb_message *msg,
306                     long long eid,
307                     int use_flags)
308 {
309         int                         flags;
310         unsigned int                i;
311         unsigned int                j;
312         sqlite3_stmt *              stmt = NULL;
313         struct ldb_context *        ldb = module->ldb;
314         struct lsqlite3_private *   lsqlite3 = module->private_data;
315
316         for (i = 0; i < msg->num_elements; i++) {
317                 const struct ldb_message_element *el = &msg->elements[i];
318
319                 if (! use_flags) {
320                         flags = LDB_FLAG_MOD_ADD;
321                 } else {
322                         flags = el->flags & LDB_FLAG_MOD_MASK;
323                 }
324
325                 if (flags == LDB_FLAG_MOD_ADD) {
326                         /* Create the attribute table if it doesn't exist */
327                         if (create_attr_table(module, el->name) != 0) {
328                                 return -1;
329                         }
330                 }
331
332                 /* For each value of the specified attribute name... */
333                 for (j = 0; j < el->num_values; j++) {
334
335                         /* ... bind the attribute value, if necessary */
336                         switch (flags) {
337                         case LDB_FLAG_MOD_ADD:
338                                 QUERY(lsqlite3,
339                                       NULL, NULL,
340                                       FALSE,
341                                       "INSERT INTO ldb_attr_%q "
342                                       "    (eid, attr_value) "
343                                       "  VALUES "
344                                       "    (%lld, %Q);",
345                                       eid, el->data);
346                                 QUERY(lsqlite3,
347                                       NULL, NULL,
348                                       FALSE,
349                                       "UPDATE ldb_entry "
350                                       "  SET entry_data = "
351                                       "        add_attr(entry_data, %Q, %Q) "
352                                       "  WHERE eid = %lld;",
353                                       el->name, el->data, eid);
354                                       
355                                 break;
356
357                         case LDB_FLAG_MOD_REPLACE:
358                                 QUERY(lsqlite3,
359                                       NULL, NULL,
360                                       FALSE,
361                                       "UPDATE ldb_attr_%q "
362                                       "  SET attr_value = %Q "
363                                       "  WHERE eid = %lld;",
364                                       el->data, eid);
365                                 QUERY(lsqlite3,
366                                       NULL, NULL,
367                                       FALSE,
368                                       "UPDATE ldb_entry "
369                                       "  SET entry_data = "
370                                       "        mod_attr(entry_data, %Q, %Q) "
371                                       "  WHERE eid = %lld;",
372                                       el->name, el->data, eid);
373                                 break;
374
375                         case LDB_FLAG_MOD_DELETE:
376                                 /* No additional parameters to this query */
377                                 QUERY(lsqlite3,
378                                       NULL, NULL,
379                                       FALSE,
380                                       "DELETE FROM ldb_attr_%q "
381                                       "  WHERE eid = %lld "
382                                       "    AND attr_value = %Q;",
383                                       eid, el->data);
384                                 QUERY(lsqlite3,
385                                       NULL, NULL,
386                                       FALSE,
387                                       "UPDATE ldb_entry "
388                                       "  SET entry_data = "
389                                       "        del_attr(entry_data, %Q, %Q) "
390                                       "  WHERE eid = %lld;",
391                                       el->name, el->data, eid);
392                                 break;
393                         }
394                 }
395         }
396
397         return 0;
398 }
399
400
401 static char *
402 lsqlite3_normalize_dn(struct ldb_context * ldb,
403                       char * pDN)
404 {
405         char *          pSrc;
406         char *          pDest;
407         char *          pNormalized;
408
409         pNormalized = talloc_size(ldb, strlen(pDN) + 1);
410         if (pNormalized == NULL) {
411                 errno = ENOMEM;
412                 return -1;
413         }
414         
415         for (pSrc = pDN, pDest = pNormalized; *pSrc != '\0'; ) {
416                 
417         }
418 }
419
420
421 static int
422 lsqlite3_insert_dn_recursive(struct lsqlite3_private * lsqlite3,
423                              char * pDN,
424                              long long * pEID)
425 {
426         
427 }
428
429
430 /*
431  * add a record
432  */
433 static int
434 lsqlite3_add(struct ldb_module *module,
435              const struct ldb_message *msg)
436 {
437         int                         ret;
438         long long                   eid;
439         struct ldb_context *        ldb = module->ldb;
440         struct lsqlite3_private *   lsqlite3 = module->private_data;
441
442         /* ignore ltdb specials */
443         if (msg->dn[0] == '@') {
444                 return 0;
445         }
446
447         /* Begin a transaction */
448         QUERY(lsqlite3, NULL, NULL< FALSE, "BEGIN EXCLUSIVE;");
449
450         /*
451          * Build any portions of the directory tree that don't exist.  If the
452          * final component already exists, it's an error.
453          */
454         if (lsqlite3_insert_dn_recursive(lsqlite3,
455                                          lsqlite3_normalize_dn(ldb, msg->dn),
456                                          &eid) != 0) {
457                 QUERY(lsqlite3, NULL, NULL, FALSE, "ROLLBACK;");
458                 return -1;
459         }
460
461         /* Add attributes to this new entry */
462         if (lsqlite3_msg_to_sql(module, msg, eid, FALSE) != 0) {
463                 QUERY(lsqlite3, NULL, NULL, FALSE, "ROLLBACK;");
464                 return -1;
465         }
466
467         /* Everything worked.  Commit it! */
468         QUERY(lsqlite3, NULL, NULL, TRUE, "COMMIT;");
469         return 0;
470 }
471
472
473 /*
474  * modify a record
475  */
476 static int
477 lsqlite3_modify(struct ldb_module *module,
478                 const struct ldb_message *msg)
479 {
480         int                         ret = 0;
481         int                         numRows;
482         char **                     ppValues;
483         struct ldb_context *        ldb = module->ldb;
484         struct lsqlite3_private *   lsqlite3 = module->private_data;
485
486         /* ignore ltdb specials */
487         if (msg->dn[0] == '@') {
488                 return 0;
489         }
490
491         /* Begin a transaction */
492         QUERY(lsqlite3, NULL, NULL, FALSE, "BEGIN EXCLUSIVE;");
493
494         /* Get the id of this DN. */
495         QUERY(lsqlite3,
496               &ppValues,
497               &numRows,
498               TRUE, 
499               "SELECT eid "
500               "  FROM ldb_entry "
501               "  WHERE dn = %Q;",
502               lsqlite3_normalize_dn(ldb, msg->dn));
503
504         /* Did it exist? */
505         if (numRows != 1) {
506                 /* Nope.  See ya! */
507                 sqlite_free_table(ppValues);
508                 return -1;
509         }
510
511         /* Retrieve the eid */
512         eid = strtoll(ppValues[1], NULL, 10);
513
514         /* Modify attributes as specified */
515         if (lsqlite3_msg_to_sql(module, msg, eid, FALSE) != 0) {
516                 QUERY(lsqlite3, NULL, NULL, FALSE, "ROLLBACK;");
517                 return -1;
518         }
519
520         /* Everything worked.  Commit it! */
521         QUERY(lsqlite3, NULL, NULL, TRUE, "COMMIT;");
522         return 0 ;
523 }
524
525 static int
526 lsqlite3_lock(struct ldb_module *module,
527               const char *lockname)
528 {
529         int                         ret = 0;
530         struct ldb_context *        ldb = module->ldb;
531         struct lsqlite3_private *   lsqlite3 = module->private_data;
532
533         if (lockname == NULL) {
534                 return -1;
535         }
536
537         /* TODO implement a local locking mechanism here */
538
539         return 0;
540 }
541
542 static int
543 lsqlite3_unlock(struct ldb_module *module,
544                 const char *lockname)
545 {
546         int                         ret = 0;
547         struct ldb_context *        ldb = module->ldb;
548         struct lsqlite3_private *   lsqlite3 = module->private_data;
549
550         if (lockname == NULL) {
551                 return -1;
552         }
553
554         /* TODO implement a local locking mechanism here */
555
556         return 0;
557 }
558
559 /*
560  * return extended error information
561  */
562 static const char *
563 lsqlite3_errstring(struct ldb_module *module)
564 {
565         struct lsqlite3_private *   lsqlite3 = module->private_data;
566
567         return sqlite3_errmsg(lsqlite3->sqlite3);
568 }
569
570
571 static const struct ldb_module_ops lsqlite3_ops = {
572         "sqlite",
573         lsqlite3_search,
574         lsqlite3_search_free,
575         lsqlite3_add,
576         lsqlite3_modify,
577         lsqlite3_delete,
578         lsqlite3_rename,
579         lsqlite3_lock,
580         lsqlite3_unlock,
581         lsqlite3_errstring
582 };
583
584
585 static int
586 lsqlite3_destructor(void *p)
587 {
588         struct lsqlite3_private *   lsqlite3 = p;
589
590         (void) sqlite3_close(lsqlite3->sqlite3);
591         return 0;
592 }
593
594 static int
595 lsqlite3_initialize(lsqlite3_private *lsqlite3,
596                     const char *url)
597 {
598         int             ret;
599         int             bNewDatabase = False;
600         char *          p;
601         char *          pTail;
602         struct stat     statbuf;
603         sqlite3_stmt *  stmt;
604         const char *    schema =       
605                 "
606                 -- ------------------------------------------------------
607
608                 PRAGMA auto_vacuum=1;
609
610                 -- ------------------------------------------------------
611
612                 BEGIN EXCLUSIVE;
613
614                 -- ------------------------------------------------------
615
616                 CREATE TABLE ldb_info AS 
617                   SELECT 'LDB' AS database_type, 
618                          '1.0' AS version;
619
620                 -- ------------------------------------------------------
621                 -- Schema
622
623                 /*
624                  * The entry table holds the information about an entry.  This
625                  * table is used to obtain the EID of the entry and to support
626                  * scope=one and scope=base.  The parent and child table
627                  * is included in the entry table since all the other
628                  * attributes on EID.
629                  */
630                 CREATE TABLE ldb_entry
631                 (
632                   -- Unique identifier of this LDB entry
633                   eid                   INTEGER PRIMARY KEY,
634
635                   -- Unique identifier of the parent LDB entry
636                   peid                  INTEGER REFERENCES ldb_entry,
637
638                   -- Distinguished name of this entry
639                   dn                    TEXT,
640
641                   -- Time when the entry was created
642                   create_timestamp      INTEGER,
643
644                   -- Time when the entry was last modified
645                   modify_timestamp      INTEGER,
646
647                   -- Attributes of this entry, in the form
648                   --   attr\1value\0[attr\1value\0]*\0
649                   entry_data            TEXT
650                 );
651
652
653                 /*
654                  * The purpose of the descendant table is to support the
655                  * subtree search feature.  For each LDB entry with a unique
656                  * ID (AEID), this table contains the unique identifiers
657                  * (DEID) of the descendant entries.
658                  *
659                  * For evern entry in the directory, a row exists in this
660                  * table for each of its ancestors including itself.  The size
661                  * of the table depends on the depth of each entry.  In the
662                  * worst case, if all the entries were at the same depth, the
663                  * number of rows in the table is O(nm) where n is the number
664                  * of nodes in the directory and m is the depth of the tree.
665                  */
666                 CREATE TABLE ldb_descendants
667                 (
668                   -- The unique identifier of the ancestor LDB entry
669                   aeid                  INTEGER REFERENCES ldb_entry,
670
671                   -- The unique identifier of the descendant LDB entry
672                   deid                  INTEGER REFERENCES ldb_entry
673                 );
674
675
676                 CREATE TABLE ldb_object_classes
677                 (
678                   -- Object classes are inserted into this table to track
679                   -- their class hierarchy.  'top' is the top-level class
680                   -- of which all other classes are subclasses.
681                   class_name            TEXT PRIMARY KEY,
682
683                   -- tree_key tracks the position of the class in
684                   -- the hierarchy 
685                   tree_key              TEXT UNIQUE
686                 );
687
688                 /*
689                  * There is one attribute table per searchable attribute.
690                  */
691 /*
692                 CREATE TABLE ldb_attr_ATTRIBUTE_NAME
693                 (
694                   -- The unique identifier of the LDB entry
695                   eid                   INTEGER REFERENCES ldb_entry,
696
697                   -- Normalized attribute value
698                   attr_value            TEXT
699                 );
700 */
701
702
703                 -- ------------------------------------------------------
704                 -- Indexes
705
706
707                 -- ------------------------------------------------------
708                 -- Triggers
709
710                 CREATE TRIGGER ldb_entry_insert_tr
711                   AFTER INSERT
712                   ON ldb_entry
713                   FOR EACH ROW
714                     BEGIN
715                       UPDATE ldb_entry
716                         SET create_timestamp = strftime('%s', 'now'),
717                             modify_timestamp = strftime('%s', 'now')
718                         WHERE eid = new.eid;
719                     END;
720
721                 CREATE TRIGGER ldb_entry_update_tr
722                   AFTER UPDATE
723                   ON ldb_entry
724                   FOR EACH ROW
725                     BEGIN
726                       UPDATE ldb_entry
727                         SET modify_timestamp = strftime('%s', 'now')
728                         WHERE eid = old.eid;
729                     END;
730
731                 -- ------------------------------------------------------
732                 -- Table initialization
733
734                 /* We need an implicit "top" level object class */
735                 INSERT INTO ldb_attributes (attr_name,
736                                             parent_tree_key)
737                   SELECT 'top', '';
738
739                 -- ------------------------------------------------------
740
741                 COMMIT;
742
743                 -- ------------------------------------------------------
744                 ";
745
746         /* Skip protocol indicator of url  */
747         if ((p = strchr(url, ':')) == NULL) {
748                 return SQLITE_MISUSE;
749         } else {
750                 ++p;
751         }
752                 
753         /*
754          * See if we'll be creating a new database, or opening an existing one
755          */
756         if ((stat(p, &statbuf) < 0 && errno == ENOENT) ||
757             statbuf.st_size == 0) {
758
759                 bNewDatabase = True;
760         }
761
762         /* Try to open the (possibly empty/non-existent) database */
763         if ((ret = sqlite3_open(p, &lsqlite3->sqlite3)) != SQLITE_SUCCESS) {
764                 return ret;
765         }
766
767         if (bNewDatabase) {
768                 /*
769                  * Create the database schema
770                  */
771                 for (pTail = schema; pTail != NULL; ) {
772
773                         if ((lsqlite3->last_rc = sqlite3_prepare(
774                                      lsqlite3->sqlite3,
775                                      pTail,
776                                      -1,
777                                      &stmt,
778                                      &pTail)) != SQLITE_SUCCESS ||
779                             (lsqlite3->last_rc = sqlite3_step(stmt)) != SQLITE_DONE ||
780                             (lsqlite3->last_rc = sqlite_finalize(stmt)) != SQLITE_SUCCESS) {
781
782                                 (void) sqlite3_close(lsqlite3->sqlite3);
783                                 return ret;
784                         }
785                 }
786         } else {
787                 /*
788                  * Ensure that the database we opened is one of ours
789                  */
790                 if ((lsqlite3->last_rc = sqlite3_prepare(
791                              lsqlite3->sqlite3,
792                              "SELECT COUNT(*) "
793                              "  FROM sqlite_master "
794                              "  WHERE type = 'table' "
795                              "    AND name IN "
796                              "      ("
797                              "        'ldb_entry', "
798                              "        'ldb_descendants', "
799                              "        'ldb_object_classes' "
800                              "      );",
801                              -1,
802                              &stmt,
803                              &pTail)) != SQLITE_SUCCESS ||
804                     (lsqlite3->last_rc = sqlite3_step(stmt)) != SQLITE_ROW ||
805                     sqlite3_column_int(stmt, 0) != 3 ||
806                     (lsqlite3->last_rc = sqlite_finalize(stmt)) != SQLITE_SUCCESS ||
807
808                     (lsqlite3->last_rc = sqlite3_prepare(
809                              lsqlite3->sqlite3,
810                              "SELECT 1 "
811                              "  FROM ldb_info "
812                              "  WHERE database_type = 'LDB' "
813                              "    AND version = '1.0';",
814                              -1,
815                              &stmt,
816                              &pTail)) != SQLITE_SUCCESS ||
817                     (lsqlite3->last_rc = sqlite3_step(stmt)) != SQLITE_ROW ||
818                     (lsqlite3->last_rc = sqlite_finalize(stmt)) != SQLITE_SUCCESS) {
819                 
820                         /* It's not one that we created.  See ya! */
821                         (void) sqlite3_close(lsqlite3->sqlite3);
822                         return SQLITE_MISUSE;
823                 }
824         }
825
826         return SQLITE_SUCCESS;
827 }
828
829 /*
830  * connect to the database
831  */
832 struct ldb_context *
833 lsqlite3_connect(const char *url, 
834                  unsigned int flags, 
835                  const char *options[])
836 {
837         int                         i;
838         struct ldb_context *        ldb = NULL;
839         struct lsqlite3_private *   lsqlite3 = NULL;
840
841         ldb = talloc(NULL, struct ldb_context);
842         if (!ldb) {
843                 errno = ENOMEM;
844                 goto failed;
845         }
846
847         lsqlite3 = talloc(ldb, struct lsqlite3_private);
848         if (!lsqlite3) {
849                 errno = ENOMEM;
850                 goto failed;
851         }
852
853         lsqlite3->sqlite3 = NULL;
854         lsqlite3->options = NULL;
855         lsqlite3->lock_count = 0;
856
857         lsqlite3->last_rc = lsqlite3_initialize(&lsqlite3->sqlite3, url);
858         if (lsqlite3->last_rc != SQLITE_SUCCESS) {
859                 goto failed;
860         }
861
862         talloc_set_destructor(lsqlite3, lsqlite3_destructor);
863
864         ldb->modules = talloc(ldb, struct ldb_module);
865         if (!ldb->modules) {
866                 errno = ENOMEM;
867                 goto failed;
868         }
869         ldb->modules->ldb = ldb;
870         ldb->modules->prev = ldb->modules->next = NULL;
871         ldb->modules->private_data = lsqlite3;
872         ldb->modules->ops = &lsqlite3_ops;
873
874         if (options) {
875                 /*
876                  * take a copy of the options array, so we don't have to rely
877                  * on the caller keeping it around (it might be dynamic)
878                  */
879                 for (i=0;options[i];i++) ;
880
881                 lsqlite3->options = talloc_array(lsqlite3, char *, i+1);
882                 if (!lsqlite3->options) {
883                         goto failed;
884                 }
885                 
886                 for (i=0;options[i];i++) {
887
888                         lsqlite3->options[i+1] = NULL;
889                         lsqlite3->options[i] =
890                                 talloc_strdup(lsqlite3->options, options[i]);
891                         if (!lsqlite3->options[i]) {
892                                 goto failed;
893                         }
894                 }
895         }
896
897         return ldb;
898
899 failed:
900         if (lsqlite3->sqlite3 != NULL) {
901                 (void) sqlite3_close(lsqlite3->sqlite3);
902         }
903         talloc_free(ldb);
904         return NULL;
905 }
906