2 This file is part of GNUnet
3 (C) 2009 Christian Grothoff (and other contributing authors)
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.
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.
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.
22 * @file datastore/plugin_datastore_sqlite.c
23 * @brief sqlite-based datastore backend
24 * @author Christian Grothoff
28 #include "gnunet_statistics_service.h"
29 #include "plugin_datastore.h"
32 #define DEBUG_SQLITE GNUNET_YES
35 * After how many payload-changing operations
36 * do we sync our statistics?
38 #define MAX_STAT_SYNC_LAG 50
40 #define QUOTA_STAT_NAME gettext_noop ("file-sharing datastore utilization (in bytes)")
44 * Die with an error message that indicates
45 * a failure of the command 'cmd' with the message given
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)
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).
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)
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"
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"
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"
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"
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"
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"
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"
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"
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).
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.
99 #define BUSY_TIMEOUT_MS 250
103 * Context for all functions in this plugin.
108 * Our execution environment.
110 struct GNUNET_DATASTORE_PluginEnvironment *env;
118 * Native SQLite database handle.
123 * Precompiled SQL for update.
125 sqlite3_stmt *updPrio;
128 * Precompiled SQL for insertion.
130 sqlite3_stmt *insertContent;
133 * Handle to the statistics service.
135 struct GNUNET_STATISTICS_Handle *statistics;
138 * How much data are we currently storing
141 unsigned long long payload;
144 * Number of updates that were made to the
145 * payload value since we last synchronized
146 * it with the statistics service.
148 unsigned int lastSync;
151 * Should the database be dropped on shutdown?
153 int drop_on_shutdown;
158 * @brief Prepare a SQL statement
160 * @param zSql SQL statement, UTF-8 encoded
163 sq_prepare (sqlite3 * dbh, const char *zSql,
164 sqlite3_stmt ** ppStmt)
167 return sqlite3_prepare (dbh,
169 strlen (zSql), ppStmt, (const char **) &dummy);
174 * Create our database indices.
177 create_indices (sqlite3 * dbh)
181 "CREATE INDEX idx_hash ON gn080 (hash)", NULL, NULL, NULL);
183 "CREATE INDEX idx_hash_vhash ON gn080 (hash,vhash)", NULL,
185 sqlite3_exec (dbh, "CREATE INDEX idx_prio ON gn080 (prio)", NULL, NULL,
187 sqlite3_exec (dbh, "CREATE INDEX idx_expire ON gn080 (expire)", NULL, NULL,
189 sqlite3_exec (dbh, "CREATE INDEX idx_comb3 ON gn080 (prio,anonLevel)", NULL,
191 sqlite3_exec (dbh, "CREATE INDEX idx_comb4 ON gn080 (prio,hash,anonLevel)",
193 sqlite3_exec (dbh, "CREATE INDEX idx_comb7 ON gn080 (expire,hash)", NULL,
200 #define CHECK(a) GNUNET_break(a)
204 #define ENULL_DEFINED 1
205 #define CHECK(a) if (! a) { GNUNET_log(GNUNET_ERROR_TYPE_ERRROR, "%s\n", e); sqlite3_free(e); }
212 * Initialize the database connections and associated
213 * data structures (create tables and indices
214 * as needed as well).
216 * @return GNUNET_OK on success
219 database_setup (struct GNUNET_CONFIGURATION_Handle *cfg,
220 struct Plugin *plugin)
229 GNUNET_CONFIGURATION_get_value_filename (cfg,
234 GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR,
236 _("Option `%s' in section `%s' missing in configuration!\n"),
239 return GNUNET_SYSERR;
241 if (GNUNET_OK != GNUNET_DISK_directory_create_for_file (afsdir))
244 GNUNET_free (afsdir);
245 return GNUNET_SYSERR;
247 plugin->fn = GNUNET_STRINGS_to_utf8 (afsdir, strlen (afsdir),
249 nl_langinfo (CODESET)
251 "UTF-8" /* good luck */
254 GNUNET_free (afsdir);
256 /* Open database and precompile statements */
257 if (sqlite3_open (plugin->fn, &plugin->dbh) != SQLITE_OK)
259 GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR,
261 _("Unable to initialize SQLite: %s.\n"),
262 sqlite3_errmsg (plugin->dbh));
263 return GNUNET_SYSERR;
266 sqlite3_exec (plugin->dbh,
267 "PRAGMA temp_store=MEMORY", NULL, NULL, ENULL));
269 sqlite3_exec (plugin->dbh,
270 "PRAGMA synchronous=OFF", NULL, NULL, ENULL));
272 sqlite3_exec (plugin->dbh,
273 "PRAGMA count_changes=OFF", NULL, NULL, ENULL));
275 sqlite3_exec (plugin->dbh, "PRAGMA page_size=4092", NULL, NULL, ENULL));
277 CHECK (SQLITE_OK == sqlite3_busy_timeout (plugin->dbh, BUSY_TIMEOUT_MS));
280 /* We have to do it here, because otherwise precompiling SQL might fail */
282 sq_prepare (plugin->dbh,
283 "SELECT 1 FROM sqlite_master WHERE tbl_name = 'gn080'",
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) )
298 LOG_SQLITE (plugin, NULL,
299 GNUNET_ERROR_TYPE_ERROR,
301 sqlite3_finalize (stmt);
302 return GNUNET_SYSERR;
304 sqlite3_finalize (stmt);
305 create_indices (plugin->dbh);
308 sq_prepare (plugin->dbh,
309 "SELECT 1 FROM sqlite_master WHERE tbl_name = 'gn071'",
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) )
318 LOG_SQLITE (plugin, NULL,
319 GNUNET_ERROR_TYPE_ERROR, "sqlite3_exec");
320 sqlite3_finalize (stmt);
321 return GNUNET_SYSERR;
323 sqlite3_finalize (stmt);
325 if ((sq_prepare (plugin->dbh,
326 "UPDATE gn080 SET prio = prio + ?, expire = MAX(expire,?) WHERE "
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))
335 LOG_SQLITE (plugin, NULL,
336 GNUNET_ERROR_TYPE_ERROR, "precompiling");
337 return GNUNET_SYSERR;
344 * Synchronize our utilization statistics with the
345 * statistics service.
348 sync_stats (struct Plugin *plugin)
350 GNUNET_STATISTICS_set (plugin->statistics,
354 plugin->lastSync = 0;
359 * Shutdown database connection and associate data
363 database_shutdown (struct Plugin *plugin)
365 if (plugin->lastSync > 0)
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);
377 * Get an estimate of how much space the database is
379 * @return number of bytes used on disk
381 static unsigned long long sqlite_plugin_get_size (void *cls)
383 struct Plugin *plugin = cls;
384 return plugin->payload;
389 * Delete the database entry with the given
393 delete_by_rowid (struct Plugin* plugin,
394 unsigned long long rid)
398 if (sq_prepare (plugin->dbh,
399 "DELETE FROM gn080 WHERE _ROWID_ = ?", &stmt) != SQLITE_OK)
401 LOG_SQLITE (plugin, NULL,
402 GNUNET_ERROR_TYPE_ERROR |
403 GNUNET_ERROR_TYPE_BULK, "sq_prepare");
404 return GNUNET_SYSERR;
406 sqlite3_bind_int64 (stmt, 1, rid);
407 if (SQLITE_DONE != sqlite3_step (stmt))
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;
415 sqlite3_finalize (stmt);
421 * Context for the universal iterator.
426 * Type of a function that will prepare
427 * the next iteration.
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
436 typedef int (*PrepareFunction)(void *cls,
437 struct NextContext *nc);
441 * Context we keep for the "next request" callback.
448 struct Plugin *plugin;
451 * Function to call on the next value.
461 * Function to call to prepare the next
464 PrepareFunction prep;
472 * Statement that the iterator will get the data
473 * from (updated or set by prep).
478 * Row ID of the last result.
480 unsigned long long last_rowid;
483 * Key of the last result.
485 GNUNET_HashCode lastKey;
488 * Expiration time of the last value visited.
490 struct GNUNET_TIME_Absolute lastExpiration;
493 * Priority of the last value visited.
495 unsigned int lastPriority;
498 * Number of results processed so far.
503 * Set to GNUNET_YES if we must stop now.
510 * Continuation of "sqlite_next_request".
512 * @param cls the next context
515 sqlite_next_request_cont (void *cls,
516 const struct GNUNET_SCHEDULER_TaskContext *tc)
518 static struct GNUNET_TIME_Absolute zero;
519 struct NextContext * nc= cls;
520 struct Plugin *plugin;
521 unsigned long long rowid;
526 unsigned int priority;
527 unsigned int anonymity;
528 struct GNUNET_TIME_Absolute expiration;
529 const GNUNET_HashCode *key;
534 if ( (GNUNET_YES == nc->end_it) ||
535 (GNUNET_OK != (nc->prep(nc->prep_cls,
539 nc->iter (nc->iter_cls,
540 NULL, NULL, 0, NULL, 0, 0, 0,
542 nc->prep (nc->prep_cls, NULL);
547 rowid = sqlite3_column_int64 (nc->stmt, 7);
548 nc->last_rowid = rowid;
549 type = sqlite3_column_int (nc->stmt, 1);
550 size = sqlite3_column_bytes (nc->stmt, 6);
551 if (sqlite3_column_bytes (nc->stmt, 5) != sizeof (GNUNET_HashCode))
553 GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING,
555 _("Invalid data in database. Trying to fix (by deletion).\n"));
556 if (SQLITE_OK != sqlite3_reset (nc->stmt))
557 LOG_SQLITE (nc->plugin, NULL,
558 GNUNET_ERROR_TYPE_ERROR |
559 GNUNET_ERROR_TYPE_BULK, "sqlite3_reset");
562 "DELETE FROM gn080 WHERE NOT LENGTH(hash) = ?",
563 &stmtd) != SQLITE_OK)
565 LOG_SQLITE (nc->plugin, NULL,
566 GNUNET_ERROR_TYPE_ERROR |
567 GNUNET_ERROR_TYPE_BULK,
572 if (SQLITE_OK != sqlite3_bind_int (stmtd, 1, sizeof (GNUNET_HashCode)))
573 LOG_SQLITE (nc->plugin, NULL,
574 GNUNET_ERROR_TYPE_ERROR |
575 GNUNET_ERROR_TYPE_BULK, "sqlite3_bind_int");
576 if (SQLITE_DONE != sqlite3_step (stmtd))
577 LOG_SQLITE (nc->plugin, NULL,
578 GNUNET_ERROR_TYPE_ERROR |
579 GNUNET_ERROR_TYPE_BULK, "sqlite3_step");
580 if (SQLITE_OK != sqlite3_finalize (stmtd))
581 LOG_SQLITE (nc->plugin, NULL,
582 GNUNET_ERROR_TYPE_ERROR |
583 GNUNET_ERROR_TYPE_BULK, "sqlite3_finalize");
587 priority = sqlite3_column_int (nc->stmt, 2);
588 anonymity = sqlite3_column_int (nc->stmt, 3);
589 expiration.value = sqlite3_column_int64 (nc->stmt, 4);
590 key = sqlite3_column_blob (nc->stmt, 5);
591 nc->lastPriority = priority;
592 nc->lastExpiration = expiration;
593 memcpy (&nc->lastKey, key, sizeof(GNUNET_HashCode));
594 data = sqlite3_column_blob (nc->stmt, 6);
596 ret = nc->iter (nc->iter_cls,
606 if (ret == GNUNET_SYSERR)
608 nc->end_it = GNUNET_YES;
611 if ( (ret == GNUNET_NO) &&
612 (GNUNET_OK == delete_by_rowid (plugin, rowid)) )
614 plugin->payload -= (size + GNUNET_DATASTORE_ENTRY_OVERHEAD);
616 if (plugin->lastSync >= MAX_STAT_SYNC_LAG)
623 * Function invoked on behalf of a "PluginIterator"
624 * asking the database plugin to call the iterator
625 * with the next item.
627 * @param next_cls whatever argument was given
628 * to the PluginIterator as "next_cls".
629 * @param end_it set to GNUNET_YES if we
630 * should terminate the iteration early
631 * (iterator should be still called once more
632 * to signal the end of the iteration).
635 sqlite_next_request (void *next_cls,
638 struct NextContext * nc= next_cls;
640 if (GNUNET_YES == end_it)
641 nc->end_it = GNUNET_YES;
642 GNUNET_SCHEDULER_add_continuation (nc->plugin->env->sched,
644 &sqlite_next_request_cont,
646 GNUNET_SCHEDULER_REASON_PREREQ_DONE);
652 * Store an item in the datastore.
655 * @param key key for the item
656 * @param size number of bytes in data
657 * @param data content stored
658 * @param type type of the content
659 * @param priority priority of the content
660 * @param anonymity anonymity-level for the content
661 * @param expiration expiration time for the content
662 * @param msg set to an error message
663 * @return GNUNET_OK on success
666 sqlite_plugin_put (void *cls,
667 const GNUNET_HashCode * key,
673 struct GNUNET_TIME_Absolute expiration,
676 struct Plugin *plugin = cls;
679 GNUNET_HashCode vhash;
682 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
684 "Storing in database block with type %u/key `%s'/priority %u/expiration %llu.\n",
688 GNUNET_TIME_absolute_get_remaining (expiration).value);
690 GNUNET_CRYPTO_hash (data, size, &vhash);
691 stmt = plugin->insertContent;
692 if ((SQLITE_OK != sqlite3_bind_int (stmt, 1, size)) ||
693 (SQLITE_OK != sqlite3_bind_int (stmt, 2, type)) ||
694 (SQLITE_OK != sqlite3_bind_int (stmt, 3, priority)) ||
695 (SQLITE_OK != sqlite3_bind_int (stmt, 4, anonymity)) ||
696 (SQLITE_OK != sqlite3_bind_int64 (stmt, 5, expiration.value)) ||
698 sqlite3_bind_blob (stmt, 6, key, sizeof (GNUNET_HashCode),
699 SQLITE_TRANSIENT)) ||
701 sqlite3_bind_blob (stmt, 7, &vhash, sizeof (GNUNET_HashCode),
704 sqlite3_bind_blob (stmt, 8, data, size,
709 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, "sqlite3_bind_XXXX");
710 if (SQLITE_OK != sqlite3_reset (stmt))
711 LOG_SQLITE (plugin, NULL,
712 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, "sqlite3_reset");
713 return GNUNET_SYSERR;
715 n = sqlite3_step (stmt);
716 if (n != SQLITE_DONE)
718 if (n == SQLITE_BUSY)
720 LOG_SQLITE (plugin, msg,
721 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, "sqlite3_step");
722 sqlite3_reset (stmt);
726 LOG_SQLITE (plugin, msg,
727 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, "sqlite3_step");
728 sqlite3_reset (stmt);
729 return GNUNET_SYSERR;
731 if (SQLITE_OK != sqlite3_reset (stmt))
732 LOG_SQLITE (plugin, NULL,
733 GNUNET_ERROR_TYPE_ERROR |
734 GNUNET_ERROR_TYPE_BULK, "sqlite3_reset");
736 plugin->payload += size + GNUNET_DATASTORE_ENTRY_OVERHEAD;
737 if (plugin->lastSync >= MAX_STAT_SYNC_LAG)
744 * Update the priority for a particular key in the datastore. If
745 * the expiration time in value is different than the time found in
746 * the datastore, the higher value should be kept. For the
747 * anonymity level, the lower value is to be used. The specified
748 * priority should be added to the existing priority, ignoring the
751 * Note that it is possible for multiple values to match this put.
752 * In that case, all of the respective values are updated.
754 * @param uid unique identifier of the datum
755 * @param delta by how much should the priority
756 * change? If priority + delta < 0 the
757 * priority should be set to 0 (never go
759 * @param expire new expiration time should be the
760 * MAX of any existing expiration time and
762 * @param msg set to an error message
763 * @return GNUNET_OK on success
766 sqlite_plugin_update (void *cls,
768 int delta, struct GNUNET_TIME_Absolute expire,
771 struct Plugin *plugin = cls;
774 sqlite3_bind_int (plugin->updPrio, 1, delta);
775 sqlite3_bind_int64 (plugin->updPrio, 2, expire.value);
776 sqlite3_bind_int64 (plugin->updPrio, 3, uid);
777 n = sqlite3_step (plugin->updPrio);
779 LOG_SQLITE (plugin, msg,
780 GNUNET_ERROR_TYPE_WARNING | GNUNET_ERROR_TYPE_BULK,
784 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
788 sqlite3_reset (plugin->updPrio);
790 if (n == SQLITE_BUSY)
792 return n == SQLITE_OK ? GNUNET_OK : GNUNET_SYSERR;
798 sqlite3_stmt *stmt_1;
799 sqlite3_stmt *stmt_2;
803 int limit_nonanonymous;
809 iter_next_prepare (void *cls,
810 struct NextContext *nc)
812 struct IterContext *ic = cls;
813 struct Plugin *plugin;
819 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
820 "Asked to clean up iterator state.\n");
822 sqlite3_finalize (ic->stmt_1);
823 sqlite3_finalize (ic->stmt_2);
824 return GNUNET_SYSERR;
826 sqlite3_reset (ic->stmt_1);
827 sqlite3_reset (ic->stmt_2);
832 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
833 "Restricting to results larger than the last priority %u\n",
836 sqlite3_bind_int (ic->stmt_1, 1, nc->lastPriority);
837 sqlite3_bind_int (ic->stmt_2, 1, nc->lastPriority);
842 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
843 "Restricting to results larger than the last expiration %llu\n",
844 (unsigned long long) nc->lastExpiration.value);
846 sqlite3_bind_int64 (ic->stmt_1, 1, nc->lastExpiration.value);
847 sqlite3_bind_int64 (ic->stmt_2, 1, nc->lastExpiration.value);
850 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
851 "Restricting to results larger than the last key `%s'\n",
852 GNUNET_h2s(&nc->lastKey));
854 sqlite3_bind_blob (ic->stmt_1, 2,
856 sizeof (GNUNET_HashCode),
858 if (SQLITE_ROW == (ret = sqlite3_step (ic->stmt_1)))
861 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
862 "Result found using iterator 1\n");
864 nc->stmt = ic->stmt_1;
867 if (ret != SQLITE_DONE)
869 LOG_SQLITE (plugin, NULL,
870 GNUNET_ERROR_TYPE_ERROR |
871 GNUNET_ERROR_TYPE_BULK,
873 return GNUNET_SYSERR;
875 if (SQLITE_OK != sqlite3_reset (ic->stmt_1))
876 LOG_SQLITE (plugin, NULL,
877 GNUNET_ERROR_TYPE_ERROR |
878 GNUNET_ERROR_TYPE_BULK,
880 if (SQLITE_ROW == (ret = sqlite3_step (ic->stmt_2)))
883 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
884 "Result found using iterator 2\n");
886 nc->stmt = ic->stmt_2;
889 if (ret != SQLITE_DONE)
891 LOG_SQLITE (plugin, NULL,
892 GNUNET_ERROR_TYPE_ERROR |
893 GNUNET_ERROR_TYPE_BULK,
895 return GNUNET_SYSERR;
897 if (SQLITE_OK != sqlite3_reset (ic->stmt_2))
898 LOG_SQLITE (plugin, NULL,
899 GNUNET_ERROR_TYPE_ERROR |
900 GNUNET_ERROR_TYPE_BULK,
903 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
904 "No result found using either iterator\n");
911 * Call a method for each key in the database and
912 * call the callback method on it.
914 * @param type entries of which type should be considered?
915 * @param iter function to call on each matching value;
916 * will be called once with a NULL value at the end
917 * @param iter_cls closure for iter
918 * @return the number of results processed,
919 * GNUNET_SYSERR on error
922 basic_iter (struct Plugin *plugin,
927 int limit_nonanonymous,
928 const char *stmt_str_1,
929 const char *stmt_str_2,
933 static struct GNUNET_TIME_Absolute zero;
934 struct NextContext *nc;
935 struct IterContext *ic;
936 sqlite3_stmt *stmt_1;
937 sqlite3_stmt *stmt_2;
940 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
941 "At %llu, using queries `%s' and `%s'\n",
942 (unsigned long long) GNUNET_TIME_absolute_get ().value,
946 if (sq_prepare (plugin->dbh, stmt_str_1, &stmt_1) != SQLITE_OK)
948 LOG_SQLITE (plugin, NULL,
949 GNUNET_ERROR_TYPE_ERROR |
950 GNUNET_ERROR_TYPE_BULK, "sqlite3_prepare");
951 iter (iter_cls, NULL, NULL, 0, NULL, 0, 0, 0, zero, 0);
954 if (sq_prepare (plugin->dbh, stmt_str_2, &stmt_2) != SQLITE_OK)
956 LOG_SQLITE (plugin, NULL,
957 GNUNET_ERROR_TYPE_ERROR |
958 GNUNET_ERROR_TYPE_BULK, "sqlite3_prepare");
959 sqlite3_finalize (stmt_1);
960 iter (iter_cls, NULL, NULL, 0, NULL, 0, 0, 0, zero, 0);
963 nc = GNUNET_malloc (sizeof(struct NextContext) +
964 sizeof(struct IterContext));
967 nc->iter_cls = iter_cls;
969 ic = (struct IterContext*) &nc[1];
974 ic->is_prio = is_prio;
975 ic->is_migr = is_migr;
976 ic->limit_nonanonymous = limit_nonanonymous;
977 nc->prep = &iter_next_prepare;
981 nc->lastPriority = 0;
982 nc->lastExpiration.value = 0;
983 memset (&nc->lastKey, 0, sizeof (GNUNET_HashCode));
987 nc->lastPriority = 0x7FFFFFFF;
988 nc->lastExpiration.value = 0x7FFFFFFFFFFFFFFFLL;
989 memset (&nc->lastKey, 255, sizeof (GNUNET_HashCode));
991 sqlite_next_request (nc, GNUNET_NO);
996 * Select a subset of the items in the datastore and call
997 * the given iterator for each of them.
999 * @param type entries of which type should be considered?
1000 * Use 0 for any type.
1001 * @param iter function to call on each matching value;
1002 * will be called once with a NULL value at the end
1003 * @param iter_cls closure for iter
1006 sqlite_plugin_iter_low_priority (void *cls,
1008 PluginIterator iter,
1013 GNUNET_YES, GNUNET_YES,
1014 GNUNET_NO, GNUNET_NO,
1015 SELECT_IT_LOW_PRIORITY_1,
1016 SELECT_IT_LOW_PRIORITY_2,
1022 * Select a subset of the items in the datastore and call
1023 * the given iterator for each of them.
1025 * @param type entries of which type should be considered?
1026 * Use 0 for any type.
1027 * @param iter function to call on each matching value;
1028 * will be called once with a NULL value at the end
1029 * @param iter_cls closure for iter
1032 sqlite_plugin_iter_zero_anonymity (void *cls,
1034 PluginIterator iter,
1037 struct GNUNET_TIME_Absolute now;
1041 now = GNUNET_TIME_absolute_get ();
1042 GNUNET_asprintf (&q1, SELECT_IT_NON_ANONYMOUS_1,
1043 (unsigned long long) now.value);
1044 GNUNET_asprintf (&q2, SELECT_IT_NON_ANONYMOUS_2,
1045 (unsigned long long) now.value);
1048 GNUNET_NO, GNUNET_YES,
1049 GNUNET_NO, GNUNET_YES,
1060 * Select a subset of the items in the datastore and call
1061 * the given iterator for each of them.
1063 * @param type entries of which type should be considered?
1064 * Use 0 for any type.
1065 * @param iter function to call on each matching value;
1066 * will be called once with a NULL value at the end
1067 * @param iter_cls closure for iter
1070 sqlite_plugin_iter_ascending_expiration (void *cls,
1072 PluginIterator iter,
1075 struct GNUNET_TIME_Absolute now;
1079 now = GNUNET_TIME_absolute_get ();
1080 GNUNET_asprintf (&q1, SELECT_IT_EXPIRATION_TIME_1,
1081 (unsigned long long) 0*now.value);
1082 GNUNET_asprintf (&q2, SELECT_IT_EXPIRATION_TIME_2,
1083 (unsigned long long) 0*now.value);
1086 GNUNET_YES, GNUNET_NO,
1087 GNUNET_NO, GNUNET_NO,
1096 * Select a subset of the items in the datastore and call
1097 * the given iterator for each of them.
1099 * @param type entries of which type should be considered?
1100 * Use 0 for any type.
1101 * @param iter function to call on each matching value;
1102 * will be called once with a NULL value at the end
1103 * @param iter_cls closure for iter
1106 sqlite_plugin_iter_migration_order (void *cls,
1108 PluginIterator iter,
1111 struct GNUNET_TIME_Absolute now;
1114 now = GNUNET_TIME_absolute_get ();
1115 GNUNET_asprintf (&q, SELECT_IT_MIGRATION_ORDER_2,
1116 (unsigned long long) now.value);
1119 GNUNET_NO, GNUNET_NO,
1120 GNUNET_YES, GNUNET_NO,
1121 SELECT_IT_MIGRATION_ORDER_1,
1129 all_next_prepare (void *cls,
1130 struct NextContext *nc)
1132 struct Plugin *plugin;
1138 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1139 "Asked to clean up iterator state.\n");
1141 return GNUNET_SYSERR;
1143 plugin = nc->plugin;
1144 if (SQLITE_ROW == (ret = sqlite3_step (nc->stmt)))
1148 if (ret != SQLITE_DONE)
1150 LOG_SQLITE (plugin, NULL,
1151 GNUNET_ERROR_TYPE_ERROR |
1152 GNUNET_ERROR_TYPE_BULK,
1154 return GNUNET_SYSERR;
1161 * Select a subset of the items in the datastore and call
1162 * the given iterator for each of them.
1164 * @param type entries of which type should be considered?
1165 * Use 0 for any type.
1166 * @param iter function to call on each matching value;
1167 * will be called once with a NULL value at the end
1168 * @param iter_cls closure for iter
1171 sqlite_plugin_iter_all_now (void *cls,
1173 PluginIterator iter,
1176 static struct GNUNET_TIME_Absolute zero;
1177 struct Plugin *plugin = cls;
1178 struct NextContext *nc;
1181 if (sq_prepare (plugin->dbh,
1182 "SELECT size,type,prio,anonLevel,expire,hash,value,_ROWID_ FROM gn080",
1183 &stmt) != SQLITE_OK)
1185 LOG_SQLITE (plugin, NULL,
1186 GNUNET_ERROR_TYPE_ERROR |
1187 GNUNET_ERROR_TYPE_BULK, "sqlite3_prepare");
1188 iter (iter_cls, NULL, NULL, 0, NULL, 0, 0, 0, zero, 0);
1191 nc = GNUNET_malloc (sizeof(struct NextContext));
1192 nc->plugin = plugin;
1194 nc->iter_cls = iter_cls;
1196 nc->prep = &all_next_prepare;
1197 nc->prep_cls = NULL;
1198 sqlite_next_request (nc, GNUNET_NO);
1202 struct GetNextContext
1209 GNUNET_HashCode key;
1210 GNUNET_HashCode vhash;
1215 get_next_prepare (void *cls,
1216 struct NextContext *nc)
1218 struct GetNextContext *gnc = cls;
1225 sqlite3_finalize (gnc->stmt);
1226 return GNUNET_SYSERR;
1228 if (nc->count == gnc->total)
1230 if (nc->count + gnc->off == gnc->total)
1233 limit_off = gnc->off;
1237 sqlite3_reset (nc->stmt);
1238 ret = sqlite3_bind_blob (nc->stmt,
1241 sizeof (GNUNET_HashCode),
1243 if ((gnc->have_vhash) && (ret == SQLITE_OK))
1244 ret = sqlite3_bind_blob (nc->stmt,
1247 sizeof (GNUNET_HashCode), SQLITE_TRANSIENT);
1248 if ((gnc->type != 0) && (ret == SQLITE_OK))
1249 ret = sqlite3_bind_int (nc->stmt, sqoff++, gnc->type);
1250 if (ret == SQLITE_OK)
1251 ret = sqlite3_bind_int64 (nc->stmt, sqoff++, nc->last_rowid + 1);
1252 if (ret == SQLITE_OK)
1253 ret = sqlite3_bind_int (nc->stmt, sqoff++, limit_off);
1254 if (ret != SQLITE_OK)
1255 return GNUNET_SYSERR;
1256 if (SQLITE_ROW != sqlite3_step (nc->stmt))
1263 * Iterate over the results for a particular key
1266 * @param cls closure
1267 * @param key maybe NULL (to match all entries)
1268 * @param vhash hash of the value, maybe NULL (to
1269 * match all values that have the right key).
1270 * Note that for DBlocks there is no difference
1271 * betwen key and vhash, but for other blocks
1273 * @param type entries of which type are relevant?
1274 * Use 0 for any type.
1275 * @param iter function to call on each matching value;
1276 * will be called once with a NULL value at the end
1277 * @param iter_cls closure for iter
1280 sqlite_plugin_get (void *cls,
1281 const GNUNET_HashCode * key,
1282 const GNUNET_HashCode * vhash,
1284 PluginIterator iter, void *iter_cls)
1286 static struct GNUNET_TIME_Absolute zero;
1287 struct Plugin *plugin = cls;
1288 struct GetNextContext *gpc;
1289 struct NextContext *nc;
1296 GNUNET_assert (iter != NULL);
1299 sqlite_plugin_iter_low_priority (cls, type, iter, iter_cls);
1302 GNUNET_snprintf (scratch, 256,
1303 "SELECT count(*) FROM gn080 WHERE hash=:1%s%s",
1304 vhash == NULL ? "" : " AND vhash=:2",
1305 type == 0 ? "" : (vhash ==
1306 NULL) ? " AND type=:2" : " AND type=:3");
1307 if (sq_prepare (plugin->dbh, scratch, &stmt) != SQLITE_OK)
1309 LOG_SQLITE (plugin, NULL,
1310 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, "sqlite_prepare");
1311 iter (iter_cls, NULL, NULL, 0, NULL, 0, 0, 0, zero, 0);
1315 ret = sqlite3_bind_blob (stmt,
1317 key, sizeof (GNUNET_HashCode), SQLITE_TRANSIENT);
1318 if ((vhash != NULL) && (ret == SQLITE_OK))
1319 ret = sqlite3_bind_blob (stmt,
1322 sizeof (GNUNET_HashCode), SQLITE_TRANSIENT);
1323 if ((type != 0) && (ret == SQLITE_OK))
1324 ret = sqlite3_bind_int (stmt, sqoff++, type);
1325 if (SQLITE_OK != ret)
1327 LOG_SQLITE (plugin, NULL,
1328 GNUNET_ERROR_TYPE_ERROR, "sqlite_bind");
1329 sqlite3_reset (stmt);
1330 sqlite3_finalize (stmt);
1331 iter (iter_cls, NULL, NULL, 0, NULL, 0, 0, 0, zero, 0);
1334 ret = sqlite3_step (stmt);
1335 if (ret != SQLITE_ROW)
1337 LOG_SQLITE (plugin, NULL,
1338 GNUNET_ERROR_TYPE_ERROR| GNUNET_ERROR_TYPE_BULK,
1340 sqlite3_reset (stmt);
1341 sqlite3_finalize (stmt);
1342 iter (iter_cls, NULL, NULL, 0, NULL, 0, 0, 0, zero, 0);
1345 total = sqlite3_column_int (stmt, 0);
1346 sqlite3_reset (stmt);
1347 sqlite3_finalize (stmt);
1350 iter (iter_cls, NULL, NULL, 0, NULL, 0, 0, 0, zero, 0);
1354 GNUNET_snprintf (scratch, 256,
1355 "SELECT size, type, prio, anonLevel, expire, hash, value, _ROWID_ "
1356 "FROM gn080 WHERE hash=:1%s%s AND _ROWID_ >= :%d "
1357 "ORDER BY _ROWID_ ASC LIMIT 1 OFFSET :d",
1358 vhash == NULL ? "" : " AND vhash=:2",
1359 type == 0 ? "" : (vhash ==
1360 NULL) ? " AND type=:2" : " AND type=:3",
1362 if (sq_prepare (plugin->dbh, scratch, &stmt) != SQLITE_OK)
1364 LOG_SQLITE (plugin, NULL,
1365 GNUNET_ERROR_TYPE_ERROR |
1366 GNUNET_ERROR_TYPE_BULK, "sqlite_prepare");
1367 iter (iter_cls, NULL, NULL, 0, NULL, 0, 0, 0, zero, 0);
1370 nc = GNUNET_malloc (sizeof(struct NextContext) +
1371 sizeof(struct GetNextContext));
1372 nc->plugin = plugin;
1374 nc->iter_cls = iter_cls;
1376 gpc = (struct GetNextContext*) &nc[1];
1380 gpc->stmt = stmt; /* alias used for freeing at the end! */
1383 gpc->have_vhash = GNUNET_YES;
1384 gpc->vhash = *vhash;
1386 gpc->off = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, total);
1387 nc->prep = &get_next_prepare;
1389 sqlite_next_request (nc, GNUNET_NO);
1397 sqlite_plugin_drop (void *cls)
1399 struct Plugin *plugin = cls;
1400 plugin->drop_on_shutdown = GNUNET_YES;
1405 * Callback function to process statistic values.
1407 * @param cls closure
1408 * @param subsystem name of subsystem that created the statistic
1409 * @param name the name of the datum
1410 * @param value the current value
1411 * @param is_persistent GNUNET_YES if the value is persistent, GNUNET_NO if not
1412 * @return GNUNET_OK to continue, GNUNET_SYSERR to abort iteration
1415 process_stat_in (void *cls,
1416 const char *subsystem,
1418 unsigned long long value,
1421 struct Plugin *plugin = cls;
1422 plugin->payload += value;
1428 * Entry point for the plugin.
1431 libgnunet_plugin_datastore_sqlite_init (void *cls)
1433 static struct Plugin plugin;
1434 struct GNUNET_DATASTORE_PluginEnvironment *env = cls;
1435 struct GNUNET_DATASTORE_PluginFunctions *api;
1437 if (plugin.env != NULL)
1438 return NULL; /* can only initialize once! */
1439 memset (&plugin, 0, sizeof(struct Plugin));
1441 plugin.statistics = GNUNET_STATISTICS_create (env->sched,
1444 GNUNET_STATISTICS_get (plugin.statistics,
1447 GNUNET_TIME_UNIT_MINUTES,
1452 database_setup (env->cfg, &plugin))
1454 database_shutdown (&plugin);
1457 api = GNUNET_malloc (sizeof (struct GNUNET_DATASTORE_PluginFunctions));
1459 api->get_size = &sqlite_plugin_get_size;
1460 api->put = &sqlite_plugin_put;
1461 api->next_request = &sqlite_next_request;
1462 api->get = &sqlite_plugin_get;
1463 api->update = &sqlite_plugin_update;
1464 api->iter_low_priority = &sqlite_plugin_iter_low_priority;
1465 api->iter_zero_anonymity = &sqlite_plugin_iter_zero_anonymity;
1466 api->iter_ascending_expiration = &sqlite_plugin_iter_ascending_expiration;
1467 api->iter_migration_order = &sqlite_plugin_iter_migration_order;
1468 api->iter_all_now = &sqlite_plugin_iter_all_now;
1469 api->drop = &sqlite_plugin_drop;
1470 GNUNET_log_from (GNUNET_ERROR_TYPE_INFO,
1471 "sqlite", _("Sqlite database running\n"));
1477 * Exit point from the plugin.
1480 libgnunet_plugin_datastore_sqlite_done (void *cls)
1483 struct GNUNET_DATASTORE_PluginFunctions *api = cls;
1484 struct Plugin *plugin = api->cls;
1487 if (plugin->drop_on_shutdown)
1488 fn = GNUNET_strdup (plugin->fn);
1489 database_shutdown (plugin);
1491 plugin->payload = 0;
1495 if (0 != UNLINK(fn))
1496 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING,
1504 /* end of plugin_datastore_sqlite.c */