fixes
[oweals/gnunet.git] / src / datastore / plugin_datastore_sqlite.c
1  /*
2      This file is part of GNUnet
3      (C) 2009 Christian Grothoff (and other contributing authors)
4
5      GNUnet is free software; you can redistribute it and/or modify
6      it under the terms of the GNU General Public License as published
7      by the Free Software Foundation; either version 2, or (at your
8      option) any later version.
9
10      GNUnet is distributed in the hope that it will be useful, but
11      WITHOUT ANY WARRANTY; without even the implied warranty of
12      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13      General Public License for more details.
14
15      You should have received a copy of the GNU General Public License
16      along with GNUnet; see the file COPYING.  If not, write to the
17      Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18      Boston, MA 02111-1307, USA.
19 */
20
21 /**
22  * @file datastore/plugin_datastore_sqlite.c
23  * @brief sqlite-based datastore backend
24  * @author Christian Grothoff
25  */
26
27 #include "platform.h"
28 #include "gnunet_statistics_service.h"
29 #include "plugin_datastore.h"
30 #include <sqlite3.h>
31
32 #define DEBUG_SQLITE GNUNET_YES
33
34 /**
35  * After how many payload-changing operations
36  * do we sync our statistics?
37  */
38 #define MAX_STAT_SYNC_LAG 50
39
40 #define QUOTA_STAT_NAME gettext_noop ("file-sharing datastore utilization (in bytes)")
41
42
43 /**
44  * Die with an error message that indicates
45  * a failure of the command 'cmd' with the message given
46  * by strerror(errno).
47  */
48 #define DIE_SQLITE(db, cmd) do { GNUNET_log_from(GNUNET_ERROR_TYPE_ERROR, "sqlite", _("`%s' failed at %s:%d with error: %s\n"), cmd, __FILE__, __LINE__, sqlite3_errmsg(db->dbh)); abort(); } while(0)
49
50 /**
51  * Log an error message at log-level 'level' that indicates
52  * a failure of the command 'cmd' on file 'filename'
53  * with the message given by strerror(errno).
54  */
55 #define LOG_SQLITE(db, msg, level, cmd) do { GNUNET_log_from (level, "sqlite", _("`%s' failed at %s:%d with error: %s\n"), cmd, __FILE__, __LINE__, sqlite3_errmsg(db->dbh)); if (msg != NULL) GNUNET_asprintf(msg, _("`%s' failed with error: %s\n"), cmd, sqlite3_errmsg(db->dbh)); } while(0)
56
57 #define SELECT_IT_LOW_PRIORITY_1 \
58   "SELECT size,type,prio,anonLevel,expire,hash,value,_ROWID_ FROM gn080 WHERE (prio = ? AND hash > ?) "\
59   "ORDER BY hash ASC LIMIT 1"
60
61 #define SELECT_IT_LOW_PRIORITY_2 \
62   "SELECT size,type,prio,anonLevel,expire,hash,value,_ROWID_ FROM gn080 WHERE (prio > ?) "\
63   "ORDER BY prio ASC, hash ASC LIMIT 1"
64
65 #define SELECT_IT_NON_ANONYMOUS_1 \
66   "SELECT size,type,prio,anonLevel,expire,hash,value,_ROWID_ FROM gn080 WHERE (prio = ? AND hash < ? AND anonLevel = 0 AND expire > %llu) "\
67   " ORDER BY hash DESC LIMIT 1"
68
69 #define SELECT_IT_NON_ANONYMOUS_2 \
70   "SELECT size,type,prio,anonLevel,expire,hash,value,_ROWID_ FROM gn080 WHERE (prio < ? AND anonLevel = 0 AND expire > %llu)"\
71   " ORDER BY prio DESC, hash DESC LIMIT 1"
72
73 #define SELECT_IT_EXPIRATION_TIME_1 \
74   "SELECT size,type,prio,anonLevel,expire,hash,value,_ROWID_ FROM gn080 WHERE (expire = ? AND hash > ?) "\
75   " ORDER BY hash ASC LIMIT 1"
76
77 #define SELECT_IT_EXPIRATION_TIME_2 \
78   "SELECT size,type,prio,anonLevel,expire,hash,value,_ROWID_ FROM gn080 WHERE (expire > ?) "\
79   " ORDER BY expire ASC, hash ASC LIMIT 1"
80
81 #define SELECT_IT_MIGRATION_ORDER_1 \
82   "SELECT size,type,prio,anonLevel,expire,hash,value,_ROWID_ FROM gn080 WHERE (expire = ? AND hash < ?) "\
83   " ORDER BY hash DESC LIMIT 1"
84
85 #define SELECT_IT_MIGRATION_ORDER_2 \
86   "SELECT size,type,prio,anonLevel,expire,hash,value,_ROWID_ FROM gn080 WHERE (expire < ? AND expire > %llu) "\
87   " ORDER BY expire DESC, hash DESC LIMIT 1"
88
89 /**
90  * After how many ms "busy" should a DB operation fail for good?
91  * A low value makes sure that we are more responsive to requests
92  * (especially PUTs).  A high value guarantees a higher success
93  * rate (SELECTs in iterate can take several seconds despite LIMIT=1).
94  *
95  * The default value of 250ms should ensure that users do not experience
96  * huge latencies while at the same time allowing operations to succeed
97  * with reasonable probability.
98  */
99 #define BUSY_TIMEOUT_MS 250
100
101
102 /**
103  * Context for all functions in this plugin.
104  */
105 struct Plugin 
106 {
107   /**
108    * Our execution environment.
109    */
110   struct GNUNET_DATASTORE_PluginEnvironment *env;
111
112   /**
113    * Database filename.
114    */
115   char *fn;
116
117   /**
118    * Native SQLite database handle.
119    */
120   sqlite3 *dbh;
121
122   /**
123    * Precompiled SQL for update.
124    */
125   sqlite3_stmt *updPrio;
126
127   /**
128    * Precompiled SQL for insertion.
129    */
130   sqlite3_stmt *insertContent;
131
132   /**
133    * Handle to the statistics service.
134    */
135   struct GNUNET_STATISTICS_Handle *statistics;
136   
137   /**
138    * How much data are we currently storing
139    * in the database?
140    */
141   unsigned long long payload;
142
143   /**
144    * Number of updates that were made to the
145    * payload value since we last synchronized
146    * it with the statistics service.
147    */
148   unsigned int lastSync;
149
150   /**
151    * Should the database be dropped on shutdown?
152    */
153   int drop_on_shutdown;
154 };
155
156
157 /**
158  * @brief Prepare a SQL statement
159  *
160  * @param zSql SQL statement, UTF-8 encoded
161  */
162 static int
163 sq_prepare (sqlite3 * dbh, const char *zSql,
164             sqlite3_stmt ** ppStmt)
165 {
166   char *dummy;
167   return sqlite3_prepare (dbh,
168                           zSql,
169                           strlen (zSql), ppStmt, (const char **) &dummy);
170 }
171
172
173 /**
174  * Create our database indices.
175  */
176 static void
177 create_indices (sqlite3 * dbh)
178 {
179   /* create indices */
180   sqlite3_exec (dbh,
181                 "CREATE INDEX idx_hash ON gn080 (hash)", NULL, NULL, NULL);
182   sqlite3_exec (dbh,
183                 "CREATE INDEX idx_hash_vhash ON gn080 (hash,vhash)", NULL,
184                 NULL, NULL);
185   sqlite3_exec (dbh, "CREATE INDEX idx_prio ON gn080 (prio)", NULL, NULL,
186                 NULL);
187   sqlite3_exec (dbh, "CREATE INDEX idx_expire ON gn080 (expire)", NULL, NULL,
188                 NULL);
189   sqlite3_exec (dbh, "CREATE INDEX idx_comb3 ON gn080 (prio,anonLevel)", NULL,
190                 NULL, NULL);
191   sqlite3_exec (dbh, "CREATE INDEX idx_comb4 ON gn080 (prio,hash,anonLevel)",
192                 NULL, NULL, NULL);
193   sqlite3_exec (dbh, "CREATE INDEX idx_comb7 ON gn080 (expire,hash)", NULL,
194                 NULL, NULL);
195 }
196
197
198
199 #if 1
200 #define CHECK(a) GNUNET_break(a)
201 #define ENULL NULL
202 #else
203 #define ENULL &e
204 #define ENULL_DEFINED 1
205 #define CHECK(a) if (! a) { GNUNET_log(GNUNET_ERROR_TYPE_ERRROR, "%s\n", e); sqlite3_free(e); }
206 #endif
207
208
209
210
211 /**
212  * Initialize the database connections and associated
213  * data structures (create tables and indices
214  * as needed as well).
215  *
216  * @return GNUNET_OK on success
217  */
218 static int
219 database_setup (struct GNUNET_CONFIGURATION_Handle *cfg,
220                 struct Plugin *plugin)
221 {
222   sqlite3_stmt *stmt;
223   char *afsdir;
224 #if ENULL_DEFINED
225   char *e;
226 #endif
227   
228   if (GNUNET_OK != 
229       GNUNET_CONFIGURATION_get_value_filename (cfg,
230                                                "datastore-sqlite",
231                                                "FILENAME",
232                                                &afsdir))
233     {
234       GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR,
235                        "sqlite",
236                        _("Option `%s' in section `%s' missing in configuration!\n"),
237                        "FILENAME",
238                        "datastore-sqlite");
239       return GNUNET_SYSERR;
240     }
241   if (GNUNET_OK != GNUNET_DISK_directory_create_for_file (afsdir))
242     {
243       GNUNET_break (0);
244       GNUNET_free (afsdir);
245       return GNUNET_SYSERR;
246     }
247   plugin->fn = GNUNET_STRINGS_to_utf8 (afsdir, strlen (afsdir),
248 #ifdef ENABLE_NLS
249                                               nl_langinfo (CODESET)
250 #else
251                                               "UTF-8"   /* good luck */
252 #endif
253                                               );
254   GNUNET_free (afsdir);
255   
256   /* Open database and precompile statements */
257   if (sqlite3_open (plugin->fn, &plugin->dbh) != SQLITE_OK)
258     {
259       GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR,
260                        "sqlite",
261                        _("Unable to initialize SQLite: %s.\n"),
262                        sqlite3_errmsg (plugin->dbh));
263       return GNUNET_SYSERR;
264     }
265   CHECK (SQLITE_OK ==
266          sqlite3_exec (plugin->dbh,
267                        "PRAGMA temp_store=MEMORY", NULL, NULL, ENULL));
268   CHECK (SQLITE_OK ==
269          sqlite3_exec (plugin->dbh,
270                        "PRAGMA synchronous=OFF", NULL, NULL, ENULL));
271   CHECK (SQLITE_OK ==
272          sqlite3_exec (plugin->dbh,
273                        "PRAGMA count_changes=OFF", NULL, NULL, ENULL));
274   CHECK (SQLITE_OK ==
275          sqlite3_exec (plugin->dbh, "PRAGMA page_size=4092", NULL, NULL, ENULL));
276
277   CHECK (SQLITE_OK == sqlite3_busy_timeout (plugin->dbh, BUSY_TIMEOUT_MS));
278
279
280   /* We have to do it here, because otherwise precompiling SQL might fail */
281   CHECK (SQLITE_OK ==
282          sq_prepare (plugin->dbh,
283                      "SELECT 1 FROM sqlite_master WHERE tbl_name = 'gn080'",
284                      &stmt));
285   if ( (sqlite3_step (stmt) == SQLITE_DONE) &&
286        (sqlite3_exec (plugin->dbh,
287                       "CREATE TABLE gn080 ("
288                       "  size INTEGER NOT NULL DEFAULT 0,"
289                       "  type INTEGER NOT NULL DEFAULT 0,"
290                       "  prio INTEGER NOT NULL DEFAULT 0,"
291                       "  anonLevel INTEGER NOT NULL DEFAULT 0,"
292                       "  expire INTEGER NOT NULL DEFAULT 0,"
293                       "  hash TEXT NOT NULL DEFAULT '',"
294                       "  vhash TEXT NOT NULL DEFAULT '',"
295                       "  value BLOB NOT NULL DEFAULT '')", NULL, NULL,
296                       NULL) != SQLITE_OK) )
297     {
298       LOG_SQLITE (plugin, NULL,
299                   GNUNET_ERROR_TYPE_ERROR, 
300                   "sqlite3_exec");
301       sqlite3_finalize (stmt);
302       return GNUNET_SYSERR;
303     }
304   sqlite3_finalize (stmt);
305   create_indices (plugin->dbh);
306
307   CHECK (SQLITE_OK ==
308          sq_prepare (plugin->dbh,
309                      "SELECT 1 FROM sqlite_master WHERE tbl_name = 'gn071'",
310                      &stmt));
311   if ( (sqlite3_step (stmt) == SQLITE_DONE) &&
312        (sqlite3_exec (plugin->dbh,
313                       "CREATE TABLE gn071 ("
314                       "  key TEXT NOT NULL DEFAULT '',"
315                       "  value INTEGER NOT NULL DEFAULT 0)", NULL, NULL,
316                       NULL) != SQLITE_OK) )
317     {
318       LOG_SQLITE (plugin, NULL,
319                   GNUNET_ERROR_TYPE_ERROR, "sqlite3_exec");
320       sqlite3_finalize (stmt);
321       return GNUNET_SYSERR;
322     }
323   sqlite3_finalize (stmt);
324
325   if ((sq_prepare (plugin->dbh,
326                    "UPDATE gn080 SET prio = prio + ?, expire = MAX(expire,?) WHERE "
327                    "_ROWID_ = ?",
328                    &plugin->updPrio) != SQLITE_OK) ||
329       (sq_prepare (plugin->dbh,
330                    "INSERT INTO gn080 (size, type, prio, "
331                    "anonLevel, expire, hash, vhash, value) VALUES "
332                    "(?, ?, ?, ?, ?, ?, ?, ?)",
333                    &plugin->insertContent) != SQLITE_OK))
334     {
335       LOG_SQLITE (plugin, NULL,
336                   GNUNET_ERROR_TYPE_ERROR, "precompiling");
337       return GNUNET_SYSERR;
338     }
339   return GNUNET_OK;
340 }
341
342
343 /**
344  * Synchronize our utilization statistics with the 
345  * statistics service.
346  */
347 static void 
348 sync_stats (struct Plugin *plugin)
349 {
350   GNUNET_STATISTICS_set (plugin->statistics,
351                          QUOTA_STAT_NAME,
352                          plugin->payload,
353                          GNUNET_YES);
354   plugin->lastSync = 0;
355 }
356
357
358 /**
359  * Shutdown database connection and associate data
360  * structures.
361  */
362 static void
363 database_shutdown (struct Plugin *plugin)
364 {
365   if (plugin->lastSync > 0)
366     sync_stats (plugin);
367   if (plugin->updPrio != NULL)
368     sqlite3_finalize (plugin->updPrio);
369   if (plugin->insertContent != NULL)
370     sqlite3_finalize (plugin->insertContent);
371   sqlite3_close (plugin->dbh);
372   GNUNET_free_non_null (plugin->fn);
373 }
374
375
376 /**
377  * Get an estimate of how much space the database is
378  * currently using.
379  * @return number of bytes used on disk
380  */
381 static unsigned long long sqlite_plugin_get_size (void *cls)
382 {
383   struct Plugin *plugin = cls;
384   return plugin->payload;
385 }
386
387
388 /**
389  * Delete the database entry with the given
390  * row identifier.
391  */
392 static int
393 delete_by_rowid (struct Plugin* plugin, 
394                  unsigned long long rid)
395 {
396   sqlite3_stmt *stmt;
397
398   if (sq_prepare (plugin->dbh,
399                   "DELETE FROM gn080 WHERE _ROWID_ = ?", &stmt) != SQLITE_OK)
400     {
401       LOG_SQLITE (plugin, NULL,
402                   GNUNET_ERROR_TYPE_ERROR |
403                   GNUNET_ERROR_TYPE_BULK, "sq_prepare");
404       return GNUNET_SYSERR;
405     }
406   sqlite3_bind_int64 (stmt, 1, rid);
407   if (SQLITE_DONE != sqlite3_step (stmt))
408     {
409       LOG_SQLITE (plugin, NULL,
410                   GNUNET_ERROR_TYPE_ERROR |
411                   GNUNET_ERROR_TYPE_BULK, "sqlite3_step");
412       sqlite3_finalize (stmt);
413       return GNUNET_SYSERR;
414     }
415   sqlite3_finalize (stmt);
416   return GNUNET_OK;
417 }
418
419
420 /**
421  * Context for the universal iterator.
422  */
423 struct NextContext;
424
425 /**
426  * Type of a function that will prepare
427  * the next iteration.
428  *
429  * @param cls closure
430  * @param nc the next context; NULL for the last
431  *         call which gives the callback a chance to
432  *         clean up the closure
433  * @return GNUNET_OK on success, GNUNET_NO if there are
434  *        no more values, GNUNET_SYSERR on error
435  */
436 typedef int (*PrepareFunction)(void *cls,
437                                struct NextContext *nc);
438
439
440 /**
441  * Context we keep for the "next request" callback.
442  */
443 struct NextContext
444 {
445   /**
446    * Internal state.
447    */ 
448   struct Plugin *plugin;
449
450   /**
451    * Function to call on the next value.
452    */
453   PluginIterator iter;
454
455   /**
456    * Closure for iter.
457    */
458   void *iter_cls;
459
460   /**
461    * Function to call to prepare the next
462    * iteration.
463    */
464   PrepareFunction prep;
465
466   /**
467    * Closure for prep.
468    */
469   void *prep_cls;
470
471   /**
472    * Statement that the iterator will get the data
473    * from (updated or set by prep).
474    */ 
475   sqlite3_stmt *stmt;
476
477   /**
478    * Row ID of the last result.
479    */
480   unsigned long long last_rowid;
481
482   /**
483    * Expiration time of the last value visited.
484    */
485   struct GNUNET_TIME_Absolute lastExpiration;
486
487   /**
488    * Priority of the last value visited.
489    */ 
490   unsigned int lastPriority; 
491
492   /**
493    * Number of results processed so far.
494    */
495   unsigned int count;
496
497   /**
498    * Set to GNUNET_YES if we must stop now.
499    */
500   int end_it;
501 };
502
503
504 /**
505  * Function invoked on behalf of a "PluginIterator"
506  * asking the database plugin to call the iterator
507  * with the next item.
508  *
509  * @param next_cls whatever argument was given
510  *        to the PluginIterator as "next_cls".
511  * @param end_it set to GNUNET_YES if we
512  *        should terminate the iteration early
513  *        (iterator should be still called once more
514  *         to signal the end of the iteration).
515  */
516 static void 
517 sqlite_next_request (void *next_cls,
518                      int end_it)
519 {
520   static struct GNUNET_TIME_Absolute zero;
521   struct NextContext * nc= next_cls;
522   struct Plugin *plugin;
523   unsigned long long rowid;
524   sqlite3_stmt *stmtd;
525   int ret;
526   unsigned int type;
527   unsigned int size;
528   unsigned int priority;
529   unsigned int anonymity;
530   struct GNUNET_TIME_Absolute expiration;
531   const GNUNET_HashCode *key;
532   const void *data;
533
534   plugin = nc->plugin;
535   sqlite3_reset (nc->stmt);
536   if ( (GNUNET_YES == end_it) ||
537        (GNUNET_YES == nc->end_it) ||
538        (GNUNET_OK != (nc->prep(nc->prep_cls,
539                                nc))) ||
540        (SQLITE_ROW != sqlite3_step (nc->stmt)) )
541     {
542     END:
543       nc->iter (nc->iter_cls, 
544                 NULL, NULL, 0, NULL, 0, 0, 0, 
545                 zero, 0);
546       nc->prep (nc->prep_cls, NULL);
547       GNUNET_free (nc);
548       return;
549     }
550
551   rowid = sqlite3_column_int64 (nc->stmt, 7);
552   nc->last_rowid = rowid;
553   type = sqlite3_column_int (nc->stmt, 1);
554   size = sqlite3_column_bytes (nc->stmt, 6);
555   if (sqlite3_column_bytes (nc->stmt, 5) != sizeof (GNUNET_HashCode))
556     {
557       GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING, 
558                        "sqlite",
559                        _("Invalid data in database.  Trying to fix (by deletion).\n"));
560       if (SQLITE_OK != sqlite3_reset (nc->stmt))
561         LOG_SQLITE (nc->plugin, NULL,
562                     GNUNET_ERROR_TYPE_ERROR |
563                     GNUNET_ERROR_TYPE_BULK, "sqlite3_reset");
564       if (sq_prepare
565           (nc->plugin->dbh,
566            "DELETE FROM gn080 WHERE NOT LENGTH(hash) = ?",
567            &stmtd) != SQLITE_OK)
568         {
569           LOG_SQLITE (nc->plugin, NULL,
570                       GNUNET_ERROR_TYPE_ERROR |
571                       GNUNET_ERROR_TYPE_BULK, 
572                       "sq_prepare");
573           goto END;
574         }
575
576       if (SQLITE_OK != sqlite3_bind_int (stmtd, 1, sizeof (GNUNET_HashCode)))
577         LOG_SQLITE (nc->plugin, NULL,
578                     GNUNET_ERROR_TYPE_ERROR |
579                     GNUNET_ERROR_TYPE_BULK, "sqlite3_bind_int");
580       if (SQLITE_DONE != sqlite3_step (stmtd))
581         LOG_SQLITE (nc->plugin, NULL,
582                     GNUNET_ERROR_TYPE_ERROR |
583                     GNUNET_ERROR_TYPE_BULK, "sqlite3_step");
584       if (SQLITE_OK != sqlite3_finalize (stmtd))
585         LOG_SQLITE (nc->plugin, NULL,
586                     GNUNET_ERROR_TYPE_ERROR |
587                     GNUNET_ERROR_TYPE_BULK, "sqlite3_finalize");
588       goto END;
589     }
590
591   priority = sqlite3_column_int (nc->stmt, 2);
592   nc->lastPriority = priority;
593   anonymity = sqlite3_column_int (nc->stmt, 3);
594   expiration.value = sqlite3_column_int64 (nc->stmt, 4);
595   nc->lastExpiration = expiration;
596   key = sqlite3_column_blob (nc->stmt, 5);
597   data = sqlite3_column_blob (nc->stmt, 6);
598   nc->count++;
599   ret = nc->iter (nc->iter_cls,
600                   nc,
601                   key,
602                   size,
603                   data, 
604                   type,
605                   priority,
606                   anonymity,
607                   expiration,
608                   rowid);
609   if (ret == GNUNET_SYSERR)
610     {
611       nc->end_it = GNUNET_YES;
612       return;
613     }
614   if ( (ret == GNUNET_NO) &&
615        (GNUNET_OK == delete_by_rowid (plugin, rowid)) )
616     {
617       plugin->payload -= (size + GNUNET_DATASTORE_ENTRY_OVERHEAD);
618       plugin->lastSync++; 
619       if (plugin->lastSync >= MAX_STAT_SYNC_LAG)
620         sync_stats (plugin);
621     }
622 }
623
624
625 /**
626  * Store an item in the datastore.
627  *
628  * @param cls closure
629  * @param key key for the item
630  * @param size number of bytes in data
631  * @param data content stored
632  * @param type type of the content
633  * @param priority priority of the content
634  * @param anonymity anonymity-level for the content
635  * @param expiration expiration time for the content
636  * @param msg set to an error message
637  * @return GNUNET_OK on success
638  */
639 static int
640 sqlite_plugin_put (void *cls,
641                    const GNUNET_HashCode * key,
642                    uint32_t size,
643                    const void *data,
644                    uint32_t type,
645                    uint32_t priority,
646                    uint32_t anonymity,
647                    struct GNUNET_TIME_Absolute expiration,
648                    char ** msg)
649 {
650   struct Plugin *plugin = cls;
651   int n;
652   sqlite3_stmt *stmt;
653   GNUNET_HashCode vhash;
654
655 #if DEBUG_SQLITE
656   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
657                    "sqlite",
658                    "Storing in database block with type %u/key `%s'/priority %u/expiration %llu.\n",
659                    type, 
660                    GNUNET_h2s(key),
661                    priority,
662                    GNUNET_TIME_absolute_get_remaining (expiration).value);
663 #endif
664   GNUNET_CRYPTO_hash (data, size, &vhash);
665   stmt = plugin->insertContent;
666   if ((SQLITE_OK != sqlite3_bind_int (stmt, 1, size)) ||
667       (SQLITE_OK != sqlite3_bind_int (stmt, 2, type)) ||
668       (SQLITE_OK != sqlite3_bind_int (stmt, 3, priority)) ||
669       (SQLITE_OK != sqlite3_bind_int (stmt, 4, anonymity)) ||
670       (SQLITE_OK != sqlite3_bind_int64 (stmt, 5, expiration.value)) ||
671       (SQLITE_OK !=
672        sqlite3_bind_blob (stmt, 6, key, sizeof (GNUNET_HashCode),
673                           SQLITE_TRANSIENT)) ||
674       (SQLITE_OK !=
675        sqlite3_bind_blob (stmt, 7, &vhash, sizeof (GNUNET_HashCode),
676                           SQLITE_TRANSIENT))
677       || (SQLITE_OK !=
678           sqlite3_bind_blob (stmt, 8, data, size,
679                              SQLITE_TRANSIENT)))
680     {
681       LOG_SQLITE (plugin,
682                   msg,
683                   GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, "sqlite3_bind_XXXX");
684       if (SQLITE_OK != sqlite3_reset (stmt))
685         LOG_SQLITE (plugin, NULL,
686                     GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, "sqlite3_reset");
687       return GNUNET_SYSERR;
688     }
689   n = sqlite3_step (stmt);
690   if (n != SQLITE_DONE)
691     {
692       if (n == SQLITE_BUSY)
693         {
694           LOG_SQLITE (plugin, msg,
695                       GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, "sqlite3_step");
696           sqlite3_reset (stmt);
697           GNUNET_break (0);
698           return GNUNET_NO;
699         }
700       LOG_SQLITE (plugin, msg,
701                   GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, "sqlite3_step");
702       sqlite3_reset (stmt);
703       return GNUNET_SYSERR;
704     }
705   if (SQLITE_OK != sqlite3_reset (stmt))
706     LOG_SQLITE (plugin, NULL,
707                 GNUNET_ERROR_TYPE_ERROR |
708                 GNUNET_ERROR_TYPE_BULK, "sqlite3_reset");
709   plugin->lastSync++;
710   plugin->payload += size + GNUNET_DATASTORE_ENTRY_OVERHEAD;
711   if (plugin->lastSync >= MAX_STAT_SYNC_LAG)
712     sync_stats (plugin);
713   return GNUNET_OK;
714 }
715
716
717 /**
718  * Update the priority for a particular key in the datastore.  If
719  * the expiration time in value is different than the time found in
720  * the datastore, the higher value should be kept.  For the
721  * anonymity level, the lower value is to be used.  The specified
722  * priority should be added to the existing priority, ignoring the
723  * priority in value.
724  *
725  * Note that it is possible for multiple values to match this put.
726  * In that case, all of the respective values are updated.
727  *
728  * @param uid unique identifier of the datum
729  * @param delta by how much should the priority
730  *     change?  If priority + delta < 0 the
731  *     priority should be set to 0 (never go
732  *     negative).
733  * @param expire new expiration time should be the
734  *     MAX of any existing expiration time and
735  *     this value
736  * @param msg set to an error message
737  * @return GNUNET_OK on success
738  */
739 static int
740 sqlite_plugin_update (void *cls,
741                       uint64_t uid,
742                       int delta, struct GNUNET_TIME_Absolute expire,
743                       char **msg)
744 {
745   struct Plugin *plugin = cls;
746   int n;
747
748   sqlite3_bind_int (plugin->updPrio, 1, delta);
749   sqlite3_bind_int64 (plugin->updPrio, 2, expire.value);
750   sqlite3_bind_int64 (plugin->updPrio, 3, uid);
751   n = sqlite3_step (plugin->updPrio);
752   if (n != SQLITE_OK)
753     LOG_SQLITE (plugin, msg,
754                 GNUNET_ERROR_TYPE_WARNING | GNUNET_ERROR_TYPE_BULK,
755                 "sqlite3_step");
756 #if DEBUG_SQLITE
757   else
758     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
759                      "sqlite",
760                      "Block updated\n");
761 #endif
762   sqlite3_reset (plugin->updPrio);
763
764   if (n == SQLITE_BUSY)
765     return GNUNET_NO;
766   return n == SQLITE_OK ? GNUNET_OK : GNUNET_SYSERR;
767 }
768
769
770 struct IterContext
771 {
772   sqlite3_stmt *stmt_1;
773   sqlite3_stmt *stmt_2;
774   int is_asc;
775   int is_prio;
776   int is_migr;
777   int limit_nonanonymous;
778   uint32_t type;
779   GNUNET_HashCode key;  
780 };
781
782
783 static int
784 iter_next_prepare (void *cls,
785                    struct NextContext *nc)
786 {
787   struct IterContext *ic = cls;
788   struct Plugin *plugin;
789   int ret;
790
791   if (nc == NULL)
792     {
793       sqlite3_finalize (ic->stmt_1);
794       sqlite3_finalize (ic->stmt_2);
795       return GNUNET_SYSERR;
796     }
797   plugin = nc->plugin;
798   if (ic->is_prio)
799     {
800       sqlite3_bind_int (ic->stmt_1, 1, nc->lastPriority);
801       sqlite3_bind_int (ic->stmt_2, 1, nc->lastPriority);
802     }
803   else
804     {
805       sqlite3_bind_int64 (ic->stmt_1, 1, nc->lastExpiration.value);
806       sqlite3_bind_int64 (ic->stmt_2, 1, nc->lastExpiration.value);
807     }
808   sqlite3_bind_blob (ic->stmt_1, 2, 
809                      &ic->key, 
810                      sizeof (GNUNET_HashCode),
811                      SQLITE_TRANSIENT);
812   if (SQLITE_ROW == (ret = sqlite3_step (ic->stmt_1)))
813     {
814       nc->stmt = ic->stmt_1;
815       return GNUNET_OK;
816     }
817   if (ret != SQLITE_DONE)
818     {
819       LOG_SQLITE (plugin, NULL,
820                   GNUNET_ERROR_TYPE_ERROR |
821                   GNUNET_ERROR_TYPE_BULK,
822                   "sqlite3_step");
823       return GNUNET_SYSERR;
824     }
825   if (SQLITE_OK != sqlite3_reset (ic->stmt_1))
826     LOG_SQLITE (plugin, NULL,
827                 GNUNET_ERROR_TYPE_ERROR | 
828                 GNUNET_ERROR_TYPE_BULK, 
829                 "sqlite3_reset");
830   if (SQLITE_ROW == (ret = sqlite3_step (ic->stmt_2))) 
831     {
832       nc->stmt = ic->stmt_2;
833       return GNUNET_OK;
834     }
835   if (ret != SQLITE_DONE)
836     {
837       LOG_SQLITE (plugin, NULL,
838                   GNUNET_ERROR_TYPE_ERROR |
839                   GNUNET_ERROR_TYPE_BULK,
840                   "sqlite3_step");
841       return GNUNET_SYSERR;
842     }
843   if (SQLITE_OK != sqlite3_reset (ic->stmt_2))
844     LOG_SQLITE (plugin, NULL,
845                 GNUNET_ERROR_TYPE_ERROR |
846                 GNUNET_ERROR_TYPE_BULK,
847                 "sqlite3_reset");
848   return GNUNET_NO;
849 }
850
851
852 /**
853  * Call a method for each key in the database and
854  * call the callback method on it.
855  *
856  * @param type entries of which type should be considered?
857  * @param iter function to call on each matching value;
858  *        will be called once with a NULL value at the end
859  * @param iter_cls closure for iter
860  * @return the number of results processed,
861  *         GNUNET_SYSERR on error
862  */
863 static void
864 basic_iter (struct Plugin *plugin,
865             uint32_t type,
866             int is_asc,
867             int is_prio,
868             int is_migr,
869             int limit_nonanonymous,
870             const char *stmt_str_1,
871             const char *stmt_str_2,
872             PluginIterator iter,
873             void *iter_cls)
874 {
875   static struct GNUNET_TIME_Absolute zero;
876   struct NextContext *nc;
877   struct IterContext *ic;
878   sqlite3_stmt *stmt_1;
879   sqlite3_stmt *stmt_2;
880
881   if (sq_prepare (plugin->dbh, stmt_str_1, &stmt_1) != SQLITE_OK)
882     {
883       LOG_SQLITE (plugin, NULL,
884                   GNUNET_ERROR_TYPE_ERROR |
885                   GNUNET_ERROR_TYPE_BULK, "sqlite3_prepare");
886       iter (iter_cls, NULL, NULL, 0, NULL, 0, 0, 0, zero, 0);
887       return;
888     }
889   if (sq_prepare (plugin->dbh, stmt_str_2, &stmt_2) != SQLITE_OK)
890     {
891       LOG_SQLITE (plugin, NULL,
892                   GNUNET_ERROR_TYPE_ERROR |
893                   GNUNET_ERROR_TYPE_BULK, "sqlite3_prepare");
894       sqlite3_finalize (stmt_1);
895       iter (iter_cls, NULL, NULL, 0, NULL, 0, 0, 0, zero, 0);
896       return;
897     }
898   nc = GNUNET_malloc (sizeof(struct NextContext) + 
899                       sizeof(struct IterContext));
900   nc->plugin = plugin;
901   nc->iter = iter;
902   nc->iter_cls = iter_cls;
903   nc->stmt = NULL;
904   ic = (struct IterContext*) &nc[1];
905   ic->stmt_1 = stmt_1;
906   ic->stmt_2 = stmt_2;
907   ic->type = type;
908   ic->is_asc = is_asc;
909   ic->is_prio = is_prio;
910   ic->is_migr = is_migr;
911   ic->limit_nonanonymous = limit_nonanonymous;
912   nc->prep = &iter_next_prepare;
913   nc->prep_cls = ic;
914   if (is_asc)
915     {
916       nc->lastPriority = 0;
917       nc->lastExpiration.value = 0;
918       memset (&ic->key, 0, sizeof (GNUNET_HashCode));
919     }
920   else
921     {
922       nc->lastPriority = 0x7FFFFFFF;
923       nc->lastExpiration.value = 0x7FFFFFFFFFFFFFFFLL;
924       memset (&ic->key, 255, sizeof (GNUNET_HashCode));
925     }
926   sqlite_next_request (nc, GNUNET_NO);
927 }
928
929
930 /**
931  * Select a subset of the items in the datastore and call
932  * the given iterator for each of them.
933  *
934  * @param type entries of which type should be considered?
935  *        Use 0 for any type.
936  * @param iter function to call on each matching value;
937  *        will be called once with a NULL value at the end
938  * @param iter_cls closure for iter
939  */
940 static void
941 sqlite_plugin_iter_low_priority (void *cls,
942                                  uint32_t type,
943                                  PluginIterator iter,
944                                  void *iter_cls)
945 {
946   basic_iter (cls,
947               type, 
948               GNUNET_YES, GNUNET_YES, 
949               GNUNET_NO, GNUNET_NO,
950               SELECT_IT_LOW_PRIORITY_1,
951               SELECT_IT_LOW_PRIORITY_2, 
952               iter, iter_cls);
953 }
954
955
956 /**
957  * Select a subset of the items in the datastore and call
958  * the given iterator for each of them.
959  *
960  * @param type entries of which type should be considered?
961  *        Use 0 for any type.
962  * @param iter function to call on each matching value;
963  *        will be called once with a NULL value at the end
964  * @param iter_cls closure for iter
965  */
966 static void
967 sqlite_plugin_iter_zero_anonymity (void *cls,
968                                    uint32_t type,
969                                    PluginIterator iter,
970                                    void *iter_cls)
971 {
972   basic_iter (cls,
973               type, 
974               GNUNET_NO, GNUNET_YES, 
975               GNUNET_NO, GNUNET_YES,
976               SELECT_IT_NON_ANONYMOUS_1,
977               SELECT_IT_NON_ANONYMOUS_2, 
978               iter, iter_cls);
979 }
980
981
982
983 /**
984  * Select a subset of the items in the datastore and call
985  * the given iterator for each of them.
986  *
987  * @param type entries of which type should be considered?
988  *        Use 0 for any type.
989  * @param iter function to call on each matching value;
990  *        will be called once with a NULL value at the end
991  * @param iter_cls closure for iter
992  */
993 static void
994 sqlite_plugin_iter_ascending_expiration (void *cls,
995                                          uint32_t type,
996                                          PluginIterator iter,
997                                          void *iter_cls)
998 {
999   struct GNUNET_TIME_Absolute now;
1000   char *q1;
1001   char *q2;
1002
1003   now = GNUNET_TIME_absolute_get ();
1004   GNUNET_asprintf (&q1, SELECT_IT_EXPIRATION_TIME_1,
1005                    now.value);
1006   GNUNET_asprintf (&q2, SELECT_IT_EXPIRATION_TIME_2,
1007                    now.value);
1008   basic_iter (cls,
1009               type, 
1010               GNUNET_YES, GNUNET_NO, 
1011               GNUNET_NO, GNUNET_NO,
1012               q1, q2,
1013               iter, iter_cls);
1014   GNUNET_free (q1);
1015   GNUNET_free (q2);
1016 }
1017
1018
1019 /**
1020  * Select a subset of the items in the datastore and call
1021  * the given iterator for each of them.
1022  *
1023  * @param type entries of which type should be considered?
1024  *        Use 0 for any type.
1025  * @param iter function to call on each matching value;
1026  *        will be called once with a NULL value at the end
1027  * @param iter_cls closure for iter
1028  */
1029 static void
1030 sqlite_plugin_iter_migration_order (void *cls,
1031                                     uint32_t type,
1032                                     PluginIterator iter,
1033                                     void *iter_cls)
1034 {
1035   struct GNUNET_TIME_Absolute now;
1036   char *q;
1037
1038   now = GNUNET_TIME_absolute_get ();
1039   GNUNET_asprintf (&q, SELECT_IT_MIGRATION_ORDER_2,
1040                    now.value);
1041   basic_iter (cls,
1042               type, 
1043               GNUNET_NO, GNUNET_NO, 
1044               GNUNET_YES, GNUNET_NO,
1045               SELECT_IT_MIGRATION_ORDER_1,
1046               q,
1047               iter, iter_cls);
1048   GNUNET_free (q);
1049 }
1050
1051
1052
1053 /**
1054  * Select a subset of the items in the datastore and call
1055  * the given iterator for each of them.
1056  *
1057  * @param type entries of which type should be considered?
1058  *        Use 0 for any type.
1059  * @param iter function to call on each matching value;
1060  *        will be called once with a NULL value at the end
1061  * @param iter_cls closure for iter
1062  */
1063 static void
1064 sqlite_plugin_iter_all_now (void *cls,
1065                             uint32_t type,
1066                             PluginIterator iter,
1067                             void *iter_cls)
1068 {
1069   static struct GNUNET_TIME_Absolute zero;
1070   iter (iter_cls, NULL, NULL, 0, NULL, 0, 0, 0, zero, 0);
1071 }
1072
1073
1074 struct GetNextContext
1075 {
1076   int total;
1077   int off;
1078   int have_vhash;
1079   unsigned int type;
1080   sqlite3_stmt *stmt;
1081   GNUNET_HashCode key;
1082   GNUNET_HashCode vhash;
1083 };
1084
1085
1086 static int
1087 get_next_prepare (void *cls,
1088                   struct NextContext *nc)
1089 {
1090   struct GetNextContext *gnc = cls;
1091   int sqoff;
1092   int ret;
1093   int limit_off;
1094
1095   if (nc == NULL)
1096     {
1097       sqlite3_finalize (gnc->stmt);
1098       return GNUNET_SYSERR;
1099     }
1100   if (nc->count == gnc->total)
1101     return GNUNET_NO;
1102   if (nc->count + gnc->off == gnc->total)
1103     nc->last_rowid = 0;
1104   if (nc->count == 0)
1105     limit_off = gnc->off;
1106   else
1107     limit_off = 0;
1108   sqoff = 1;
1109   ret = sqlite3_bind_blob (nc->stmt,
1110                            sqoff++,
1111                            &gnc->key, 
1112                            sizeof (GNUNET_HashCode),
1113                            SQLITE_TRANSIENT);
1114   if ((gnc->have_vhash) && (ret == SQLITE_OK))
1115     ret = sqlite3_bind_blob (nc->stmt,
1116                              sqoff++,
1117                              &gnc->vhash,
1118                              sizeof (GNUNET_HashCode), SQLITE_TRANSIENT);
1119   if ((gnc->type != 0) && (ret == SQLITE_OK))
1120     ret = sqlite3_bind_int (nc->stmt, sqoff++, gnc->type);
1121   if (ret == SQLITE_OK)
1122     ret = sqlite3_bind_int64 (nc->stmt, sqoff++, nc->last_rowid + 1);
1123   if (ret == SQLITE_OK)
1124     ret = sqlite3_bind_int (nc->stmt, sqoff++, limit_off);
1125   if (ret != SQLITE_OK)
1126     return GNUNET_SYSERR;
1127   if (SQLITE_ROW != sqlite3_step (nc->stmt))
1128     return GNUNET_NO;
1129   return GNUNET_OK;
1130 }
1131
1132
1133 /**
1134  * Iterate over the results for a particular key
1135  * in the datastore.
1136  *
1137  * @param cls closure
1138  * @param key maybe NULL (to match all entries)
1139  * @param vhash hash of the value, maybe NULL (to
1140  *        match all values that have the right key).
1141  *        Note that for DBlocks there is no difference
1142  *        betwen key and vhash, but for other blocks
1143  *        there may be!
1144  * @param type entries of which type are relevant?
1145  *     Use 0 for any type.
1146  * @param iter function to call on each matching value;
1147  *        will be called once with a NULL value at the end
1148  * @param iter_cls closure for iter
1149  */
1150 static void
1151 sqlite_plugin_get (void *cls,
1152                    const GNUNET_HashCode * key,
1153                    const GNUNET_HashCode * vhash,
1154                    uint32_t type,
1155                    PluginIterator iter, void *iter_cls)
1156 {
1157   static struct GNUNET_TIME_Absolute zero;
1158   struct Plugin *plugin = cls;
1159   struct GetNextContext *gpc;
1160   struct NextContext *nc;
1161   int ret;
1162   int total;
1163   sqlite3_stmt *stmt;
1164   char scratch[256];
1165   int sqoff;
1166
1167   GNUNET_assert (iter != NULL);
1168   if (key == NULL)
1169     {
1170       sqlite_plugin_iter_low_priority (cls, type, iter, iter_cls);
1171       return;
1172     }
1173   GNUNET_snprintf (scratch, 256,
1174                    "SELECT count(*) FROM gn080 WHERE hash=:1%s%s",
1175                    vhash == NULL ? "" : " AND vhash=:2",
1176                    type == 0 ? "" : (vhash ==
1177                                      NULL) ? " AND type=:2" : " AND type=:3");
1178   if (sq_prepare (plugin->dbh, scratch, &stmt) != SQLITE_OK)
1179     {
1180       LOG_SQLITE (plugin, NULL,
1181                   GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, "sqlite_prepare");
1182       iter (iter_cls, NULL, NULL, 0, NULL, 0, 0, 0, zero, 0);
1183       return;
1184     }
1185   sqoff = 1;
1186   ret = sqlite3_bind_blob (stmt,
1187                            sqoff++,
1188                            key, sizeof (GNUNET_HashCode), SQLITE_TRANSIENT);
1189   if ((vhash != NULL) && (ret == SQLITE_OK))
1190     ret = sqlite3_bind_blob (stmt,
1191                              sqoff++,
1192                              vhash,
1193                              sizeof (GNUNET_HashCode), SQLITE_TRANSIENT);
1194   if ((type != 0) && (ret == SQLITE_OK))
1195     ret = sqlite3_bind_int (stmt, sqoff++, type);
1196   if (SQLITE_OK != ret)
1197     {
1198       LOG_SQLITE (plugin, NULL,
1199                   GNUNET_ERROR_TYPE_ERROR, "sqlite_bind");
1200       sqlite3_reset (stmt);
1201       sqlite3_finalize (stmt);
1202       iter (iter_cls, NULL, NULL, 0, NULL, 0, 0, 0, zero, 0);
1203       return;
1204     }
1205   ret = sqlite3_step (stmt);
1206   if (ret != SQLITE_ROW)
1207     {
1208       LOG_SQLITE (plugin, NULL,
1209                   GNUNET_ERROR_TYPE_ERROR| GNUNET_ERROR_TYPE_BULK, 
1210                   "sqlite_step");
1211       sqlite3_reset (stmt);
1212       sqlite3_finalize (stmt);
1213       iter (iter_cls, NULL, NULL, 0, NULL, 0, 0, 0, zero, 0);
1214       return;
1215     }
1216   total = sqlite3_column_int (stmt, 0);
1217   sqlite3_reset (stmt);
1218   sqlite3_finalize (stmt);
1219   if (0 == total)
1220     {
1221       iter (iter_cls, NULL, NULL, 0, NULL, 0, 0, 0, zero, 0);
1222       return;
1223     }
1224
1225   GNUNET_snprintf (scratch, 256,
1226                    "SELECT size, type, prio, anonLevel, expire, hash, value, _ROWID_ "
1227                    "FROM gn080 WHERE hash=:1%s%s AND _ROWID_ >= :%d "
1228                    "ORDER BY _ROWID_ ASC LIMIT 1 OFFSET :d",
1229                    vhash == NULL ? "" : " AND vhash=:2",
1230                    type == 0 ? "" : (vhash ==
1231                                      NULL) ? " AND type=:2" : " AND type=:3",
1232                    sqoff, sqoff + 1);
1233   if (sq_prepare (plugin->dbh, scratch, &stmt) != SQLITE_OK)
1234     {
1235       LOG_SQLITE (plugin, NULL,
1236                   GNUNET_ERROR_TYPE_ERROR |
1237                   GNUNET_ERROR_TYPE_BULK, "sqlite_prepare");
1238       iter (iter_cls, NULL, NULL, 0, NULL, 0, 0, 0, zero, 0);
1239       return;
1240     }
1241   nc = GNUNET_malloc (sizeof(struct NextContext) + 
1242                       sizeof(struct GetNextContext));
1243   nc->plugin = plugin;
1244   nc->iter = iter;
1245   nc->iter_cls = iter_cls;
1246   nc->stmt = stmt;
1247   gpc = (struct GetNextContext*) &nc[1];
1248   gpc->total = total;
1249   gpc->type = type;
1250   gpc->key = *key;
1251   gpc->stmt = stmt; /* alias used for freeing at the end! */
1252   if (NULL != vhash)
1253     {
1254       gpc->have_vhash = GNUNET_YES;
1255       gpc->vhash = *vhash;
1256     }
1257   gpc->off = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, total);
1258   nc->prep = &get_next_prepare;
1259   nc->prep_cls = gpc;
1260   sqlite_next_request (nc, GNUNET_NO);
1261 }
1262
1263
1264 /**
1265  * Drop database.
1266  */
1267 static void 
1268 sqlite_plugin_drop (void *cls)
1269 {
1270   struct Plugin *plugin = cls;
1271   plugin->drop_on_shutdown = GNUNET_YES;
1272 }
1273
1274
1275 /**
1276  * Callback function to process statistic values.
1277  *
1278  * @param cls closure
1279  * @param subsystem name of subsystem that created the statistic
1280  * @param name the name of the datum
1281  * @param value the current value
1282  * @param is_persistent GNUNET_YES if the value is persistent, GNUNET_NO if not
1283  * @return GNUNET_OK to continue, GNUNET_SYSERR to abort iteration
1284  */
1285 static int
1286 process_stat_in (void *cls,
1287                  const char *subsystem,
1288                  const char *name,
1289                  unsigned long long value,
1290                  int is_persistent)
1291 {
1292   struct Plugin *plugin = cls;
1293   plugin->payload += value;
1294   return GNUNET_OK;
1295 }
1296                                          
1297
1298 /**
1299  * Entry point for the plugin.
1300  */
1301 void *
1302 libgnunet_plugin_datastore_sqlite_init (void *cls)
1303 {
1304   static struct Plugin plugin;
1305   struct GNUNET_DATASTORE_PluginEnvironment *env = cls;
1306   struct GNUNET_DATASTORE_PluginFunctions *api;
1307
1308   if (plugin.env != NULL)
1309     return NULL; /* can only initialize once! */
1310   memset (&plugin, 0, sizeof(struct Plugin));
1311   plugin.env = env;
1312   plugin.statistics = GNUNET_STATISTICS_create (env->sched,
1313                                                 "sqlite",
1314                                                 env->cfg);
1315   GNUNET_STATISTICS_get (plugin.statistics,
1316                          "sqlite",
1317                          QUOTA_STAT_NAME,
1318                          GNUNET_TIME_UNIT_MINUTES,
1319                          NULL,
1320                          &process_stat_in,
1321                          &plugin);
1322   if (GNUNET_OK !=
1323       database_setup (env->cfg, &plugin))
1324     {
1325       database_shutdown (&plugin);
1326       return NULL;
1327     }
1328   api = GNUNET_malloc (sizeof (struct GNUNET_DATASTORE_PluginFunctions));
1329   api->cls = &plugin;
1330   api->get_size = &sqlite_plugin_get_size;
1331   api->put = &sqlite_plugin_put;
1332   api->next_request = &sqlite_next_request;
1333   api->get = &sqlite_plugin_get;
1334   api->update = &sqlite_plugin_update;
1335   api->iter_low_priority = &sqlite_plugin_iter_low_priority;
1336   api->iter_zero_anonymity = &sqlite_plugin_iter_zero_anonymity;
1337   api->iter_ascending_expiration = &sqlite_plugin_iter_ascending_expiration;
1338   api->iter_migration_order = &sqlite_plugin_iter_migration_order;
1339   api->iter_all_now = &sqlite_plugin_iter_all_now;
1340   api->drop = &sqlite_plugin_drop;
1341   GNUNET_log_from (GNUNET_ERROR_TYPE_INFO,
1342                    "sqlite", _("Sqlite database running\n"));
1343   return api;
1344 }
1345
1346
1347 /**
1348  * Exit point from the plugin.
1349  */
1350 void *
1351 libgnunet_plugin_datastore_sqlite_done (void *cls)
1352 {
1353   char *fn;
1354   struct GNUNET_DATASTORE_PluginFunctions *api = cls;
1355   struct Plugin *plugin = api->cls;
1356
1357   fn = NULL;
1358   if (plugin->drop_on_shutdown)
1359     fn = GNUNET_strdup (plugin->fn);
1360   database_shutdown (plugin);
1361   plugin->env = NULL; 
1362   plugin->payload = 0;
1363   GNUNET_free (api);
1364   if (fn != NULL)
1365     {
1366       if (0 != UNLINK(fn))
1367         GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING,
1368                                   "unlink",
1369                                   fn);
1370       GNUNET_free (fn);
1371     }
1372   return NULL;
1373 }
1374
1375 /* end of plugin_datastore_sqlite.c */