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 * Expiration time of the last value visited.
485 struct GNUNET_TIME_Absolute lastExpiration;
488 * Priority of the last value visited.
490 unsigned int lastPriority;
493 * Number of results processed so far.
498 * Set to GNUNET_YES if we must stop now.
505 * Function invoked on behalf of a "PluginIterator"
506 * asking the database plugin to call the iterator
507 * with the next item.
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).
517 sqlite_next_request (void *next_cls,
520 static struct GNUNET_TIME_Absolute zero;
521 struct NextContext * nc= next_cls;
522 struct Plugin *plugin = nc->plugin;
523 unsigned long long rowid;
528 unsigned int priority;
529 unsigned int anonymity;
530 struct GNUNET_TIME_Absolute expiration;
531 const GNUNET_HashCode *key;
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,
539 (SQLITE_ROW != sqlite3_step (nc->stmt)) )
542 nc->iter (nc->iter_cls,
543 NULL, NULL, 0, NULL, 0, 0, 0,
545 nc->prep (nc->prep_cls, NULL);
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))
556 GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING,
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");
565 "DELETE FROM gn080 WHERE NOT LENGTH(hash) = ?",
566 &stmtd) != SQLITE_OK)
568 LOG_SQLITE (nc->plugin, NULL,
569 GNUNET_ERROR_TYPE_ERROR |
570 GNUNET_ERROR_TYPE_BULK,
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");
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);
598 ret = nc->iter (nc->iter_cls,
608 if (ret == GNUNET_SYSERR)
610 nc->end_it = GNUNET_YES;
613 if ( (ret == GNUNET_NO) &&
614 (GNUNET_OK == delete_by_rowid (plugin, rowid)) )
616 plugin->payload -= (size + GNUNET_DATASTORE_ENTRY_OVERHEAD);
618 if (plugin->lastSync >= MAX_STAT_SYNC_LAG)
625 * Store an item in the datastore.
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
639 sqlite_plugin_put (void *cls,
640 const GNUNET_HashCode * key,
646 struct GNUNET_TIME_Absolute expiration,
649 struct Plugin *plugin = cls;
652 GNUNET_HashCode vhash;
655 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
657 "Storing in database block with type %u/key `%s'/priority %u/expiration %llu.\n",
661 GNUNET_TIME_absolute_get_remaining (expiration).value);
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)) ||
671 sqlite3_bind_blob (stmt, 6, key, sizeof (GNUNET_HashCode),
672 SQLITE_TRANSIENT)) ||
674 sqlite3_bind_blob (stmt, 7, &vhash, sizeof (GNUNET_HashCode),
677 sqlite3_bind_blob (stmt, 8, data, size,
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;
688 n = sqlite3_step (stmt);
689 if (n != SQLITE_DONE)
691 if (n == SQLITE_BUSY)
693 LOG_SQLITE (plugin, msg,
694 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, "sqlite3_step");
695 sqlite3_reset (stmt);
699 LOG_SQLITE (plugin, msg,
700 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, "sqlite3_step");
701 sqlite3_reset (stmt);
702 return GNUNET_SYSERR;
704 if (SQLITE_OK != sqlite3_reset (stmt))
705 LOG_SQLITE (plugin, NULL,
706 GNUNET_ERROR_TYPE_ERROR |
707 GNUNET_ERROR_TYPE_BULK, "sqlite3_reset");
709 plugin->payload += size + GNUNET_DATASTORE_ENTRY_OVERHEAD;
710 if (plugin->lastSync >= MAX_STAT_SYNC_LAG)
717 * Update the priority for a particular key in the datastore. If
718 * the expiration time in value is different than the time found in
719 * the datastore, the higher value should be kept. For the
720 * anonymity level, the lower value is to be used. The specified
721 * priority should be added to the existing priority, ignoring the
724 * Note that it is possible for multiple values to match this put.
725 * In that case, all of the respective values are updated.
727 * @param uid unique identifier of the datum
728 * @param delta by how much should the priority
729 * change? If priority + delta < 0 the
730 * priority should be set to 0 (never go
732 * @param expire new expiration time should be the
733 * MAX of any existing expiration time and
735 * @param msg set to an error message
736 * @return GNUNET_OK on success
739 sqlite_plugin_update (void *cls,
741 int delta, struct GNUNET_TIME_Absolute expire,
744 struct Plugin *plugin = cls;
747 sqlite3_bind_int (plugin->updPrio, 1, delta);
748 sqlite3_bind_int64 (plugin->updPrio, 2, expire.value);
749 sqlite3_bind_int64 (plugin->updPrio, 3, uid);
750 n = sqlite3_step (plugin->updPrio);
752 LOG_SQLITE (plugin, msg,
753 GNUNET_ERROR_TYPE_WARNING | GNUNET_ERROR_TYPE_BULK,
757 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
761 sqlite3_reset (plugin->updPrio);
763 if (n == SQLITE_BUSY)
765 return n == SQLITE_OK ? GNUNET_OK : GNUNET_SYSERR;
771 sqlite3_stmt *stmt_1;
772 sqlite3_stmt *stmt_2;
776 int limit_nonanonymous;
783 iter_next_prepare (void *cls,
784 struct NextContext *nc)
786 struct IterContext *ic = cls;
787 struct Plugin *plugin = nc->plugin;
792 sqlite3_finalize (ic->stmt_1);
793 sqlite3_finalize (ic->stmt_2);
794 return GNUNET_SYSERR;
798 sqlite3_bind_int (ic->stmt_1, 1, nc->lastPriority);
799 sqlite3_bind_int (ic->stmt_2, 1, nc->lastPriority);
803 sqlite3_bind_int64 (ic->stmt_1, 1, nc->lastExpiration.value);
804 sqlite3_bind_int64 (ic->stmt_2, 1, nc->lastExpiration.value);
806 sqlite3_bind_blob (ic->stmt_1, 2,
808 sizeof (GNUNET_HashCode),
810 if (SQLITE_ROW == (ret = sqlite3_step (ic->stmt_1)))
812 nc->stmt = ic->stmt_1;
815 if (ret != SQLITE_DONE)
817 LOG_SQLITE (plugin, NULL,
818 GNUNET_ERROR_TYPE_ERROR |
819 GNUNET_ERROR_TYPE_BULK,
821 return GNUNET_SYSERR;
823 if (SQLITE_OK != sqlite3_reset (ic->stmt_1))
824 LOG_SQLITE (plugin, NULL,
825 GNUNET_ERROR_TYPE_ERROR |
826 GNUNET_ERROR_TYPE_BULK,
828 if (SQLITE_ROW == (ret = sqlite3_step (ic->stmt_2)))
830 nc->stmt = ic->stmt_2;
833 if (ret != SQLITE_DONE)
835 LOG_SQLITE (plugin, NULL,
836 GNUNET_ERROR_TYPE_ERROR |
837 GNUNET_ERROR_TYPE_BULK,
839 return GNUNET_SYSERR;
841 if (SQLITE_OK != sqlite3_reset (ic->stmt_2))
842 LOG_SQLITE (plugin, NULL,
843 GNUNET_ERROR_TYPE_ERROR |
844 GNUNET_ERROR_TYPE_BULK,
851 * Call a method for each key in the database and
852 * call the callback method on it.
854 * @param type entries of which type should be considered?
855 * @param iter function to call on each matching value;
856 * will be called once with a NULL value at the end
857 * @param iter_cls closure for iter
858 * @return the number of results processed,
859 * GNUNET_SYSERR on error
862 basic_iter (struct Plugin *plugin,
867 int limit_nonanonymous,
868 const char *stmt_str_1,
869 const char *stmt_str_2,
873 static struct GNUNET_TIME_Absolute zero;
874 struct NextContext *nc;
875 struct IterContext *ic;
876 sqlite3_stmt *stmt_1;
877 sqlite3_stmt *stmt_2;
879 if (sq_prepare (plugin->dbh, stmt_str_1, &stmt_1) != SQLITE_OK)
881 LOG_SQLITE (plugin, NULL,
882 GNUNET_ERROR_TYPE_ERROR |
883 GNUNET_ERROR_TYPE_BULK, "sqlite3_prepare");
884 iter (iter_cls, NULL, NULL, 0, NULL, 0, 0, 0, zero, 0);
887 if (sq_prepare (plugin->dbh, stmt_str_2, &stmt_2) != SQLITE_OK)
889 LOG_SQLITE (plugin, NULL,
890 GNUNET_ERROR_TYPE_ERROR |
891 GNUNET_ERROR_TYPE_BULK, "sqlite3_prepare");
892 sqlite3_finalize (stmt_1);
893 iter (iter_cls, NULL, NULL, 0, NULL, 0, 0, 0, zero, 0);
896 nc = GNUNET_malloc (sizeof(struct NextContext) +
897 sizeof(struct IterContext));
900 nc->iter_cls = iter_cls;
902 ic = (struct IterContext*) &nc[1];
907 ic->is_prio = is_prio;
908 ic->is_migr = is_migr;
909 ic->limit_nonanonymous = limit_nonanonymous;
910 nc->prep = &iter_next_prepare;
914 nc->lastPriority = 0;
915 nc->lastExpiration.value = 0;
916 memset (&ic->key, 0, sizeof (GNUNET_HashCode));
920 nc->lastPriority = 0x7FFFFFFF;
921 nc->lastExpiration.value = 0x7FFFFFFFFFFFFFFFLL;
922 memset (&ic->key, 255, sizeof (GNUNET_HashCode));
924 sqlite_next_request (nc, GNUNET_NO);
929 * Select a subset of the items in the datastore and call
930 * the given iterator for each of them.
932 * @param type entries of which type should be considered?
933 * Use 0 for any type.
934 * @param iter function to call on each matching value;
935 * will be called once with a NULL value at the end
936 * @param iter_cls closure for iter
939 sqlite_plugin_iter_low_priority (void *cls,
946 GNUNET_YES, GNUNET_YES,
947 GNUNET_NO, GNUNET_NO,
948 SELECT_IT_LOW_PRIORITY_1,
949 SELECT_IT_LOW_PRIORITY_2,
955 * Select a subset of the items in the datastore and call
956 * the given iterator for each of them.
958 * @param type entries of which type should be considered?
959 * Use 0 for any type.
960 * @param iter function to call on each matching value;
961 * will be called once with a NULL value at the end
962 * @param iter_cls closure for iter
965 sqlite_plugin_iter_zero_anonymity (void *cls,
972 GNUNET_NO, GNUNET_YES,
973 GNUNET_NO, GNUNET_YES,
974 SELECT_IT_NON_ANONYMOUS_1,
975 SELECT_IT_NON_ANONYMOUS_2,
982 * Select a subset of the items in the datastore and call
983 * the given iterator for each of them.
985 * @param type entries of which type should be considered?
986 * Use 0 for any type.
987 * @param iter function to call on each matching value;
988 * will be called once with a NULL value at the end
989 * @param iter_cls closure for iter
992 sqlite_plugin_iter_ascending_expiration (void *cls,
997 struct GNUNET_TIME_Absolute now;
1001 now = GNUNET_TIME_absolute_get ();
1002 GNUNET_asprintf (&q1, SELECT_IT_EXPIRATION_TIME_1,
1004 GNUNET_asprintf (&q2, SELECT_IT_EXPIRATION_TIME_2,
1008 GNUNET_YES, GNUNET_NO,
1009 GNUNET_NO, GNUNET_NO,
1018 * Select a subset of the items in the datastore and call
1019 * the given iterator for each of them.
1021 * @param type entries of which type should be considered?
1022 * Use 0 for any type.
1023 * @param iter function to call on each matching value;
1024 * will be called once with a NULL value at the end
1025 * @param iter_cls closure for iter
1028 sqlite_plugin_iter_migration_order (void *cls,
1030 PluginIterator iter,
1033 struct GNUNET_TIME_Absolute now;
1036 now = GNUNET_TIME_absolute_get ();
1037 GNUNET_asprintf (&q, SELECT_IT_MIGRATION_ORDER_2,
1041 GNUNET_NO, GNUNET_NO,
1042 GNUNET_YES, GNUNET_NO,
1043 SELECT_IT_MIGRATION_ORDER_1,
1052 * Select a subset of the items in the datastore and call
1053 * the given iterator for each of them.
1055 * @param type entries of which type should be considered?
1056 * Use 0 for any type.
1057 * @param iter function to call on each matching value;
1058 * will be called once with a NULL value at the end
1059 * @param iter_cls closure for iter
1062 sqlite_plugin_iter_all_now (void *cls,
1064 PluginIterator iter,
1067 static struct GNUNET_TIME_Absolute zero;
1068 iter (iter_cls, NULL, NULL, 0, NULL, 0, 0, 0, zero, 0);
1072 struct GetNextContext
1079 GNUNET_HashCode key;
1080 GNUNET_HashCode vhash;
1085 get_next_prepare (void *cls,
1086 struct NextContext *nc)
1088 struct GetNextContext *gnc = cls;
1095 sqlite3_finalize (gnc->stmt);
1096 return GNUNET_SYSERR;
1098 if (nc->count == gnc->total)
1100 if (nc->count + gnc->off == gnc->total)
1103 limit_off = gnc->off;
1107 ret = sqlite3_bind_blob (nc->stmt,
1110 sizeof (GNUNET_HashCode),
1112 if ((gnc->have_vhash) && (ret == SQLITE_OK))
1113 ret = sqlite3_bind_blob (nc->stmt,
1116 sizeof (GNUNET_HashCode), SQLITE_TRANSIENT);
1117 if ((gnc->type != 0) && (ret == SQLITE_OK))
1118 ret = sqlite3_bind_int (nc->stmt, sqoff++, gnc->type);
1119 if (ret == SQLITE_OK)
1120 ret = sqlite3_bind_int64 (nc->stmt, sqoff++, nc->last_rowid + 1);
1121 if (ret == SQLITE_OK)
1122 ret = sqlite3_bind_int (nc->stmt, sqoff++, limit_off);
1123 if (ret != SQLITE_OK)
1124 return GNUNET_SYSERR;
1125 if (SQLITE_ROW != sqlite3_step (nc->stmt))
1132 * Iterate over the results for a particular key
1135 * @param cls closure
1136 * @param key maybe NULL (to match all entries)
1137 * @param vhash hash of the value, maybe NULL (to
1138 * match all values that have the right key).
1139 * Note that for DBlocks there is no difference
1140 * betwen key and vhash, but for other blocks
1142 * @param type entries of which type are relevant?
1143 * Use 0 for any type.
1144 * @param iter function to call on each matching value;
1145 * will be called once with a NULL value at the end
1146 * @param iter_cls closure for iter
1149 sqlite_plugin_get (void *cls,
1150 const GNUNET_HashCode * key,
1151 const GNUNET_HashCode * vhash,
1153 PluginIterator iter, void *iter_cls)
1155 static struct GNUNET_TIME_Absolute zero;
1156 struct Plugin *plugin = cls;
1157 struct GetNextContext *gpc;
1158 struct NextContext *nc;
1165 GNUNET_assert (iter != NULL);
1168 sqlite_plugin_iter_low_priority (cls, type, iter, iter_cls);
1171 GNUNET_snprintf (scratch, 256,
1172 "SELECT count(*) FROM gn080 WHERE hash=:1%s%s",
1173 vhash == NULL ? "" : " AND vhash=:2",
1174 type == 0 ? "" : (vhash ==
1175 NULL) ? " AND type=:2" : " AND type=:3");
1176 if (sq_prepare (plugin->dbh, scratch, &stmt) != SQLITE_OK)
1178 LOG_SQLITE (plugin, NULL,
1179 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, "sqlite_prepare");
1180 iter (iter_cls, NULL, NULL, 0, NULL, 0, 0, 0, zero, 0);
1184 ret = sqlite3_bind_blob (stmt,
1186 key, sizeof (GNUNET_HashCode), SQLITE_TRANSIENT);
1187 if ((vhash != NULL) && (ret == SQLITE_OK))
1188 ret = sqlite3_bind_blob (stmt,
1191 sizeof (GNUNET_HashCode), SQLITE_TRANSIENT);
1192 if ((type != 0) && (ret == SQLITE_OK))
1193 ret = sqlite3_bind_int (stmt, sqoff++, type);
1194 if (SQLITE_OK != ret)
1196 LOG_SQLITE (plugin, NULL,
1197 GNUNET_ERROR_TYPE_ERROR, "sqlite_bind");
1198 sqlite3_reset (stmt);
1199 sqlite3_finalize (stmt);
1200 iter (iter_cls, NULL, NULL, 0, NULL, 0, 0, 0, zero, 0);
1203 ret = sqlite3_step (stmt);
1204 if (ret != SQLITE_ROW)
1206 LOG_SQLITE (plugin, NULL,
1207 GNUNET_ERROR_TYPE_ERROR| GNUNET_ERROR_TYPE_BULK,
1209 sqlite3_reset (stmt);
1210 sqlite3_finalize (stmt);
1211 iter (iter_cls, NULL, NULL, 0, NULL, 0, 0, 0, zero, 0);
1214 total = sqlite3_column_int (stmt, 0);
1215 sqlite3_reset (stmt);
1216 sqlite3_finalize (stmt);
1219 iter (iter_cls, NULL, NULL, 0, NULL, 0, 0, 0, zero, 0);
1223 GNUNET_snprintf (scratch, 256,
1224 "SELECT size, type, prio, anonLevel, expire, hash, value, _ROWID_ "
1225 "FROM gn080 WHERE hash=:1%s%s AND _ROWID_ >= :%d "
1226 "ORDER BY _ROWID_ ASC LIMIT 1 OFFSET :d",
1227 vhash == NULL ? "" : " AND vhash=:2",
1228 type == 0 ? "" : (vhash ==
1229 NULL) ? " AND type=:2" : " AND type=:3",
1231 if (sq_prepare (plugin->dbh, scratch, &stmt) != SQLITE_OK)
1233 LOG_SQLITE (plugin, NULL,
1234 GNUNET_ERROR_TYPE_ERROR |
1235 GNUNET_ERROR_TYPE_BULK, "sqlite_prepare");
1236 iter (iter_cls, NULL, NULL, 0, NULL, 0, 0, 0, zero, 0);
1239 nc = GNUNET_malloc (sizeof(struct NextContext) +
1240 sizeof(struct GetNextContext));
1241 nc->plugin = plugin;
1243 nc->iter_cls = iter_cls;
1245 gpc = (struct GetNextContext*) &nc[1];
1249 gpc->stmt = stmt; /* alias used for freeing at the end! */
1252 gpc->have_vhash = GNUNET_YES;
1253 gpc->vhash = *vhash;
1255 gpc->off = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, total);
1256 nc->prep = &get_next_prepare;
1258 sqlite_next_request (nc, GNUNET_NO);
1266 sqlite_plugin_drop (void *cls)
1268 struct Plugin *plugin = cls;
1269 plugin->drop_on_shutdown = GNUNET_YES;
1274 * Callback function to process statistic values.
1276 * @param cls closure
1277 * @param subsystem name of subsystem that created the statistic
1278 * @param name the name of the datum
1279 * @param value the current value
1280 * @param is_persistent GNUNET_YES if the value is persistent, GNUNET_NO if not
1281 * @return GNUNET_OK to continue, GNUNET_SYSERR to abort iteration
1284 process_stat_in (void *cls,
1285 const char *subsystem,
1287 unsigned long long value,
1290 struct Plugin *plugin = cls;
1291 plugin->payload += value;
1297 * Entry point for the plugin.
1300 libgnunet_plugin_datastore_sqlite_init (void *cls)
1302 static struct Plugin plugin;
1303 struct GNUNET_DATASTORE_PluginEnvironment *env = cls;
1304 struct GNUNET_DATASTORE_PluginFunctions *api;
1306 if (plugin.env != NULL)
1307 return NULL; /* can only initialize once! */
1308 memset (&plugin, 0, sizeof(struct Plugin));
1310 plugin.statistics = GNUNET_STATISTICS_create (env->sched,
1313 GNUNET_STATISTICS_get (plugin.statistics,
1316 GNUNET_TIME_UNIT_MINUTES,
1321 database_setup (env->cfg, &plugin))
1323 database_shutdown (&plugin);
1326 api = GNUNET_malloc (sizeof (struct GNUNET_DATASTORE_PluginFunctions));
1328 api->get_size = &sqlite_plugin_get_size;
1329 api->put = &sqlite_plugin_put;
1330 api->next_request = &sqlite_next_request;
1331 api->get = &sqlite_plugin_get;
1332 api->update = &sqlite_plugin_update;
1333 api->iter_low_priority = &sqlite_plugin_iter_low_priority;
1334 api->iter_zero_anonymity = &sqlite_plugin_iter_zero_anonymity;
1335 api->iter_ascending_expiration = &sqlite_plugin_iter_ascending_expiration;
1336 api->iter_migration_order = &sqlite_plugin_iter_migration_order;
1337 api->iter_all_now = &sqlite_plugin_iter_all_now;
1338 api->drop = &sqlite_plugin_drop;
1339 GNUNET_log_from (GNUNET_ERROR_TYPE_INFO,
1340 "sqlite", _("Sqlite database running\n"));
1346 * Exit point from the plugin.
1349 libgnunet_plugin_datastore_sqlite_done (void *cls)
1352 struct GNUNET_DATASTORE_PluginFunctions *api = cls;
1353 struct Plugin *plugin = api->cls;
1356 if (plugin->drop_on_shutdown)
1357 fn = GNUNET_strdup (plugin->fn);
1358 database_shutdown (plugin);
1360 plugin->payload = 0;
1364 if (0 != UNLINK(fn))
1365 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING,
1373 /* end of plugin_datastore_sqlite.c */