debugging
[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 = nc->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   sqlite3_reset (nc->stmt);
535   if ( (GNUNET_YES == end_it) ||
536        (GNUNET_YES == nc->end_it) ||
537        (GNUNET_OK != (nc->prep(nc->prep_cls,
538                                nc))) ||
539        (SQLITE_ROW != sqlite3_step (nc->stmt)) )
540     {
541     END:
542       nc->iter (nc->iter_cls, 
543                 NULL, NULL, 0, NULL, 0, 0, 0, 
544                 zero, 0);
545       nc->prep (nc->prep_cls, NULL);
546       GNUNET_free (nc);
547       return;
548     }
549
550   rowid = sqlite3_column_int64 (nc->stmt, 7);
551   nc->last_rowid = rowid;
552   type = sqlite3_column_int (nc->stmt, 1);
553   size = sqlite3_column_bytes (nc->stmt, 6);
554   if (sqlite3_column_bytes (nc->stmt, 5) != sizeof (GNUNET_HashCode))
555     {
556       GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING, 
557                        "sqlite",
558                        _("Invalid data in database.  Trying to fix (by deletion).\n"));
559       if (SQLITE_OK != sqlite3_reset (nc->stmt))
560         LOG_SQLITE (nc->plugin, NULL,
561                     GNUNET_ERROR_TYPE_ERROR |
562                     GNUNET_ERROR_TYPE_BULK, "sqlite3_reset");
563       if (sq_prepare
564           (nc->plugin->dbh,
565            "DELETE FROM gn080 WHERE NOT LENGTH(hash) = ?",
566            &stmtd) != SQLITE_OK)
567         {
568           LOG_SQLITE (nc->plugin, NULL,
569                       GNUNET_ERROR_TYPE_ERROR |
570                       GNUNET_ERROR_TYPE_BULK, 
571                       "sq_prepare");
572           goto END;
573         }
574
575       if (SQLITE_OK != sqlite3_bind_int (stmtd, 1, sizeof (GNUNET_HashCode)))
576         LOG_SQLITE (nc->plugin, NULL,
577                     GNUNET_ERROR_TYPE_ERROR |
578                     GNUNET_ERROR_TYPE_BULK, "sqlite3_bind_int");
579       if (SQLITE_DONE != sqlite3_step (stmtd))
580         LOG_SQLITE (nc->plugin, NULL,
581                     GNUNET_ERROR_TYPE_ERROR |
582                     GNUNET_ERROR_TYPE_BULK, "sqlite3_step");
583       if (SQLITE_OK != sqlite3_finalize (stmtd))
584         LOG_SQLITE (nc->plugin, NULL,
585                     GNUNET_ERROR_TYPE_ERROR |
586                     GNUNET_ERROR_TYPE_BULK, "sqlite3_finalize");
587       goto END;
588     }
589
590   priority = sqlite3_column_int (nc->stmt, 2);
591   nc->lastPriority = priority;
592   anonymity = sqlite3_column_int (nc->stmt, 3);
593   expiration.value = sqlite3_column_int64 (nc->stmt, 4);
594   nc->lastExpiration = expiration;
595   key = sqlite3_column_blob (nc->stmt, 5);
596   data = sqlite3_column_blob (nc->stmt, 6);
597   nc->count++;
598   ret = nc->iter (nc->iter_cls,
599                   nc,
600                   key,
601                   size,
602                   data, 
603                   type,
604                   priority,
605                   anonymity,
606                   expiration,
607                   rowid);
608   if (ret == GNUNET_SYSERR)
609     {
610       nc->end_it = GNUNET_YES;
611       return;
612     }
613   if ( (ret == GNUNET_NO) &&
614        (GNUNET_OK == delete_by_rowid (plugin, rowid)) )
615     {
616       plugin->payload -= (size + GNUNET_DATASTORE_ENTRY_OVERHEAD);
617       plugin->lastSync++; 
618       if (plugin->lastSync >= MAX_STAT_SYNC_LAG)
619         sync_stats (plugin);
620     }
621 }
622
623
624 /**
625  * Store an item in the datastore.
626  *
627  * @param cls closure
628  * @param key key for the item
629  * @param size number of bytes in data
630  * @param data content stored
631  * @param type type of the content
632  * @param priority priority of the content
633  * @param anonymity anonymity-level for the content
634  * @param expiration expiration time for the content
635  * @param msg set to an error message
636  * @return GNUNET_OK on success
637  */
638 static int
639 sqlite_plugin_put (void *cls,
640                    const GNUNET_HashCode * key,
641                    uint32_t size,
642                    const void *data,
643                    uint32_t type,
644                    uint32_t priority,
645                    uint32_t anonymity,
646                    struct GNUNET_TIME_Absolute expiration,
647                    char ** msg)
648 {
649   struct Plugin *plugin = cls;
650   int n;
651   sqlite3_stmt *stmt;
652   GNUNET_HashCode vhash;
653
654 #if DEBUG_SQLITE
655   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
656                    "sqlite",
657                    "Storing in database block with type %u/key `%s'/priority %u/expiration %llu.\n",
658                    type, 
659                    GNUNET_h2s(key),
660                    priority,
661                    GNUNET_TIME_absolute_get_remaining (expiration).value);
662 #endif
663   GNUNET_CRYPTO_hash (data, size, &vhash);
664   stmt = plugin->insertContent;
665   if ((SQLITE_OK != sqlite3_bind_int (stmt, 1, size)) ||
666       (SQLITE_OK != sqlite3_bind_int (stmt, 2, type)) ||
667       (SQLITE_OK != sqlite3_bind_int (stmt, 3, priority)) ||
668       (SQLITE_OK != sqlite3_bind_int (stmt, 4, anonymity)) ||
669       (SQLITE_OK != sqlite3_bind_int64 (stmt, 5, expiration.value)) ||
670       (SQLITE_OK !=
671        sqlite3_bind_blob (stmt, 6, key, sizeof (GNUNET_HashCode),
672                           SQLITE_TRANSIENT)) ||
673       (SQLITE_OK !=
674        sqlite3_bind_blob (stmt, 7, &vhash, sizeof (GNUNET_HashCode),
675                           SQLITE_TRANSIENT))
676       || (SQLITE_OK !=
677           sqlite3_bind_blob (stmt, 8, data, size,
678                              SQLITE_TRANSIENT)))
679     {
680       LOG_SQLITE (plugin,
681                   msg,
682                   GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, "sqlite3_bind_XXXX");
683       if (SQLITE_OK != sqlite3_reset (stmt))
684         LOG_SQLITE (plugin, NULL,
685                     GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, "sqlite3_reset");
686       return GNUNET_SYSERR;
687     }
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 #if DEBUG_SQLITE
714   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
715                    "sqlite",
716                    "done writing content\n");
717 #endif
718   return GNUNET_OK;
719 }
720
721
722 /**
723  * Update the priority for a particular key in the datastore.  If
724  * the expiration time in value is different than the time found in
725  * the datastore, the higher value should be kept.  For the
726  * anonymity level, the lower value is to be used.  The specified
727  * priority should be added to the existing priority, ignoring the
728  * priority in value.
729  *
730  * Note that it is possible for multiple values to match this put.
731  * In that case, all of the respective values are updated.
732  *
733  * @param uid unique identifier of the datum
734  * @param delta by how much should the priority
735  *     change?  If priority + delta < 0 the
736  *     priority should be set to 0 (never go
737  *     negative).
738  * @param expire new expiration time should be the
739  *     MAX of any existing expiration time and
740  *     this value
741  * @param msg set to an error message
742  * @return GNUNET_OK on success
743  */
744 static int
745 sqlite_plugin_update (void *cls,
746                       uint64_t uid,
747                       int delta, struct GNUNET_TIME_Absolute expire,
748                       char **msg)
749 {
750   struct Plugin *plugin = cls;
751   int n;
752
753   sqlite3_bind_int (plugin->updPrio, 1, delta);
754   sqlite3_bind_int64 (plugin->updPrio, 2, expire.value);
755   sqlite3_bind_int64 (plugin->updPrio, 3, uid);
756   n = sqlite3_step (plugin->updPrio);
757   if (n != SQLITE_OK)
758     LOG_SQLITE (plugin, msg,
759                 GNUNET_ERROR_TYPE_WARNING | GNUNET_ERROR_TYPE_BULK,
760                 "sqlite3_step");
761 #if DEBUG_SQLITE
762   else
763     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
764                      "sqlite",
765                      "Block updated\n");
766 #endif
767   sqlite3_reset (plugin->updPrio);
768
769   if (n == SQLITE_BUSY)
770     return GNUNET_NO;
771   return n == SQLITE_OK ? GNUNET_OK : GNUNET_SYSERR;
772 }
773
774
775 struct IterContext
776 {
777   sqlite3_stmt *stmt_1;
778   sqlite3_stmt *stmt_2;
779   int is_asc;
780   int is_prio;
781   int is_migr;
782   int limit_nonanonymous;
783   uint32_t type;
784   GNUNET_HashCode key;  
785 };
786
787
788 static int
789 iter_next_prepare (void *cls,
790                    struct NextContext *nc)
791 {
792   struct IterContext *ic = cls;
793   struct Plugin *plugin = nc->plugin;
794   int ret;
795
796   if (nc == NULL)
797     {
798       sqlite3_finalize (ic->stmt_1);
799       sqlite3_finalize (ic->stmt_2);
800       return GNUNET_SYSERR;
801     }
802   if (ic->is_prio)
803     {
804       sqlite3_bind_int (ic->stmt_1, 1, nc->lastPriority);
805       sqlite3_bind_int (ic->stmt_2, 1, nc->lastPriority);
806     }
807   else
808     {
809       sqlite3_bind_int64 (ic->stmt_1, 1, nc->lastExpiration.value);
810       sqlite3_bind_int64 (ic->stmt_2, 1, nc->lastExpiration.value);
811     }
812   sqlite3_bind_blob (ic->stmt_1, 2, 
813                      &ic->key, 
814                      sizeof (GNUNET_HashCode),
815                      SQLITE_TRANSIENT);
816   if (SQLITE_ROW == (ret = sqlite3_step (ic->stmt_1)))
817     {
818       nc->stmt = ic->stmt_1;
819       return GNUNET_OK;
820     }
821   if (ret != SQLITE_DONE)
822     {
823       LOG_SQLITE (plugin, NULL,
824                   GNUNET_ERROR_TYPE_ERROR |
825                   GNUNET_ERROR_TYPE_BULK,
826                   "sqlite3_step");
827       return GNUNET_SYSERR;
828     }
829   if (SQLITE_OK != sqlite3_reset (ic->stmt_1))
830     LOG_SQLITE (plugin, NULL,
831                 GNUNET_ERROR_TYPE_ERROR | 
832                 GNUNET_ERROR_TYPE_BULK, 
833                 "sqlite3_reset");
834   if (SQLITE_ROW == (ret = sqlite3_step (ic->stmt_2))) 
835     {
836       nc->stmt = ic->stmt_2;
837       return GNUNET_OK;
838     }
839   if (ret != SQLITE_DONE)
840     {
841       LOG_SQLITE (plugin, NULL,
842                   GNUNET_ERROR_TYPE_ERROR |
843                   GNUNET_ERROR_TYPE_BULK,
844                   "sqlite3_step");
845       return GNUNET_SYSERR;
846     }
847   if (SQLITE_OK != sqlite3_reset (ic->stmt_2))
848     LOG_SQLITE (plugin, NULL,
849                 GNUNET_ERROR_TYPE_ERROR |
850                 GNUNET_ERROR_TYPE_BULK,
851                 "sqlite3_reset");
852   return GNUNET_NO;
853 }
854
855
856 /**
857  * Call a method for each key in the database and
858  * call the callback method on it.
859  *
860  * @param type entries of which type should be considered?
861  * @param iter function to call on each matching value;
862  *        will be called once with a NULL value at the end
863  * @param iter_cls closure for iter
864  * @return the number of results processed,
865  *         GNUNET_SYSERR on error
866  */
867 static void
868 basic_iter (struct Plugin *plugin,
869             uint32_t type,
870             int is_asc,
871             int is_prio,
872             int is_migr,
873             int limit_nonanonymous,
874             const char *stmt_str_1,
875             const char *stmt_str_2,
876             PluginIterator iter,
877             void *iter_cls)
878 {
879   static struct GNUNET_TIME_Absolute zero;
880   struct NextContext *nc;
881   struct IterContext *ic;
882   sqlite3_stmt *stmt_1;
883   sqlite3_stmt *stmt_2;
884
885   if (sq_prepare (plugin->dbh, stmt_str_1, &stmt_1) != SQLITE_OK)
886     {
887       LOG_SQLITE (plugin, NULL,
888                   GNUNET_ERROR_TYPE_ERROR |
889                   GNUNET_ERROR_TYPE_BULK, "sqlite3_prepare");
890       iter (iter_cls, NULL, NULL, 0, NULL, 0, 0, 0, zero, 0);
891       return;
892     }
893   if (sq_prepare (plugin->dbh, stmt_str_2, &stmt_2) != SQLITE_OK)
894     {
895       LOG_SQLITE (plugin, NULL,
896                   GNUNET_ERROR_TYPE_ERROR |
897                   GNUNET_ERROR_TYPE_BULK, "sqlite3_prepare");
898       sqlite3_finalize (stmt_1);
899       iter (iter_cls, NULL, NULL, 0, NULL, 0, 0, 0, zero, 0);
900       return;
901     }
902   nc = GNUNET_malloc (sizeof(struct NextContext) + 
903                       sizeof(struct IterContext));
904   nc->plugin = plugin;
905   nc->iter = iter;
906   nc->iter_cls = iter_cls;
907   nc->stmt = NULL;
908   ic = (struct IterContext*) &nc[1];
909   ic->stmt_1 = stmt_1;
910   ic->stmt_2 = stmt_2;
911   ic->type = type;
912   ic->is_asc = is_asc;
913   ic->is_prio = is_prio;
914   ic->is_migr = is_migr;
915   ic->limit_nonanonymous = limit_nonanonymous;
916   nc->prep = &iter_next_prepare;
917   nc->prep_cls = ic;
918   if (is_asc)
919     {
920       nc->lastPriority = 0;
921       nc->lastExpiration.value = 0;
922       memset (&ic->key, 0, sizeof (GNUNET_HashCode));
923     }
924   else
925     {
926       nc->lastPriority = 0x7FFFFFFF;
927       nc->lastExpiration.value = 0x7FFFFFFFFFFFFFFFLL;
928       memset (&ic->key, 255, sizeof (GNUNET_HashCode));
929     }
930   sqlite_next_request (nc, GNUNET_NO);
931 }
932
933
934 /**
935  * Select a subset of the items in the datastore and call
936  * the given iterator for each of them.
937  *
938  * @param type entries of which type should be considered?
939  *        Use 0 for any type.
940  * @param iter function to call on each matching value;
941  *        will be called once with a NULL value at the end
942  * @param iter_cls closure for iter
943  */
944 static void
945 sqlite_plugin_iter_low_priority (void *cls,
946                                  uint32_t type,
947                                  PluginIterator iter,
948                                  void *iter_cls)
949 {
950   basic_iter (cls,
951               type, 
952               GNUNET_YES, GNUNET_YES, 
953               GNUNET_NO, GNUNET_NO,
954               SELECT_IT_LOW_PRIORITY_1,
955               SELECT_IT_LOW_PRIORITY_2, 
956               iter, iter_cls);
957 }
958
959
960 /**
961  * Select a subset of the items in the datastore and call
962  * the given iterator for each of them.
963  *
964  * @param type entries of which type should be considered?
965  *        Use 0 for any type.
966  * @param iter function to call on each matching value;
967  *        will be called once with a NULL value at the end
968  * @param iter_cls closure for iter
969  */
970 static void
971 sqlite_plugin_iter_zero_anonymity (void *cls,
972                                    uint32_t type,
973                                    PluginIterator iter,
974                                    void *iter_cls)
975 {
976   basic_iter (cls,
977               type, 
978               GNUNET_NO, GNUNET_YES, 
979               GNUNET_NO, GNUNET_YES,
980               SELECT_IT_NON_ANONYMOUS_1,
981               SELECT_IT_NON_ANONYMOUS_2, 
982               iter, iter_cls);
983 }
984
985
986
987 /**
988  * Select a subset of the items in the datastore and call
989  * the given iterator for each of them.
990  *
991  * @param type entries of which type should be considered?
992  *        Use 0 for any type.
993  * @param iter function to call on each matching value;
994  *        will be called once with a NULL value at the end
995  * @param iter_cls closure for iter
996  */
997 static void
998 sqlite_plugin_iter_ascending_expiration (void *cls,
999                                          uint32_t type,
1000                                          PluginIterator iter,
1001                                          void *iter_cls)
1002 {
1003   struct GNUNET_TIME_Absolute now;
1004   char *q1;
1005   char *q2;
1006
1007   now = GNUNET_TIME_absolute_get ();
1008   GNUNET_asprintf (&q1, SELECT_IT_EXPIRATION_TIME_1,
1009                    now.value);
1010   GNUNET_asprintf (&q2, SELECT_IT_EXPIRATION_TIME_2,
1011                    now.value);
1012   basic_iter (cls,
1013               type, 
1014               GNUNET_YES, GNUNET_NO, 
1015               GNUNET_NO, GNUNET_NO,
1016               q1, q2,
1017               iter, iter_cls);
1018   GNUNET_free (q1);
1019   GNUNET_free (q2);
1020 }
1021
1022
1023 /**
1024  * Select a subset of the items in the datastore and call
1025  * the given iterator for each of them.
1026  *
1027  * @param type entries of which type should be considered?
1028  *        Use 0 for any type.
1029  * @param iter function to call on each matching value;
1030  *        will be called once with a NULL value at the end
1031  * @param iter_cls closure for iter
1032  */
1033 static void
1034 sqlite_plugin_iter_migration_order (void *cls,
1035                                     uint32_t type,
1036                                     PluginIterator iter,
1037                                     void *iter_cls)
1038 {
1039   struct GNUNET_TIME_Absolute now;
1040   char *q;
1041
1042   now = GNUNET_TIME_absolute_get ();
1043   GNUNET_asprintf (&q, SELECT_IT_MIGRATION_ORDER_2,
1044                    now.value);
1045   basic_iter (cls,
1046               type, 
1047               GNUNET_NO, GNUNET_NO, 
1048               GNUNET_YES, GNUNET_NO,
1049               SELECT_IT_MIGRATION_ORDER_1,
1050               q,
1051               iter, iter_cls);
1052   GNUNET_free (q);
1053 }
1054
1055
1056
1057 /**
1058  * Select a subset of the items in the datastore and call
1059  * the given iterator for each of them.
1060  *
1061  * @param type entries of which type should be considered?
1062  *        Use 0 for any type.
1063  * @param iter function to call on each matching value;
1064  *        will be called once with a NULL value at the end
1065  * @param iter_cls closure for iter
1066  */
1067 static void
1068 sqlite_plugin_iter_all_now (void *cls,
1069                             uint32_t type,
1070                             PluginIterator iter,
1071                             void *iter_cls)
1072 {
1073   static struct GNUNET_TIME_Absolute zero;
1074   iter (iter_cls, NULL, NULL, 0, NULL, 0, 0, 0, zero, 0);
1075 }
1076
1077
1078 struct GetNextContext
1079 {
1080   int total;
1081   int off;
1082   int have_vhash;
1083   unsigned int type;
1084   sqlite3_stmt *stmt;
1085   GNUNET_HashCode key;
1086   GNUNET_HashCode vhash;
1087 };
1088
1089
1090 static int
1091 get_next_prepare (void *cls,
1092                   struct NextContext *nc)
1093 {
1094   struct GetNextContext *gnc = cls;
1095   int sqoff;
1096   int ret;
1097   int limit_off;
1098
1099   if (nc == NULL)
1100     {
1101       sqlite3_finalize (gnc->stmt);
1102       return GNUNET_SYSERR;
1103     }
1104   if (nc->count == gnc->total)
1105     return GNUNET_NO;
1106   if (nc->count + gnc->off == gnc->total)
1107     nc->last_rowid = 0;
1108   if (nc->count == 0)
1109     limit_off = gnc->off;
1110   else
1111     limit_off = 0;
1112   sqoff = 1;
1113   ret = sqlite3_bind_blob (nc->stmt,
1114                            sqoff++,
1115                            &gnc->key, 
1116                            sizeof (GNUNET_HashCode),
1117                            SQLITE_TRANSIENT);
1118   if ((gnc->have_vhash) && (ret == SQLITE_OK))
1119     ret = sqlite3_bind_blob (nc->stmt,
1120                              sqoff++,
1121                              &gnc->vhash,
1122                              sizeof (GNUNET_HashCode), SQLITE_TRANSIENT);
1123   if ((gnc->type != 0) && (ret == SQLITE_OK))
1124     ret = sqlite3_bind_int (nc->stmt, sqoff++, gnc->type);
1125   if (ret == SQLITE_OK)
1126     ret = sqlite3_bind_int64 (nc->stmt, sqoff++, nc->last_rowid + 1);
1127   if (ret == SQLITE_OK)
1128     ret = sqlite3_bind_int (nc->stmt, sqoff++, limit_off);
1129   if (ret != SQLITE_OK)
1130     return GNUNET_SYSERR;
1131   if (SQLITE_ROW != sqlite3_step (nc->stmt))
1132     return GNUNET_NO;
1133   return GNUNET_OK;
1134 }
1135
1136
1137 /**
1138  * Iterate over the results for a particular key
1139  * in the datastore.
1140  *
1141  * @param cls closure
1142  * @param key maybe NULL (to match all entries)
1143  * @param vhash hash of the value, maybe NULL (to
1144  *        match all values that have the right key).
1145  *        Note that for DBlocks there is no difference
1146  *        betwen key and vhash, but for other blocks
1147  *        there may be!
1148  * @param type entries of which type are relevant?
1149  *     Use 0 for any type.
1150  * @param iter function to call on each matching value;
1151  *        will be called once with a NULL value at the end
1152  * @param iter_cls closure for iter
1153  */
1154 static void
1155 sqlite_plugin_get (void *cls,
1156                    const GNUNET_HashCode * key,
1157                    const GNUNET_HashCode * vhash,
1158                    uint32_t type,
1159                    PluginIterator iter, void *iter_cls)
1160 {
1161   static struct GNUNET_TIME_Absolute zero;
1162   struct Plugin *plugin = cls;
1163   struct GetNextContext *gpc;
1164   struct NextContext *nc;
1165   int ret;
1166   int total;
1167   sqlite3_stmt *stmt;
1168   char scratch[256];
1169   int sqoff;
1170
1171   GNUNET_assert (iter != NULL);
1172   if (key == NULL)
1173     {
1174       sqlite_plugin_iter_low_priority (cls, type, iter, iter_cls);
1175       return;
1176     }
1177   GNUNET_snprintf (scratch, 256,
1178                    "SELECT count(*) FROM gn080 WHERE hash=:1%s%s",
1179                    vhash == NULL ? "" : " AND vhash=:2",
1180                    type == 0 ? "" : (vhash ==
1181                                      NULL) ? " AND type=:2" : " AND type=:3");
1182   if (sq_prepare (plugin->dbh, scratch, &stmt) != SQLITE_OK)
1183     {
1184       LOG_SQLITE (plugin, NULL,
1185                   GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, "sqlite_prepare");
1186       iter (iter_cls, NULL, NULL, 0, NULL, 0, 0, 0, zero, 0);
1187       return;
1188     }
1189   sqoff = 1;
1190   ret = sqlite3_bind_blob (stmt,
1191                            sqoff++,
1192                            key, sizeof (GNUNET_HashCode), SQLITE_TRANSIENT);
1193   if ((vhash != NULL) && (ret == SQLITE_OK))
1194     ret = sqlite3_bind_blob (stmt,
1195                              sqoff++,
1196                              vhash,
1197                              sizeof (GNUNET_HashCode), SQLITE_TRANSIENT);
1198   if ((type != 0) && (ret == SQLITE_OK))
1199     ret = sqlite3_bind_int (stmt, sqoff++, type);
1200   if (SQLITE_OK != ret)
1201     {
1202       LOG_SQLITE (plugin, NULL,
1203                   GNUNET_ERROR_TYPE_ERROR, "sqlite_bind");
1204       sqlite3_reset (stmt);
1205       sqlite3_finalize (stmt);
1206       iter (iter_cls, NULL, NULL, 0, NULL, 0, 0, 0, zero, 0);
1207       return;
1208     }
1209   ret = sqlite3_step (stmt);
1210   if (ret != SQLITE_ROW)
1211     {
1212       LOG_SQLITE (plugin, NULL,
1213                   GNUNET_ERROR_TYPE_ERROR| GNUNET_ERROR_TYPE_BULK, 
1214                   "sqlite_step");
1215       sqlite3_reset (stmt);
1216       sqlite3_finalize (stmt);
1217       iter (iter_cls, NULL, NULL, 0, NULL, 0, 0, 0, zero, 0);
1218       return;
1219     }
1220   total = sqlite3_column_int (stmt, 0);
1221   sqlite3_reset (stmt);
1222   sqlite3_finalize (stmt);
1223   if (0 == total)
1224     {
1225       iter (iter_cls, NULL, NULL, 0, NULL, 0, 0, 0, zero, 0);
1226       return;
1227     }
1228
1229   GNUNET_snprintf (scratch, 256,
1230                    "SELECT size, type, prio, anonLevel, expire, hash, value, _ROWID_ "
1231                    "FROM gn080 WHERE hash=:1%s%s AND _ROWID_ >= :%d "
1232                    "ORDER BY _ROWID_ ASC LIMIT 1 OFFSET :d",
1233                    vhash == NULL ? "" : " AND vhash=:2",
1234                    type == 0 ? "" : (vhash ==
1235                                      NULL) ? " AND type=:2" : " AND type=:3",
1236                    sqoff, sqoff + 1);
1237   if (sq_prepare (plugin->dbh, scratch, &stmt) != SQLITE_OK)
1238     {
1239       LOG_SQLITE (plugin, NULL,
1240                   GNUNET_ERROR_TYPE_ERROR |
1241                   GNUNET_ERROR_TYPE_BULK, "sqlite_prepare");
1242       iter (iter_cls, NULL, NULL, 0, NULL, 0, 0, 0, zero, 0);
1243       return;
1244     }
1245   nc = GNUNET_malloc (sizeof(struct NextContext) + 
1246                       sizeof(struct GetNextContext));
1247   nc->plugin = plugin;
1248   nc->iter = iter;
1249   nc->iter_cls = iter_cls;
1250   nc->stmt = stmt;
1251   gpc = (struct GetNextContext*) &nc[1];
1252   gpc->total = total;
1253   gpc->type = type;
1254   gpc->key = *key;
1255   gpc->stmt = stmt; /* alias used for freeing at the end! */
1256   if (NULL != vhash)
1257     {
1258       gpc->have_vhash = GNUNET_YES;
1259       gpc->vhash = *vhash;
1260     }
1261   gpc->off = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, total);
1262   nc->prep = &get_next_prepare;
1263   nc->prep_cls = gpc;
1264   sqlite_next_request (nc, GNUNET_NO);
1265 }
1266
1267
1268 /**
1269  * Drop database.
1270  */
1271 static void 
1272 sqlite_plugin_drop (void *cls)
1273 {
1274   struct Plugin *plugin = cls;
1275   plugin->drop_on_shutdown = GNUNET_YES;
1276 }
1277
1278
1279 /**
1280  * Callback function to process statistic values.
1281  *
1282  * @param cls closure
1283  * @param subsystem name of subsystem that created the statistic
1284  * @param name the name of the datum
1285  * @param value the current value
1286  * @param is_persistent GNUNET_YES if the value is persistent, GNUNET_NO if not
1287  * @return GNUNET_OK to continue, GNUNET_SYSERR to abort iteration
1288  */
1289 static int
1290 process_stat_in (void *cls,
1291                  const char *subsystem,
1292                  const char *name,
1293                  unsigned long long value,
1294                  int is_persistent)
1295 {
1296   struct Plugin *plugin = cls;
1297   plugin->payload += value;
1298   return GNUNET_OK;
1299 }
1300                                          
1301
1302 /**
1303  * Entry point for the plugin.
1304  */
1305 void *
1306 libgnunet_plugin_datastore_sqlite_init (void *cls)
1307 {
1308   static struct Plugin plugin;
1309   struct GNUNET_DATASTORE_PluginEnvironment *env = cls;
1310   struct GNUNET_DATASTORE_PluginFunctions *api;
1311
1312   if (plugin.env != NULL)
1313     return NULL; /* can only initialize once! */
1314   memset (&plugin, 0, sizeof(struct Plugin));
1315   plugin.env = env;
1316   plugin.statistics = GNUNET_STATISTICS_create (env->sched,
1317                                                 "sqlite",
1318                                                 env->cfg);
1319   GNUNET_STATISTICS_get (plugin.statistics,
1320                          "sqlite",
1321                          QUOTA_STAT_NAME,
1322                          GNUNET_TIME_UNIT_MINUTES,
1323                          NULL,
1324                          &process_stat_in,
1325                          &plugin);
1326   if (GNUNET_OK !=
1327       database_setup (env->cfg, &plugin))
1328     {
1329       database_shutdown (&plugin);
1330       return NULL;
1331     }
1332   api = GNUNET_malloc (sizeof (struct GNUNET_DATASTORE_PluginFunctions));
1333   api->cls = &plugin;
1334   api->get_size = &sqlite_plugin_get_size;
1335   api->put = &sqlite_plugin_put;
1336   api->next_request = &sqlite_next_request;
1337   api->get = &sqlite_plugin_get;
1338   api->update = &sqlite_plugin_update;
1339   api->iter_low_priority = &sqlite_plugin_iter_low_priority;
1340   api->iter_zero_anonymity = &sqlite_plugin_iter_zero_anonymity;
1341   api->iter_ascending_expiration = &sqlite_plugin_iter_ascending_expiration;
1342   api->iter_migration_order = &sqlite_plugin_iter_migration_order;
1343   api->iter_all_now = &sqlite_plugin_iter_all_now;
1344   api->drop = &sqlite_plugin_drop;
1345   GNUNET_log_from (GNUNET_ERROR_TYPE_INFO,
1346                    "sqlite", _("Sqlite database running\n"));
1347   return api;
1348 }
1349
1350
1351 /**
1352  * Exit point from the plugin.
1353  */
1354 void *
1355 libgnunet_plugin_datastore_sqlite_done (void *cls)
1356 {
1357   char *fn;
1358   struct GNUNET_DATASTORE_PluginFunctions *api = cls;
1359   struct Plugin *plugin = api->cls;
1360
1361   fn = NULL;
1362   if (plugin->drop_on_shutdown)
1363     fn = GNUNET_strdup (plugin->fn);
1364   database_shutdown (plugin);
1365   plugin->env = NULL; 
1366   plugin->payload = 0;
1367   GNUNET_free (api);
1368   if (fn != NULL)
1369     {
1370       if (0 != UNLINK(fn))
1371         GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING,
1372                                   "unlink",
1373                                   fn);
1374       GNUNET_free (fn);
1375     }
1376   return NULL;
1377 }
1378
1379 /* end of plugin_datastore_sqlite.c */