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 3, 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 "plugin_datastore.h"
31 #define DEBUG_SQLITE GNUNET_NO
35 * Log an error message at log-level 'level' that indicates
36 * a failure of the command 'cmd' on file 'filename'
37 * with the message given by strerror(errno).
39 #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 at %s:%u with error: %s"), cmd, __FILE__, __LINE__, sqlite3_errmsg(db->dbh)); } while(0)
41 #define SELECT_IT_LOW_PRIORITY_1 \
42 "SELECT size,type,prio,anonLevel,expire,hash,value,_ROWID_ FROM gn080 WHERE (prio = ? AND hash > ?) "\
43 "ORDER BY hash ASC LIMIT 1"
45 #define SELECT_IT_LOW_PRIORITY_2 \
46 "SELECT size,type,prio,anonLevel,expire,hash,value,_ROWID_ FROM gn080 WHERE (prio > ?) "\
47 "ORDER BY prio ASC, hash ASC LIMIT 1"
49 #define SELECT_IT_NON_ANONYMOUS_1 \
50 "SELECT size,type,prio,anonLevel,expire,hash,value,_ROWID_ FROM gn080 WHERE (prio = ? AND hash < ? AND anonLevel = 0 AND expire > %llu) "\
51 " ORDER BY hash DESC LIMIT 1"
53 #define SELECT_IT_NON_ANONYMOUS_2 \
54 "SELECT size,type,prio,anonLevel,expire,hash,value,_ROWID_ FROM gn080 WHERE (prio < ? AND anonLevel = 0 AND expire > %llu)"\
55 " ORDER BY prio DESC, hash DESC LIMIT 1"
57 #define SELECT_IT_EXPIRATION_TIME_1 \
58 "SELECT size,type,prio,anonLevel,expire,hash,value,_ROWID_ FROM gn080 WHERE (expire = ? AND hash > ?) "\
59 " ORDER BY hash ASC LIMIT 1"
61 #define SELECT_IT_EXPIRATION_TIME_2 \
62 "SELECT size,type,prio,anonLevel,expire,hash,value,_ROWID_ FROM gn080 WHERE (expire > ?) "\
63 " ORDER BY expire ASC, hash ASC LIMIT 1"
65 #define SELECT_IT_MIGRATION_ORDER_1 \
66 "SELECT size,type,prio,anonLevel,expire,hash,value,_ROWID_ FROM gn080 WHERE (expire = ? AND hash < ?) "\
67 " ORDER BY hash DESC LIMIT 1"
69 #define SELECT_IT_MIGRATION_ORDER_2 \
70 "SELECT size,type,prio,anonLevel,expire,hash,value,_ROWID_ FROM gn080 WHERE (expire < ? AND expire > %llu) "\
71 " ORDER BY expire DESC, hash DESC LIMIT 1"
74 * After how many ms "busy" should a DB operation fail for good?
75 * A low value makes sure that we are more responsive to requests
76 * (especially PUTs). A high value guarantees a higher success
77 * rate (SELECTs in iterate can take several seconds despite LIMIT=1).
79 * The default value of 250ms should ensure that users do not experience
80 * huge latencies while at the same time allowing operations to succeed
81 * with reasonable probability.
83 #define BUSY_TIMEOUT_MS 250
88 * Context for all functions in this plugin.
93 * Our execution environment.
95 struct GNUNET_DATASTORE_PluginEnvironment *env;
103 * Native SQLite database handle.
108 * Precompiled SQL for update.
110 sqlite3_stmt *updPrio;
113 * Precompiled SQL for insertion.
115 sqlite3_stmt *insertContent;
118 * Closure of the 'next_task' (must be freed if 'next_task' is cancelled).
120 struct NextContext *next_task_nc;
123 * Pending task with scheduler for running the next request.
125 GNUNET_SCHEDULER_TaskIdentifier next_task;
128 * Should the database be dropped on shutdown?
130 int drop_on_shutdown;
136 * @brief Prepare a SQL statement
138 * @param dbh handle to the database
139 * @param zSql SQL statement, UTF-8 encoded
140 * @param ppStmt set to the prepared statement
141 * @return 0 on success
144 sq_prepare (sqlite3 * dbh, const char *zSql,
145 sqlite3_stmt ** ppStmt)
148 return sqlite3_prepare_v2 (dbh,
150 strlen (zSql), ppStmt, (const char **) &dummy);
155 * Create our database indices.
157 * @param dbh handle to the database
160 create_indices (sqlite3 * dbh)
164 "CREATE INDEX idx_hash ON gn080 (hash)", NULL, NULL, NULL);
166 "CREATE INDEX idx_hash_vhash ON gn080 (hash,vhash)", NULL,
168 sqlite3_exec (dbh, "CREATE INDEX idx_prio ON gn080 (prio)", NULL, NULL,
170 sqlite3_exec (dbh, "CREATE INDEX idx_expire ON gn080 (expire)", NULL, NULL,
172 sqlite3_exec (dbh, "CREATE INDEX idx_comb3 ON gn080 (prio,anonLevel)", NULL,
174 sqlite3_exec (dbh, "CREATE INDEX idx_comb4 ON gn080 (prio,hash,anonLevel)",
176 sqlite3_exec (dbh, "CREATE INDEX idx_comb7 ON gn080 (expire,hash)", NULL,
183 #define CHECK(a) GNUNET_break(a)
187 #define ENULL_DEFINED 1
188 #define CHECK(a) if (! a) { GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "%s\n", e); sqlite3_free(e); }
195 * Initialize the database connections and associated
196 * data structures (create tables and indices
197 * as needed as well).
199 * @param cfg our configuration
200 * @param plugin the plugin context (state for this module)
201 * @return GNUNET_OK on success
204 database_setup (const struct GNUNET_CONFIGURATION_Handle *cfg,
205 struct Plugin *plugin)
214 GNUNET_CONFIGURATION_get_value_filename (cfg,
219 GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR,
221 _("Option `%s' in section `%s' missing in configuration!\n"),
224 return GNUNET_SYSERR;
226 if (GNUNET_OK != GNUNET_DISK_file_test (afsdir))
228 if (GNUNET_OK != GNUNET_DISK_directory_create_for_file (afsdir))
231 GNUNET_free (afsdir);
232 return GNUNET_SYSERR;
234 /* database is new or got deleted, reset payload to zero! */
235 plugin->env->duc (plugin->env->cls, 0);
237 plugin->fn = GNUNET_STRINGS_to_utf8 (afsdir, strlen (afsdir),
239 nl_langinfo (CODESET)
241 "UTF-8" /* good luck */
244 GNUNET_free (afsdir);
246 /* Open database and precompile statements */
247 if (sqlite3_open (plugin->fn, &plugin->dbh) != SQLITE_OK)
249 GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR,
251 _("Unable to initialize SQLite: %s.\n"),
252 sqlite3_errmsg (plugin->dbh));
253 return GNUNET_SYSERR;
256 sqlite3_exec (plugin->dbh,
257 "PRAGMA temp_store=MEMORY", NULL, NULL, ENULL));
259 sqlite3_exec (plugin->dbh,
260 "PRAGMA synchronous=OFF", NULL, NULL, ENULL));
262 sqlite3_exec (plugin->dbh,
263 "PRAGMA auto_vacuum=INCREMENTAL", NULL, NULL, ENULL));
265 sqlite3_exec (plugin->dbh,
266 "PRAGMA count_changes=OFF", NULL, NULL, ENULL));
268 sqlite3_exec (plugin->dbh,
269 "PRAGMA page_size=4092", NULL, NULL, ENULL));
271 CHECK (SQLITE_OK == sqlite3_busy_timeout (plugin->dbh, BUSY_TIMEOUT_MS));
274 /* We have to do it here, because otherwise precompiling SQL might fail */
276 sq_prepare (plugin->dbh,
277 "SELECT 1 FROM sqlite_master WHERE tbl_name = 'gn080'",
279 if ( (sqlite3_step (stmt) == SQLITE_DONE) &&
280 (sqlite3_exec (plugin->dbh,
281 "CREATE TABLE gn080 ("
282 " size INT4 NOT NULL DEFAULT 0,"
283 " type INT4 NOT NULL DEFAULT 0,"
284 " prio INT4 NOT NULL DEFAULT 0,"
285 " anonLevel INT4 NOT NULL DEFAULT 0,"
286 " expire INT8 NOT NULL DEFAULT 0,"
287 " hash TEXT NOT NULL DEFAULT '',"
288 " vhash TEXT NOT NULL DEFAULT '',"
289 " value BLOB NOT NULL DEFAULT '')", NULL, NULL,
290 NULL) != SQLITE_OK) )
292 LOG_SQLITE (plugin, NULL,
293 GNUNET_ERROR_TYPE_ERROR,
295 sqlite3_finalize (stmt);
296 return GNUNET_SYSERR;
298 sqlite3_finalize (stmt);
299 create_indices (plugin->dbh);
302 sq_prepare (plugin->dbh,
303 "SELECT 1 FROM sqlite_master WHERE tbl_name = 'gn071'",
305 if ( (sqlite3_step (stmt) == SQLITE_DONE) &&
306 (sqlite3_exec (plugin->dbh,
307 "CREATE TABLE gn071 ("
308 " key TEXT NOT NULL DEFAULT '',"
309 " value INTEGER NOT NULL DEFAULT 0)", NULL, NULL,
310 NULL) != SQLITE_OK) )
312 LOG_SQLITE (plugin, NULL,
313 GNUNET_ERROR_TYPE_ERROR, "sqlite3_exec");
314 sqlite3_finalize (stmt);
315 return GNUNET_SYSERR;
317 sqlite3_finalize (stmt);
319 if ((sq_prepare (plugin->dbh,
320 "UPDATE gn080 SET prio = prio + ?, expire = MAX(expire,?) WHERE "
322 &plugin->updPrio) != SQLITE_OK) ||
323 (sq_prepare (plugin->dbh,
324 "INSERT INTO gn080 (size, type, prio, "
325 "anonLevel, expire, hash, vhash, value) VALUES "
326 "(?, ?, ?, ?, ?, ?, ?, ?)",
327 &plugin->insertContent) != SQLITE_OK))
329 LOG_SQLITE (plugin, NULL,
330 GNUNET_ERROR_TYPE_ERROR, "precompiling");
331 return GNUNET_SYSERR;
338 * Shutdown database connection and associate data
340 * @param plugin the plugin context (state for this module)
343 database_shutdown (struct Plugin *plugin)
345 if (plugin->updPrio != NULL)
346 sqlite3_finalize (plugin->updPrio);
347 if (plugin->insertContent != NULL)
348 sqlite3_finalize (plugin->insertContent);
349 sqlite3_close (plugin->dbh);
350 GNUNET_free_non_null (plugin->fn);
355 * Delete the database entry with the given
358 * @param plugin the plugin context (state for this module)
359 * @param rid the ID of the row to delete
362 delete_by_rowid (struct Plugin* plugin,
363 unsigned long long rid)
367 if (sq_prepare (plugin->dbh,
368 "DELETE FROM gn080 WHERE _ROWID_ = ?", &stmt) != SQLITE_OK)
370 LOG_SQLITE (plugin, NULL,
371 GNUNET_ERROR_TYPE_ERROR |
372 GNUNET_ERROR_TYPE_BULK, "sq_prepare");
373 return GNUNET_SYSERR;
375 sqlite3_bind_int64 (stmt, 1, rid);
376 if (SQLITE_DONE != sqlite3_step (stmt))
378 LOG_SQLITE (plugin, NULL,
379 GNUNET_ERROR_TYPE_ERROR |
380 GNUNET_ERROR_TYPE_BULK, "sqlite3_step");
381 sqlite3_finalize (stmt);
382 return GNUNET_SYSERR;
384 sqlite3_finalize (stmt);
390 * Context for the universal iterator.
395 * Type of a function that will prepare
396 * the next iteration.
399 * @param nc the next context; NULL for the last
400 * call which gives the callback a chance to
401 * clean up the closure
402 * @return GNUNET_OK on success, GNUNET_NO if there are
403 * no more values, GNUNET_SYSERR on error
405 typedef int (*PrepareFunction)(void *cls,
406 struct NextContext *nc);
410 * Context we keep for the "next request" callback.
417 struct Plugin *plugin;
420 * Function to call on the next value.
430 * Function to call to prepare the next
433 PrepareFunction prep;
441 * Statement that the iterator will get the data
442 * from (updated or set by prep).
447 * Row ID of the last result.
449 unsigned long long last_rowid;
452 * Key of the last result.
454 GNUNET_HashCode lastKey;
457 * Expiration time of the last value visited.
459 struct GNUNET_TIME_Absolute lastExpiration;
462 * Priority of the last value visited.
464 unsigned int lastPriority;
467 * Number of results processed so far.
472 * Set to GNUNET_YES if we must stop now.
479 * Continuation of "sqlite_next_request".
481 * @param cls the next context
482 * @param tc the task context (unused)
485 sqlite_next_request_cont (void *cls,
486 const struct GNUNET_SCHEDULER_TaskContext *tc)
488 struct NextContext * nc = cls;
489 struct Plugin *plugin;
490 unsigned long long rowid;
495 unsigned int priority;
496 unsigned int anonymity;
497 struct GNUNET_TIME_Absolute expiration;
498 const GNUNET_HashCode *key;
502 plugin->next_task = GNUNET_SCHEDULER_NO_TASK;
503 plugin->next_task_nc = NULL;
504 if ( (GNUNET_YES == nc->end_it) ||
505 (GNUNET_OK != (nc->prep(nc->prep_cls,
509 nc->iter (nc->iter_cls,
510 NULL, NULL, 0, NULL, 0, 0, 0,
511 GNUNET_TIME_UNIT_ZERO_ABS, 0);
512 nc->prep (nc->prep_cls, NULL);
517 rowid = sqlite3_column_int64 (nc->stmt, 7);
518 nc->last_rowid = rowid;
519 type = sqlite3_column_int (nc->stmt, 1);
520 size = sqlite3_column_bytes (nc->stmt, 6);
521 if (sqlite3_column_bytes (nc->stmt, 5) != sizeof (GNUNET_HashCode))
523 GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING,
525 _("Invalid data in database. Trying to fix (by deletion).\n"));
526 if (SQLITE_OK != sqlite3_reset (nc->stmt))
527 LOG_SQLITE (nc->plugin, NULL,
528 GNUNET_ERROR_TYPE_ERROR |
529 GNUNET_ERROR_TYPE_BULK, "sqlite3_reset");
532 "DELETE FROM gn080 WHERE NOT LENGTH(hash) = ?",
533 &stmtd) != SQLITE_OK)
535 LOG_SQLITE (nc->plugin, NULL,
536 GNUNET_ERROR_TYPE_ERROR |
537 GNUNET_ERROR_TYPE_BULK,
542 if (SQLITE_OK != sqlite3_bind_int (stmtd, 1, sizeof (GNUNET_HashCode)))
543 LOG_SQLITE (nc->plugin, NULL,
544 GNUNET_ERROR_TYPE_ERROR |
545 GNUNET_ERROR_TYPE_BULK, "sqlite3_bind_int");
546 if (SQLITE_DONE != sqlite3_step (stmtd))
547 LOG_SQLITE (nc->plugin, NULL,
548 GNUNET_ERROR_TYPE_ERROR |
549 GNUNET_ERROR_TYPE_BULK, "sqlite3_step");
550 if (SQLITE_OK != sqlite3_finalize (stmtd))
551 LOG_SQLITE (nc->plugin, NULL,
552 GNUNET_ERROR_TYPE_ERROR |
553 GNUNET_ERROR_TYPE_BULK, "sqlite3_finalize");
557 priority = sqlite3_column_int (nc->stmt, 2);
558 anonymity = sqlite3_column_int (nc->stmt, 3);
559 expiration.value = sqlite3_column_int64 (nc->stmt, 4);
560 key = sqlite3_column_blob (nc->stmt, 5);
561 nc->lastPriority = priority;
562 nc->lastExpiration = expiration;
563 memcpy (&nc->lastKey, key, sizeof(GNUNET_HashCode));
564 data = sqlite3_column_blob (nc->stmt, 6);
566 ret = nc->iter (nc->iter_cls,
576 if (ret == GNUNET_SYSERR)
578 nc->end_it = GNUNET_YES;
582 if (ret == GNUNET_NO)
583 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
585 "Asked to remove entry %llu (%u bytes)\n",
586 (unsigned long long) rowid,
587 size + GNUNET_DATASTORE_ENTRY_OVERHEAD);
589 if ( (ret == GNUNET_NO) &&
590 (GNUNET_OK == delete_by_rowid (plugin, rowid)) )
592 plugin->env->duc (plugin->env->cls,
593 - (size + GNUNET_DATASTORE_ENTRY_OVERHEAD));
595 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
597 "Removed entry %llu (%u bytes)\n",
598 (unsigned long long) rowid,
599 size + GNUNET_DATASTORE_ENTRY_OVERHEAD);
606 * Function invoked on behalf of a "PluginIterator"
607 * asking the database plugin to call the iterator
608 * with the next item.
610 * @param next_cls whatever argument was given
611 * to the PluginIterator as "next_cls".
612 * @param end_it set to GNUNET_YES if we
613 * should terminate the iteration early
614 * (iterator should be still called once more
615 * to signal the end of the iteration).
618 sqlite_next_request (void *next_cls,
621 struct NextContext * nc= next_cls;
623 if (GNUNET_YES == end_it)
624 nc->end_it = GNUNET_YES;
625 nc->plugin->next_task_nc = nc;
626 nc->plugin->next_task = GNUNET_SCHEDULER_add_now (nc->plugin->env->sched,
627 &sqlite_next_request_cont,
634 * Store an item in the datastore.
637 * @param key key for the item
638 * @param size number of bytes in data
639 * @param data content stored
640 * @param type type of the content
641 * @param priority priority of the content
642 * @param anonymity anonymity-level for the content
643 * @param expiration expiration time for the content
644 * @param msg set to an error message
645 * @return GNUNET_OK on success
648 sqlite_plugin_put (void *cls,
649 const GNUNET_HashCode * key,
652 enum GNUNET_BLOCK_Type type,
655 struct GNUNET_TIME_Absolute expiration,
658 struct Plugin *plugin = cls;
661 GNUNET_HashCode vhash;
664 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
666 "Storing in database block with type %u/key `%s'/priority %u/expiration %llu (%lld).\n",
670 (unsigned long long) GNUNET_TIME_absolute_get_remaining (expiration).value,
671 (long long) expiration.value);
673 GNUNET_CRYPTO_hash (data, size, &vhash);
674 stmt = plugin->insertContent;
675 if ((SQLITE_OK != sqlite3_bind_int (stmt, 1, size)) ||
676 (SQLITE_OK != sqlite3_bind_int (stmt, 2, type)) ||
677 (SQLITE_OK != sqlite3_bind_int (stmt, 3, priority)) ||
678 (SQLITE_OK != sqlite3_bind_int (stmt, 4, anonymity)) ||
679 (SQLITE_OK != sqlite3_bind_int64 (stmt, 5, expiration.value)) ||
681 sqlite3_bind_blob (stmt, 6, key, sizeof (GNUNET_HashCode),
682 SQLITE_TRANSIENT)) ||
684 sqlite3_bind_blob (stmt, 7, &vhash, sizeof (GNUNET_HashCode),
687 sqlite3_bind_blob (stmt, 8, data, size,
692 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, "sqlite3_bind_XXXX");
693 if (SQLITE_OK != sqlite3_reset (stmt))
694 LOG_SQLITE (plugin, NULL,
695 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, "sqlite3_reset");
696 return GNUNET_SYSERR;
698 n = sqlite3_step (stmt);
699 if (n != SQLITE_DONE)
701 if (n == SQLITE_BUSY)
703 LOG_SQLITE (plugin, msg,
704 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, "sqlite3_step");
705 sqlite3_reset (stmt);
709 LOG_SQLITE (plugin, msg,
710 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, "sqlite3_step");
711 sqlite3_reset (stmt);
712 database_shutdown (plugin);
713 database_setup (plugin->env->cfg,
715 return GNUNET_SYSERR;
717 if (SQLITE_OK != sqlite3_reset (stmt))
718 LOG_SQLITE (plugin, NULL,
719 GNUNET_ERROR_TYPE_ERROR |
720 GNUNET_ERROR_TYPE_BULK, "sqlite3_reset");
721 plugin->env->duc (plugin->env->cls,
722 size + GNUNET_DATASTORE_ENTRY_OVERHEAD);
724 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
726 "Stored new entry (%u bytes)\n",
727 size + GNUNET_DATASTORE_ENTRY_OVERHEAD);
734 * Update the priority for a particular key in the datastore. If
735 * the expiration time in value is different than the time found in
736 * the datastore, the higher value should be kept. For the
737 * anonymity level, the lower value is to be used. The specified
738 * priority should be added to the existing priority, ignoring the
741 * Note that it is possible for multiple values to match this put.
742 * In that case, all of the respective values are updated.
744 * @param cls the plugin context (state for this module)
745 * @param uid unique identifier of the datum
746 * @param delta by how much should the priority
747 * change? If priority + delta < 0 the
748 * priority should be set to 0 (never go
750 * @param expire new expiration time should be the
751 * MAX of any existing expiration time and
753 * @param msg set to an error message
754 * @return GNUNET_OK on success
757 sqlite_plugin_update (void *cls,
759 int delta, struct GNUNET_TIME_Absolute expire,
762 struct Plugin *plugin = cls;
765 sqlite3_bind_int (plugin->updPrio, 1, delta);
766 sqlite3_bind_int64 (plugin->updPrio, 2, expire.value);
767 sqlite3_bind_int64 (plugin->updPrio, 3, uid);
768 n = sqlite3_step (plugin->updPrio);
769 if (n != SQLITE_DONE)
770 LOG_SQLITE (plugin, msg,
771 GNUNET_ERROR_TYPE_WARNING | GNUNET_ERROR_TYPE_BULK,
775 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
779 sqlite3_reset (plugin->updPrio);
781 if (n == SQLITE_BUSY)
783 return n == SQLITE_DONE ? GNUNET_OK : GNUNET_SYSERR;
788 * Internal context for an iteration.
795 sqlite3_stmt *stmt_1;
800 sqlite3_stmt *stmt_2;
820 int limit_nonanonymous;
823 * Desired type for blocks returned by this iterator.
825 enum GNUNET_BLOCK_Type type;
830 * Prepare our SQL query to obtain the next record from the database.
832 * @param cls our "struct IterContext"
833 * @param nc NULL to terminate the iteration, otherwise our context for
834 * getting the next result.
835 * @return GNUNET_OK on success, GNUNET_NO if there are no more results,
836 * GNUNET_SYSERR on error (or end of iteration)
839 iter_next_prepare (void *cls,
840 struct NextContext *nc)
842 struct IterContext *ic = cls;
843 struct Plugin *plugin;
849 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
850 "Asked to clean up iterator state.\n");
852 sqlite3_finalize (ic->stmt_1);
853 sqlite3_finalize (ic->stmt_2);
854 return GNUNET_SYSERR;
856 sqlite3_reset (ic->stmt_1);
857 sqlite3_reset (ic->stmt_2);
862 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
863 "Restricting to results larger than the last priority %u\n",
866 sqlite3_bind_int (ic->stmt_1, 1, nc->lastPriority);
867 sqlite3_bind_int (ic->stmt_2, 1, nc->lastPriority);
872 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
873 "Restricting to results larger than the last expiration %llu\n",
874 (unsigned long long) nc->lastExpiration.value);
876 sqlite3_bind_int64 (ic->stmt_1, 1, nc->lastExpiration.value);
877 sqlite3_bind_int64 (ic->stmt_2, 1, nc->lastExpiration.value);
880 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
881 "Restricting to results larger than the last key `%s'\n",
882 GNUNET_h2s(&nc->lastKey));
884 sqlite3_bind_blob (ic->stmt_1, 2,
886 sizeof (GNUNET_HashCode),
888 if (SQLITE_ROW == (ret = sqlite3_step (ic->stmt_1)))
891 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
892 "Result found using iterator 1\n");
894 nc->stmt = ic->stmt_1;
897 if (ret != SQLITE_DONE)
899 LOG_SQLITE (plugin, NULL,
900 GNUNET_ERROR_TYPE_ERROR |
901 GNUNET_ERROR_TYPE_BULK,
903 return GNUNET_SYSERR;
905 if (SQLITE_OK != sqlite3_reset (ic->stmt_1))
906 LOG_SQLITE (plugin, NULL,
907 GNUNET_ERROR_TYPE_ERROR |
908 GNUNET_ERROR_TYPE_BULK,
910 if (SQLITE_ROW == (ret = sqlite3_step (ic->stmt_2)))
913 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
914 "Result found using iterator 2\n");
916 nc->stmt = ic->stmt_2;
919 if (ret != SQLITE_DONE)
921 LOG_SQLITE (plugin, NULL,
922 GNUNET_ERROR_TYPE_ERROR |
923 GNUNET_ERROR_TYPE_BULK,
925 return GNUNET_SYSERR;
927 if (SQLITE_OK != sqlite3_reset (ic->stmt_2))
928 LOG_SQLITE (plugin, NULL,
929 GNUNET_ERROR_TYPE_ERROR |
930 GNUNET_ERROR_TYPE_BULK,
933 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
934 "No result found using either iterator\n");
941 * Call a method for each key in the database and
942 * call the callback method on it.
944 * @param plugin our plugin context
945 * @param type entries of which type should be considered?
946 * @param is_asc are we iterating in ascending order?
947 * @param is_prio are we iterating by priority (otherwise by expiration)
948 * @param is_migr are we iterating in migration order?
949 * @param limit_nonanonymous are we restricting results to those with anonymity
951 * @param stmt_str_1 first SQL statement to execute
952 * @param stmt_str_2 SQL statement to execute to get "more" results (inner iteration)
953 * @param iter function to call on each matching value;
954 * will be called once with a NULL value at the end
955 * @param iter_cls closure for iter
958 basic_iter (struct Plugin *plugin,
959 enum GNUNET_BLOCK_Type type,
963 int limit_nonanonymous,
964 const char *stmt_str_1,
965 const char *stmt_str_2,
969 struct NextContext *nc;
970 struct IterContext *ic;
971 sqlite3_stmt *stmt_1;
972 sqlite3_stmt *stmt_2;
975 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
976 "At %llu, using queries `%s' and `%s'\n",
977 (unsigned long long) GNUNET_TIME_absolute_get ().value,
981 if (sq_prepare (plugin->dbh, stmt_str_1, &stmt_1) != SQLITE_OK)
983 LOG_SQLITE (plugin, NULL,
984 GNUNET_ERROR_TYPE_ERROR |
985 GNUNET_ERROR_TYPE_BULK, "sqlite3_prepare_v2");
986 iter (iter_cls, NULL, NULL, 0, NULL, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0);
989 if (sq_prepare (plugin->dbh, stmt_str_2, &stmt_2) != SQLITE_OK)
991 LOG_SQLITE (plugin, NULL,
992 GNUNET_ERROR_TYPE_ERROR |
993 GNUNET_ERROR_TYPE_BULK, "sqlite3_prepare_v2");
994 sqlite3_finalize (stmt_1);
995 iter (iter_cls, NULL, NULL, 0, NULL, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0);
998 nc = GNUNET_malloc (sizeof(struct NextContext) +
999 sizeof(struct IterContext));
1000 nc->plugin = plugin;
1002 nc->iter_cls = iter_cls;
1004 ic = (struct IterContext*) &nc[1];
1005 ic->stmt_1 = stmt_1;
1006 ic->stmt_2 = stmt_2;
1008 ic->is_asc = is_asc;
1009 ic->is_prio = is_prio;
1010 ic->is_migr = is_migr;
1011 ic->limit_nonanonymous = limit_nonanonymous;
1012 nc->prep = &iter_next_prepare;
1016 nc->lastPriority = 0;
1017 nc->lastExpiration.value = 0;
1018 memset (&nc->lastKey, 0, sizeof (GNUNET_HashCode));
1022 nc->lastPriority = 0x7FFFFFFF;
1023 nc->lastExpiration.value = 0x7FFFFFFFFFFFFFFFLL;
1024 memset (&nc->lastKey, 255, sizeof (GNUNET_HashCode));
1026 sqlite_next_request (nc, GNUNET_NO);
1031 * Select a subset of the items in the datastore and call
1032 * the given iterator for each of them.
1034 * @param cls our plugin context
1035 * @param type entries of which type should be considered?
1036 * Use 0 for any type.
1037 * @param iter function to call on each matching value;
1038 * will be called once with a NULL value at the end
1039 * @param iter_cls closure for iter
1042 sqlite_plugin_iter_low_priority (void *cls,
1043 enum GNUNET_BLOCK_Type type,
1044 PluginIterator iter,
1049 GNUNET_YES, GNUNET_YES,
1050 GNUNET_NO, GNUNET_NO,
1051 SELECT_IT_LOW_PRIORITY_1,
1052 SELECT_IT_LOW_PRIORITY_2,
1058 * Select a subset of the items in the datastore and call
1059 * the given iterator for each of them.
1061 * @param cls our plugin context
1062 * @param type entries of which type should be considered?
1063 * Use 0 for any type.
1064 * @param iter function to call on each matching value;
1065 * will be called once with a NULL value at the end
1066 * @param iter_cls closure for iter
1069 sqlite_plugin_iter_zero_anonymity (void *cls,
1070 enum GNUNET_BLOCK_Type type,
1071 PluginIterator iter,
1074 struct GNUNET_TIME_Absolute now;
1078 now = GNUNET_TIME_absolute_get ();
1079 GNUNET_asprintf (&q1, SELECT_IT_NON_ANONYMOUS_1,
1080 (unsigned long long) now.value);
1081 GNUNET_asprintf (&q2, SELECT_IT_NON_ANONYMOUS_2,
1082 (unsigned long long) now.value);
1085 GNUNET_NO, GNUNET_YES,
1086 GNUNET_NO, GNUNET_YES,
1097 * Select a subset of the items in the datastore and call
1098 * the given iterator for each of them.
1100 * @param cls our plugin context
1101 * @param type entries of which type should be considered?
1102 * Use 0 for any type.
1103 * @param iter function to call on each matching value;
1104 * will be called once with a NULL value at the end
1105 * @param iter_cls closure for iter
1108 sqlite_plugin_iter_ascending_expiration (void *cls,
1109 enum GNUNET_BLOCK_Type type,
1110 PluginIterator iter,
1113 struct GNUNET_TIME_Absolute now;
1117 now = GNUNET_TIME_absolute_get ();
1118 GNUNET_asprintf (&q1, SELECT_IT_EXPIRATION_TIME_1,
1119 (unsigned long long) 0*now.value);
1120 GNUNET_asprintf (&q2, SELECT_IT_EXPIRATION_TIME_2,
1121 (unsigned long long) 0*now.value);
1124 GNUNET_YES, GNUNET_NO,
1125 GNUNET_NO, GNUNET_NO,
1134 * Select a subset of the items in the datastore and call
1135 * the given iterator for each of them.
1137 * @param cls our plugin context
1138 * @param type entries of which type should be considered?
1139 * Use 0 for any type.
1140 * @param iter function to call on each matching value;
1141 * will be called once with a NULL value at the end
1142 * @param iter_cls closure for iter
1145 sqlite_plugin_iter_migration_order (void *cls,
1146 enum GNUNET_BLOCK_Type type,
1147 PluginIterator iter,
1150 struct GNUNET_TIME_Absolute now;
1153 now = GNUNET_TIME_absolute_get ();
1154 GNUNET_asprintf (&q, SELECT_IT_MIGRATION_ORDER_2,
1155 (unsigned long long) now.value);
1158 GNUNET_NO, GNUNET_NO,
1159 GNUNET_YES, GNUNET_NO,
1160 SELECT_IT_MIGRATION_ORDER_1,
1168 * Call sqlite using the already prepared query to get
1171 * @param cls not used
1172 * @param nc context with the prepared query
1173 * @return GNUNET_OK on success, GNUNET_SYSERR on error, GNUNET_NO if
1174 * there are no more results
1177 all_next_prepare (void *cls,
1178 struct NextContext *nc)
1180 struct Plugin *plugin;
1186 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1187 "Asked to clean up iterator state.\n");
1189 return GNUNET_SYSERR;
1191 plugin = nc->plugin;
1192 if (SQLITE_ROW == (ret = sqlite3_step (nc->stmt)))
1196 if (ret != SQLITE_DONE)
1198 LOG_SQLITE (plugin, NULL,
1199 GNUNET_ERROR_TYPE_ERROR |
1200 GNUNET_ERROR_TYPE_BULK,
1202 return GNUNET_SYSERR;
1209 * Select a subset of the items in the datastore and call
1210 * the given iterator for each of them.
1212 * @param cls our plugin context
1213 * @param type entries of which type should be considered?
1214 * Use 0 for any type.
1215 * @param iter function to call on each matching value;
1216 * will be called once with a NULL value at the end
1217 * @param iter_cls closure for iter
1220 sqlite_plugin_iter_all_now (void *cls,
1221 enum GNUNET_BLOCK_Type type,
1222 PluginIterator iter,
1225 struct Plugin *plugin = cls;
1226 struct NextContext *nc;
1229 if (sq_prepare (plugin->dbh,
1230 "SELECT size,type,prio,anonLevel,expire,hash,value,_ROWID_ FROM gn080",
1231 &stmt) != SQLITE_OK)
1233 LOG_SQLITE (plugin, NULL,
1234 GNUNET_ERROR_TYPE_ERROR |
1235 GNUNET_ERROR_TYPE_BULK, "sqlite3_prepare_v2");
1236 iter (iter_cls, NULL, NULL, 0, NULL, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0);
1239 nc = GNUNET_malloc (sizeof(struct NextContext));
1240 nc->plugin = plugin;
1242 nc->iter_cls = iter_cls;
1244 nc->prep = &all_next_prepare;
1245 nc->prep_cls = NULL;
1246 sqlite_next_request (nc, GNUNET_NO);
1253 struct GetNextContext
1284 GNUNET_HashCode key;
1289 GNUNET_HashCode vhash;
1297 * @param cls our "struct GetNextContext*"
1299 * @return GNUNET_YES if there are more results,
1300 * GNUNET_NO if there are no more results,
1301 * GNUNET_SYSERR on internal error
1304 get_next_prepare (void *cls,
1305 struct NextContext *nc)
1307 struct GetNextContext *gnc = cls;
1314 sqlite3_finalize (gnc->stmt);
1315 return GNUNET_SYSERR;
1317 if (nc->count == gnc->total)
1319 if (nc->count + gnc->off == gnc->total)
1322 limit_off = gnc->off;
1326 sqlite3_reset (nc->stmt);
1327 ret = sqlite3_bind_blob (nc->stmt,
1330 sizeof (GNUNET_HashCode),
1332 if ((gnc->have_vhash) && (ret == SQLITE_OK))
1333 ret = sqlite3_bind_blob (nc->stmt,
1336 sizeof (GNUNET_HashCode), SQLITE_TRANSIENT);
1337 if ((gnc->type != 0) && (ret == SQLITE_OK))
1338 ret = sqlite3_bind_int (nc->stmt, sqoff++, gnc->type);
1339 if (ret == SQLITE_OK)
1340 ret = sqlite3_bind_int64 (nc->stmt, sqoff++, nc->last_rowid + 1);
1341 if (ret == SQLITE_OK)
1342 ret = sqlite3_bind_int (nc->stmt, sqoff++, limit_off);
1343 if (ret != SQLITE_OK)
1344 return GNUNET_SYSERR;
1345 if (SQLITE_ROW != sqlite3_step (nc->stmt))
1352 * Iterate over the results for a particular key
1355 * @param cls closure
1356 * @param key maybe NULL (to match all entries)
1357 * @param vhash hash of the value, maybe NULL (to
1358 * match all values that have the right key).
1359 * Note that for DBlocks there is no difference
1360 * betwen key and vhash, but for other blocks
1362 * @param type entries of which type are relevant?
1363 * Use 0 for any type.
1364 * @param iter function to call on each matching value;
1365 * will be called once with a NULL value at the end
1366 * @param iter_cls closure for iter
1369 sqlite_plugin_get (void *cls,
1370 const GNUNET_HashCode * key,
1371 const GNUNET_HashCode * vhash,
1372 enum GNUNET_BLOCK_Type type,
1373 PluginIterator iter, void *iter_cls)
1375 struct Plugin *plugin = cls;
1376 struct GetNextContext *gpc;
1377 struct NextContext *nc;
1384 GNUNET_assert (iter != NULL);
1387 sqlite_plugin_iter_low_priority (cls, type, iter, iter_cls);
1390 GNUNET_snprintf (scratch, sizeof (scratch),
1391 "SELECT count(*) FROM gn080 WHERE hash=:1%s%s",
1392 vhash == NULL ? "" : " AND vhash=:2",
1393 type == 0 ? "" : (vhash ==
1394 NULL) ? " AND type=:2" : " AND type=:3");
1395 if (sq_prepare (plugin->dbh, scratch, &stmt) != SQLITE_OK)
1397 LOG_SQLITE (plugin, NULL,
1398 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, "sqlite_prepare");
1399 iter (iter_cls, NULL, NULL, 0, NULL, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0);
1403 ret = sqlite3_bind_blob (stmt,
1405 key, sizeof (GNUNET_HashCode), SQLITE_TRANSIENT);
1406 if ((vhash != NULL) && (ret == SQLITE_OK))
1407 ret = sqlite3_bind_blob (stmt,
1410 sizeof (GNUNET_HashCode), SQLITE_TRANSIENT);
1411 if ((type != 0) && (ret == SQLITE_OK))
1412 ret = sqlite3_bind_int (stmt, sqoff++, type);
1413 if (SQLITE_OK != ret)
1415 LOG_SQLITE (plugin, NULL,
1416 GNUNET_ERROR_TYPE_ERROR, "sqlite_bind");
1417 sqlite3_reset (stmt);
1418 sqlite3_finalize (stmt);
1419 iter (iter_cls, NULL, NULL, 0, NULL, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0);
1422 ret = sqlite3_step (stmt);
1423 if (ret != SQLITE_ROW)
1425 LOG_SQLITE (plugin, NULL,
1426 GNUNET_ERROR_TYPE_ERROR| GNUNET_ERROR_TYPE_BULK,
1428 sqlite3_reset (stmt);
1429 sqlite3_finalize (stmt);
1430 iter (iter_cls, NULL, NULL, 0, NULL, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0);
1433 total = sqlite3_column_int (stmt, 0);
1434 sqlite3_reset (stmt);
1435 sqlite3_finalize (stmt);
1438 iter (iter_cls, NULL, NULL, 0, NULL, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0);
1442 GNUNET_snprintf (scratch, sizeof (scratch),
1443 "SELECT size, type, prio, anonLevel, expire, hash, value, _ROWID_ "
1444 "FROM gn080 WHERE hash=:1%s%s AND _ROWID_ >= :%d "
1445 "ORDER BY _ROWID_ ASC LIMIT 1 OFFSET :d",
1446 vhash == NULL ? "" : " AND vhash=:2",
1447 type == 0 ? "" : (vhash ==
1448 NULL) ? " AND type=:2" : " AND type=:3",
1450 if (sq_prepare (plugin->dbh, scratch, &stmt) != SQLITE_OK)
1452 LOG_SQLITE (plugin, NULL,
1453 GNUNET_ERROR_TYPE_ERROR |
1454 GNUNET_ERROR_TYPE_BULK, "sqlite_prepare");
1455 iter (iter_cls, NULL, NULL, 0, NULL, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0);
1458 nc = GNUNET_malloc (sizeof(struct NextContext) +
1459 sizeof(struct GetNextContext));
1460 nc->plugin = plugin;
1462 nc->iter_cls = iter_cls;
1464 gpc = (struct GetNextContext*) &nc[1];
1468 gpc->stmt = stmt; /* alias used for freeing at the end! */
1471 gpc->have_vhash = GNUNET_YES;
1472 gpc->vhash = *vhash;
1474 gpc->off = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, total);
1475 nc->prep = &get_next_prepare;
1477 sqlite_next_request (nc, GNUNET_NO);
1484 * @param cls our plugin context
1487 sqlite_plugin_drop (void *cls)
1489 struct Plugin *plugin = cls;
1490 plugin->drop_on_shutdown = GNUNET_YES;
1494 static unsigned long long
1495 sqlite_plugin_get_size (void *cls)
1497 struct Plugin *plugin = cls;
1505 if (SQLITE_VERSION_NUMBER < 3006000)
1507 GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING,
1509 _("sqlite version to old to determine size, assuming zero\n"));
1513 sqlite3_exec (plugin->dbh,
1514 "VACUUM", NULL, NULL, ENULL));
1516 sqlite3_exec (plugin->dbh,
1517 "PRAGMA auto_vacuum=INCREMENTAL", NULL, NULL, ENULL));
1519 sq_prepare (plugin->dbh,
1520 "PRAGMA page_count",
1523 sqlite3_step (stmt))
1524 pages = sqlite3_column_int64 (stmt, 0);
1527 sqlite3_finalize (stmt);
1529 sq_prepare (plugin->dbh,
1532 CHECK (SQLITE_ROW ==
1533 sqlite3_step (stmt));
1534 page_size = sqlite3_column_int64 (stmt, 0);
1535 sqlite3_finalize (stmt);
1536 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1537 _("Using sqlite page utilization to estimate payload (%llu pages of size %llu bytes)\n"),
1538 (unsigned long long) pages,
1539 (unsigned long long) page_size);
1540 return pages * page_size;
1545 * Entry point for the plugin.
1547 * @param cls the "struct GNUNET_DATASTORE_PluginEnvironment*"
1548 * @return NULL on error, othrewise the plugin context
1551 libgnunet_plugin_datastore_sqlite_init (void *cls)
1553 static struct Plugin plugin;
1554 struct GNUNET_DATASTORE_PluginEnvironment *env = cls;
1555 struct GNUNET_DATASTORE_PluginFunctions *api;
1557 if (plugin.env != NULL)
1558 return NULL; /* can only initialize once! */
1559 memset (&plugin, 0, sizeof(struct Plugin));
1562 database_setup (env->cfg, &plugin))
1564 database_shutdown (&plugin);
1567 api = GNUNET_malloc (sizeof (struct GNUNET_DATASTORE_PluginFunctions));
1569 api->get_size = &sqlite_plugin_get_size;
1570 api->put = &sqlite_plugin_put;
1571 api->next_request = &sqlite_next_request;
1572 api->get = &sqlite_plugin_get;
1573 api->update = &sqlite_plugin_update;
1574 api->iter_low_priority = &sqlite_plugin_iter_low_priority;
1575 api->iter_zero_anonymity = &sqlite_plugin_iter_zero_anonymity;
1576 api->iter_ascending_expiration = &sqlite_plugin_iter_ascending_expiration;
1577 api->iter_migration_order = &sqlite_plugin_iter_migration_order;
1578 api->iter_all_now = &sqlite_plugin_iter_all_now;
1579 api->drop = &sqlite_plugin_drop;
1580 GNUNET_log_from (GNUNET_ERROR_TYPE_INFO,
1581 "sqlite", _("Sqlite database running\n"));
1587 * Exit point from the plugin.
1589 * @param cls the plugin context (as returned by "init")
1590 * @return always NULL
1593 libgnunet_plugin_datastore_sqlite_done (void *cls)
1596 struct GNUNET_DATASTORE_PluginFunctions *api = cls;
1597 struct Plugin *plugin = api->cls;
1599 if (plugin->next_task != GNUNET_SCHEDULER_NO_TASK)
1601 GNUNET_SCHEDULER_cancel (plugin->env->sched,
1603 plugin->next_task = GNUNET_SCHEDULER_NO_TASK;
1604 plugin->next_task_nc->prep (plugin->next_task_nc->prep_cls, NULL);
1605 GNUNET_free (plugin->next_task_nc);
1606 plugin->next_task_nc = NULL;
1609 if (plugin->drop_on_shutdown)
1610 fn = GNUNET_strdup (plugin->fn);
1611 database_shutdown (plugin);
1616 if (0 != UNLINK(fn))
1617 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING,
1625 /* end of plugin_datastore_sqlite.c */