2 * This file is part of GNUnet
3 * (C) 2009, 2011 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 "gnunet_datastore_plugin.h"
32 * Enable or disable logging debug messages.
34 #define DEBUG_SQLITE GNUNET_EXTRA_LOGGING
37 * We allocate items on the stack at times. To prevent a stack
38 * overflow, we impose a limit on the maximum size for the data per
39 * item. 64k should be enough.
41 #define MAX_ITEM_SIZE 65536
44 * After how many ms "busy" should a DB operation fail for good?
45 * A low value makes sure that we are more responsive to requests
46 * (especially PUTs). A high value guarantees a higher success
47 * rate (SELECTs in iterate can take several seconds despite LIMIT=1).
49 * The default value of 250ms should ensure that users do not experience
50 * huge latencies while at the same time allowing operations to succeed
51 * with reasonable probability.
53 #define BUSY_TIMEOUT_MS 250
57 * Log an error message at log-level 'level' that indicates
58 * a failure of the command 'cmd' on file 'filename'
59 * with the message given by strerror(errno).
61 #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)
66 * Context for all functions in this plugin.
71 * Our execution environment.
73 struct GNUNET_DATASTORE_PluginEnvironment *env;
81 * Native SQLite database handle.
86 * Precompiled SQL for deletion.
91 * Precompiled SQL for update.
93 sqlite3_stmt *updPrio;
96 * Get maximum repl value in database.
98 sqlite3_stmt *maxRepl;
101 * Precompiled SQL for replication decrement.
103 sqlite3_stmt *updRepl;
106 * Precompiled SQL for replication selection.
108 sqlite3_stmt *selRepl;
111 * Precompiled SQL for expiration selection.
113 sqlite3_stmt *selExpi;
116 * Precompiled SQL for expiration selection.
118 sqlite3_stmt *selZeroAnon;
121 * Precompiled SQL for insertion.
123 sqlite3_stmt *insertContent;
126 * Should the database be dropped on shutdown?
128 int drop_on_shutdown;
134 * @brief Prepare a SQL statement
136 * @param dbh handle to the database
137 * @param zSql SQL statement, UTF-8 encoded
138 * @param ppStmt set to the prepared statement
139 * @return 0 on success
142 sq_prepare (sqlite3 * dbh, const char *zSql, sqlite3_stmt ** ppStmt)
148 sqlite3_prepare_v2 (dbh, zSql, strlen (zSql), ppStmt,
149 (const char **) &dummy);
150 #if DEBUG_SQLITE && 0
151 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "sqlite",
152 "Prepared `%s' / %p: %d\n", zSql, *ppStmt, result);
159 * Create our database indices.
161 * @param dbh handle to the database
164 create_indices (sqlite3 * dbh)
168 sqlite3_exec (dbh, "CREATE INDEX IF NOT EXISTS idx_hash ON gn090 (hash)",
169 NULL, NULL, NULL)) ||
172 "CREATE INDEX IF NOT EXISTS idx_hash_vhash ON gn090 (hash,vhash)",
173 NULL, NULL, NULL)) ||
176 "CREATE INDEX IF NOT EXISTS idx_expire_repl ON gn090 (expire ASC,repl DESC)",
177 NULL, NULL, NULL)) ||
180 "CREATE INDEX IF NOT EXISTS idx_comb ON gn090 (anonLevel ASC,expire ASC,prio,type,hash)",
181 NULL, NULL, NULL)) ||
184 "CREATE INDEX IF NOT EXISTS idx_anon_type_hash ON gn090 (anonLevel ASC,type,hash)",
185 NULL, NULL, NULL)) ||
188 "CREATE INDEX IF NOT EXISTS idx_expire ON gn090 (expire ASC)",
189 NULL, NULL, NULL)) ||
192 "CREATE INDEX IF NOT EXISTS idx_repl_rvalue ON gn090 (repl,rvalue)",
193 NULL, NULL, NULL)) ||
196 "CREATE INDEX IF NOT EXISTS idx_repl ON gn090 (repl DESC)",
198 GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, "sqlite",
199 "Failed to create indices: %s\n", sqlite3_errmsg (dbh));
204 #define CHECK(a) GNUNET_break(a)
208 #define ENULL_DEFINED 1
209 #define CHECK(a) if (! a) { GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "%s\n", e); sqlite3_free(e); }
214 * Initialize the database connections and associated
215 * data structures (create tables and indices
216 * as needed as well).
218 * @param cfg our configuration
219 * @param plugin the plugin context (state for this module)
220 * @return GNUNET_OK on success
223 database_setup (const struct GNUNET_CONFIGURATION_Handle *cfg,
224 struct Plugin *plugin)
234 GNUNET_CONFIGURATION_get_value_filename (cfg, "datastore-sqlite",
235 "FILENAME", &afsdir))
237 GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, "sqlite",
239 ("Option `%s' in section `%s' missing in configuration!\n"),
240 "FILENAME", "datastore-sqlite");
241 return GNUNET_SYSERR;
243 if (GNUNET_OK != GNUNET_DISK_file_test (afsdir))
245 if (GNUNET_OK != GNUNET_DISK_directory_create_for_file (afsdir))
248 GNUNET_free (afsdir);
249 return GNUNET_SYSERR;
251 /* database is new or got deleted, reset payload to zero! */
252 plugin->env->duc (plugin->env->cls, 0);
256 GNUNET_STRINGS_to_utf8 (afsdir, strlen (afsdir), nl_langinfo (CODESET));
258 plugin->fn = GNUNET_STRINGS_to_utf8 (afsdir, strlen (afsdir), "UTF-8"); /* good luck */
260 GNUNET_free (afsdir);
262 /* Open database and precompile statements */
263 if (sqlite3_open (plugin->fn, &plugin->dbh) != SQLITE_OK)
265 GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, "sqlite",
266 _("Unable to initialize SQLite: %s.\n"),
267 sqlite3_errmsg (plugin->dbh));
268 return GNUNET_SYSERR;
271 sqlite3_exec (plugin->dbh, "PRAGMA temp_store=MEMORY", NULL, NULL,
274 sqlite3_exec (plugin->dbh, "PRAGMA synchronous=OFF", NULL, NULL,
277 sqlite3_exec (plugin->dbh, "PRAGMA legacy_file_format=OFF", NULL, NULL,
280 sqlite3_exec (plugin->dbh, "PRAGMA auto_vacuum=INCREMENTAL", NULL,
283 sqlite3_exec (plugin->dbh, "PRAGMA locking_mode=EXCLUSIVE", NULL, NULL,
286 sqlite3_exec (plugin->dbh, "PRAGMA count_changes=OFF", NULL, NULL,
289 sqlite3_exec (plugin->dbh, "PRAGMA page_size=4092", NULL, NULL,
292 CHECK (SQLITE_OK == sqlite3_busy_timeout (plugin->dbh, BUSY_TIMEOUT_MS));
295 /* We have to do it here, because otherwise precompiling SQL might fail */
297 sq_prepare (plugin->dbh,
298 "SELECT 1 FROM sqlite_master WHERE tbl_name = 'gn090'",
300 if ((sqlite3_step (stmt) == SQLITE_DONE) &&
303 "CREATE TABLE gn090 (" " repl INT4 NOT NULL DEFAULT 0,"
304 " type INT4 NOT NULL DEFAULT 0," " prio INT4 NOT NULL DEFAULT 0,"
305 " anonLevel INT4 NOT NULL DEFAULT 0,"
306 " expire INT8 NOT NULL DEFAULT 0," " rvalue INT8 NOT NULL,"
307 " hash TEXT NOT NULL DEFAULT ''," " vhash TEXT NOT NULL DEFAULT '',"
308 " value BLOB NOT NULL DEFAULT '')", NULL, NULL, NULL) != SQLITE_OK))
310 LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR, "sqlite3_exec");
311 sqlite3_finalize (stmt);
312 return GNUNET_SYSERR;
314 sqlite3_finalize (stmt);
315 create_indices (plugin->dbh);
320 "SET prio = prio + ?, expire = MAX(expire,?) WHERE _ROWID_ = ?",
321 &plugin->updPrio) != SQLITE_OK) ||
324 "UPDATE gn090 " "SET repl = MAX (0, repl - 1) WHERE _ROWID_ = ?",
325 &plugin->updRepl) != SQLITE_OK) ||
328 "SELECT type,prio,anonLevel,expire,hash,value,_ROWID_ " "FROM gn090 "
329 #if SQLITE_VERSION_NUMBER >= 3007000
330 "INDEXED BY idx_repl_rvalue "
332 "WHERE repl=?2 AND " " (rvalue>=?1 OR "
333 " NOT EXISTS (SELECT 1 FROM gn090 "
334 #if SQLITE_VERSION_NUMBER >= 3007000
335 "INDEXED BY idx_repl_rvalue "
337 "WHERE repl=?2 AND rvalue>=?1 LIMIT 1) ) "
338 "ORDER BY rvalue ASC LIMIT 1", &plugin->selRepl) != SQLITE_OK) ||
339 (sq_prepare (plugin->dbh, "SELECT MAX(repl) FROM gn090"
340 #if SQLITE_VERSION_NUMBER >= 3007000
341 " INDEXED BY idx_repl_rvalue"
343 "", &plugin->maxRepl) != SQLITE_OK) ||
346 "SELECT type,prio,anonLevel,expire,hash,value,_ROWID_ " "FROM gn090 "
347 #if SQLITE_VERSION_NUMBER >= 3007000
348 "INDEXED BY idx_expire "
350 "WHERE NOT EXISTS (SELECT 1 FROM gn090 WHERE expire < ?1 LIMIT 1) OR (expire < ?1) "
351 "ORDER BY expire ASC LIMIT 1", &plugin->selExpi) != SQLITE_OK) ||
354 "SELECT type,prio,anonLevel,expire,hash,value,_ROWID_ " "FROM gn090 "
355 #if SQLITE_VERSION_NUMBER >= 3007000
356 "INDEXED BY idx_anon_type_hash "
358 "WHERE (anonLevel = 0 AND type=?1) "
359 "ORDER BY hash DESC LIMIT 1 OFFSET ?2",
360 &plugin->selZeroAnon) != SQLITE_OK) ||
363 "INSERT INTO gn090 (repl, type, prio, anonLevel, expire, rvalue, hash, vhash, value) "
364 "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)",
365 &plugin->insertContent) != SQLITE_OK) ||
367 (plugin->dbh, "DELETE FROM gn090 WHERE _ROWID_ = ?",
368 &plugin->delRow) != SQLITE_OK))
370 LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR, "precompiling");
371 return GNUNET_SYSERR;
379 * Shutdown database connection and associate data
381 * @param plugin the plugin context (state for this module)
384 database_shutdown (struct Plugin *plugin)
388 #if SQLITE_VERSION_NUMBER >= 3007000
392 if (plugin->delRow != NULL)
393 sqlite3_finalize (plugin->delRow);
394 if (plugin->updPrio != NULL)
395 sqlite3_finalize (plugin->updPrio);
396 if (plugin->updRepl != NULL)
397 sqlite3_finalize (plugin->updRepl);
398 if (plugin->selRepl != NULL)
399 sqlite3_finalize (plugin->selRepl);
400 if (plugin->maxRepl != NULL)
401 sqlite3_finalize (plugin->maxRepl);
402 if (plugin->selExpi != NULL)
403 sqlite3_finalize (plugin->selExpi);
404 if (plugin->selZeroAnon != NULL)
405 sqlite3_finalize (plugin->selZeroAnon);
406 if (plugin->insertContent != NULL)
407 sqlite3_finalize (plugin->insertContent);
408 result = sqlite3_close (plugin->dbh);
409 #if SQLITE_VERSION_NUMBER >= 3007000
410 if (result == SQLITE_BUSY)
412 GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING, "sqlite",
414 ("Tried to close sqlite without finalizing all prepared statements.\n"));
415 stmt = sqlite3_next_stmt (plugin->dbh, NULL);
419 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "sqlite",
420 "Closing statement %p\n", stmt);
422 result = sqlite3_finalize (stmt);
424 if (result != SQLITE_OK)
425 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "sqlite",
426 "Failed to close statement %p: %d\n", stmt, result);
428 stmt = sqlite3_next_stmt (plugin->dbh, NULL);
430 result = sqlite3_close (plugin->dbh);
433 if (SQLITE_OK != result)
434 LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR, "sqlite3_close");
436 GNUNET_free_non_null (plugin->fn);
441 * Delete the database entry with the given
444 * @param plugin the plugin context (state for this module)
445 * @param rid the ID of the row to delete
448 delete_by_rowid (struct Plugin *plugin, unsigned long long rid)
450 if (SQLITE_OK != sqlite3_bind_int64 (plugin->delRow, 1, rid))
452 LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
453 "sqlite3_bind_XXXX");
454 if (SQLITE_OK != sqlite3_reset (plugin->delRow))
455 LOG_SQLITE (plugin, NULL,
456 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
458 return GNUNET_SYSERR;
460 if (SQLITE_DONE != sqlite3_step (plugin->delRow))
462 LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
464 if (SQLITE_OK != sqlite3_reset (plugin->delRow))
465 LOG_SQLITE (plugin, NULL,
466 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
468 return GNUNET_SYSERR;
470 if (SQLITE_OK != sqlite3_reset (plugin->delRow))
471 LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
478 * Store an item in the datastore.
481 * @param key key for the item
482 * @param size number of bytes in data
483 * @param data content stored
484 * @param type type of the content
485 * @param priority priority of the content
486 * @param anonymity anonymity-level for the content
487 * @param replication replication-level for the content
488 * @param expiration expiration time for the content
489 * @param msg set to an error message
490 * @return GNUNET_OK on success
493 sqlite_plugin_put (void *cls, const GNUNET_HashCode * key, uint32_t size,
494 const void *data, enum GNUNET_BLOCK_Type type,
495 uint32_t priority, uint32_t anonymity, uint32_t replication,
496 struct GNUNET_TIME_Absolute expiration, char **msg)
498 struct Plugin *plugin = cls;
502 GNUNET_HashCode vhash;
505 if (size > MAX_ITEM_SIZE)
506 return GNUNET_SYSERR;
508 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "sqlite",
509 "Storing in database block with type %u/key `%s'/priority %u/expiration in %llu ms (%lld).\n",
510 type, GNUNET_h2s (key), priority,
512 GNUNET_TIME_absolute_get_remaining (expiration).rel_value,
513 (long long) expiration.abs_value);
515 GNUNET_CRYPTO_hash (data, size, &vhash);
516 stmt = plugin->insertContent;
517 rvalue = GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK, UINT64_MAX);
518 if ((SQLITE_OK != sqlite3_bind_int (stmt, 1, replication)) ||
519 (SQLITE_OK != sqlite3_bind_int (stmt, 2, type)) ||
520 (SQLITE_OK != sqlite3_bind_int (stmt, 3, priority)) ||
521 (SQLITE_OK != sqlite3_bind_int (stmt, 4, anonymity)) ||
522 (SQLITE_OK != sqlite3_bind_int64 (stmt, 5, expiration.abs_value)) ||
523 (SQLITE_OK != sqlite3_bind_int64 (stmt, 6, rvalue)) ||
525 sqlite3_bind_blob (stmt, 7, key, sizeof (GNUNET_HashCode),
526 SQLITE_TRANSIENT)) ||
528 sqlite3_bind_blob (stmt, 8, &vhash, sizeof (GNUNET_HashCode),
529 SQLITE_TRANSIENT)) ||
530 (SQLITE_OK != sqlite3_bind_blob (stmt, 9, data, size, SQLITE_TRANSIENT)))
532 LOG_SQLITE (plugin, msg, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
533 "sqlite3_bind_XXXX");
534 if (SQLITE_OK != sqlite3_reset (stmt))
535 LOG_SQLITE (plugin, NULL,
536 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
538 return GNUNET_SYSERR;
540 n = sqlite3_step (stmt);
544 plugin->env->duc (plugin->env->cls, size + GNUNET_DATASTORE_ENTRY_OVERHEAD);
546 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "sqlite",
547 "Stored new entry (%u bytes)\n",
548 size + GNUNET_DATASTORE_ENTRY_OVERHEAD);
554 LOG_SQLITE (plugin, msg, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
559 LOG_SQLITE (plugin, msg, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
561 if (SQLITE_OK != sqlite3_reset (stmt))
562 LOG_SQLITE (plugin, NULL,
563 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
565 database_shutdown (plugin);
566 database_setup (plugin->env->cfg, plugin);
567 return GNUNET_SYSERR;
569 if (SQLITE_OK != sqlite3_reset (stmt))
570 LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
577 * Update the priority for a particular key in the datastore. If
578 * the expiration time in value is different than the time found in
579 * the datastore, the higher value should be kept. For the
580 * anonymity level, the lower value is to be used. The specified
581 * priority should be added to the existing priority, ignoring the
584 * Note that it is possible for multiple values to match this put.
585 * In that case, all of the respective values are updated.
587 * @param cls the plugin context (state for this module)
588 * @param uid unique identifier of the datum
589 * @param delta by how much should the priority
590 * change? If priority + delta < 0 the
591 * priority should be set to 0 (never go
593 * @param expire new expiration time should be the
594 * MAX of any existing expiration time and
596 * @param msg set to an error message
597 * @return GNUNET_OK on success
600 sqlite_plugin_update (void *cls, uint64_t uid, int delta,
601 struct GNUNET_TIME_Absolute expire, char **msg)
603 struct Plugin *plugin = cls;
606 if ((SQLITE_OK != sqlite3_bind_int (plugin->updPrio, 1, delta)) ||
607 (SQLITE_OK != sqlite3_bind_int64 (plugin->updPrio, 2, expire.abs_value))
608 || (SQLITE_OK != sqlite3_bind_int64 (plugin->updPrio, 3, uid)))
610 LOG_SQLITE (plugin, msg, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
611 "sqlite3_bind_XXXX");
612 if (SQLITE_OK != sqlite3_reset (plugin->updPrio))
613 LOG_SQLITE (plugin, NULL,
614 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
616 return GNUNET_SYSERR;
619 n = sqlite3_step (plugin->updPrio);
620 if (SQLITE_OK != sqlite3_reset (plugin->updPrio))
621 LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
627 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "sqlite", "Block updated\n");
631 LOG_SQLITE (plugin, msg, GNUNET_ERROR_TYPE_WARNING | GNUNET_ERROR_TYPE_BULK,
635 LOG_SQLITE (plugin, msg, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
637 return GNUNET_SYSERR;
643 * Execute statement that gets a row and call the callback
644 * with the result. Resets the statement afterwards.
646 * @param plugin the plugin
647 * @param stmt the statement
648 * @param proc processor to call
649 * @param proc_cls closure for 'proc'
652 execute_get (struct Plugin *plugin, sqlite3_stmt * stmt,
653 PluginDatumProcessor proc, void *proc_cls)
656 struct GNUNET_TIME_Absolute expiration;
657 unsigned long long rowid;
661 n = sqlite3_step (stmt);
665 size = sqlite3_column_bytes (stmt, 5);
666 rowid = sqlite3_column_int64 (stmt, 6);
667 if (sqlite3_column_bytes (stmt, 4) != sizeof (GNUNET_HashCode))
669 GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING, "sqlite",
671 ("Invalid data in database. Trying to fix (by deletion).\n"));
672 if (SQLITE_OK != sqlite3_reset (stmt))
673 LOG_SQLITE (plugin, NULL,
674 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
676 if (GNUNET_OK == delete_by_rowid (plugin, rowid))
677 plugin->env->duc (plugin->env->cls,
678 -(size + GNUNET_DATASTORE_ENTRY_OVERHEAD));
681 expiration.abs_value = sqlite3_column_int64 (stmt, 3);
683 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "sqlite",
684 "Found reply in database with expiration %llu\n",
685 (unsigned long long) expiration.abs_value);
687 ret = proc (proc_cls, sqlite3_column_blob (stmt, 4) /* key */ ,
688 size, sqlite3_column_blob (stmt, 5) /* data */ ,
689 sqlite3_column_int (stmt, 0) /* type */ ,
690 sqlite3_column_int (stmt, 1) /* priority */ ,
691 sqlite3_column_int (stmt, 2) /* anonymity */ ,
693 if (SQLITE_OK != sqlite3_reset (stmt))
694 LOG_SQLITE (plugin, NULL,
695 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
697 if ((GNUNET_NO == ret) && (GNUNET_OK == delete_by_rowid (plugin, rowid)))
698 plugin->env->duc (plugin->env->cls,
699 -(size + GNUNET_DATASTORE_ENTRY_OVERHEAD));
702 /* database must be empty */
703 if (SQLITE_OK != sqlite3_reset (stmt))
704 LOG_SQLITE (plugin, NULL,
705 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
712 LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
714 if (SQLITE_OK != sqlite3_reset (stmt))
715 LOG_SQLITE (plugin, NULL,
716 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
719 database_shutdown (plugin);
720 database_setup (plugin->env->cfg, plugin);
723 if (SQLITE_OK != sqlite3_reset (stmt))
724 LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
726 proc (proc_cls, NULL, 0, NULL, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0);
732 * Select a subset of the items in the datastore and call
733 * the given processor for the item.
735 * @param cls our plugin context
736 * @param offset offset of the result (modulo num-results);
737 * specific ordering does not matter for the offset
738 * @param type entries of which type should be considered?
739 * Use 0 for any type.
740 * @param proc function to call on each matching value;
741 * will be called once with a NULL value at the end
742 * @param proc_cls closure for proc
745 sqlite_plugin_get_zero_anonymity (void *cls, uint64_t offset,
746 enum GNUNET_BLOCK_Type type,
747 PluginDatumProcessor proc, void *proc_cls)
749 struct Plugin *plugin = cls;
752 GNUNET_assert (type != GNUNET_BLOCK_TYPE_ANY);
753 stmt = plugin->selZeroAnon;
754 if ((SQLITE_OK != sqlite3_bind_int (stmt, 1, type)) ||
755 (SQLITE_OK != sqlite3_bind_int64 (stmt, 2, offset)))
757 LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
758 "sqlite3_bind_XXXX");
759 if (SQLITE_OK != sqlite3_reset (stmt))
760 LOG_SQLITE (plugin, NULL,
761 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
763 proc (proc_cls, NULL, 0, NULL, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0);
766 execute_get (plugin, stmt, proc, proc_cls);
772 * Get results for a particular key in the datastore.
775 * @param offset offset (mod count).
776 * @param key key to match, never NULL
777 * @param vhash hash of the value, maybe NULL (to
778 * match all values that have the right key).
779 * Note that for DBlocks there is no difference
780 * betwen key and vhash, but for other blocks
782 * @param type entries of which type are relevant?
783 * Use 0 for any type.
784 * @param proc function to call on each matching value;
785 * will be called once with a NULL value at the end
786 * @param proc_cls closure for proc
789 sqlite_plugin_get_key (void *cls, uint64_t offset, const GNUNET_HashCode * key,
790 const GNUNET_HashCode * vhash,
791 enum GNUNET_BLOCK_Type type, PluginDatumProcessor proc,
794 struct Plugin *plugin = cls;
802 GNUNET_assert (proc != NULL);
803 GNUNET_assert (key != NULL);
804 GNUNET_snprintf (scratch, sizeof (scratch),
805 "SELECT count(*) FROM gn090 WHERE hash=?%s%s",
806 vhash == NULL ? "" : " AND vhash=?",
807 type == 0 ? "" : " AND type=?");
808 if (sq_prepare (plugin->dbh, scratch, &stmt) != SQLITE_OK)
810 LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
812 proc (proc_cls, NULL, 0, NULL, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0);
817 sqlite3_bind_blob (stmt, sqoff++, key, sizeof (GNUNET_HashCode),
819 if ((vhash != NULL) && (ret == SQLITE_OK))
821 sqlite3_bind_blob (stmt, sqoff++, vhash, sizeof (GNUNET_HashCode),
823 if ((type != 0) && (ret == SQLITE_OK))
824 ret = sqlite3_bind_int (stmt, sqoff++, type);
825 if (SQLITE_OK != ret)
827 LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR, "sqlite_bind");
828 sqlite3_finalize (stmt);
829 proc (proc_cls, NULL, 0, NULL, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0);
832 ret = sqlite3_step (stmt);
833 if (ret != SQLITE_ROW)
835 LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
837 sqlite3_finalize (stmt);
838 proc (proc_cls, NULL, 0, NULL, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0);
841 total = sqlite3_column_int (stmt, 0);
842 sqlite3_finalize (stmt);
845 proc (proc_cls, NULL, 0, NULL, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0);
848 limit_off = (int) (offset % total);
851 GNUNET_snprintf (scratch, sizeof (scratch),
852 "SELECT type, prio, anonLevel, expire, hash, value, _ROWID_ "
853 "FROM gn090 WHERE hash=?%s%s "
854 "ORDER BY _ROWID_ ASC LIMIT 1 OFFSET ?",
855 vhash == NULL ? "" : " AND vhash=?",
856 type == 0 ? "" : " AND type=?");
857 if (sq_prepare (plugin->dbh, scratch, &stmt) != SQLITE_OK)
859 LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
861 proc (proc_cls, NULL, 0, NULL, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0);
866 sqlite3_bind_blob (stmt, sqoff++, key, sizeof (GNUNET_HashCode),
868 if ((vhash != NULL) && (ret == SQLITE_OK))
870 sqlite3_bind_blob (stmt, sqoff++, vhash, sizeof (GNUNET_HashCode),
872 if ((type != 0) && (ret == SQLITE_OK))
873 ret = sqlite3_bind_int (stmt, sqoff++, type);
874 if (ret == SQLITE_OK)
875 ret = sqlite3_bind_int64 (stmt, sqoff++, limit_off);
876 if (ret != SQLITE_OK)
878 LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
880 proc (proc_cls, NULL, 0, NULL, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0);
883 execute_get (plugin, stmt, proc, proc_cls);
884 sqlite3_finalize (stmt);
890 * Context for 'repl_proc' function.
896 * Function to call for the result (or the NULL).
898 PluginDatumProcessor proc;
911 * Yes if UID was set.
918 * Wrapper for the processor for 'sqlite_plugin_replication_get'.
919 * Decrements the replication counter and calls the original
923 * @param key key for the content
924 * @param size number of bytes in data
925 * @param data content stored
926 * @param type type of the content
927 * @param priority priority of the content
928 * @param anonymity anonymity-level for the content
929 * @param expiration expiration time for the content
930 * @param uid unique identifier for the datum;
931 * maybe 0 if no unique identifier is available
933 * @return GNUNET_OK for normal return,
934 * GNUNET_NO to delete the item
937 repl_proc (void *cls, const GNUNET_HashCode * key, uint32_t size,
938 const void *data, enum GNUNET_BLOCK_Type type, uint32_t priority,
939 uint32_t anonymity, struct GNUNET_TIME_Absolute expiration,
942 struct ReplCtx *rc = cls;
946 rc->proc (rc->proc_cls, key, size, data, type, priority, anonymity,
951 rc->have_uid = GNUNET_YES;
958 * Get a random item for replication. Returns a single random item
959 * from those with the highest replication counters. The item's
960 * replication counter is decremented by one IF it was positive before.
961 * Call 'proc' with all values ZERO or NULL if the datastore is empty.
964 * @param proc function to call the value (once only).
965 * @param proc_cls closure for proc
968 sqlite_plugin_get_replication (void *cls, PluginDatumProcessor proc,
971 struct Plugin *plugin = cls;
978 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "sqlite",
979 "Getting random block based on replication order.\n");
981 rc.have_uid = GNUNET_NO;
983 rc.proc_cls = proc_cls;
984 stmt = plugin->maxRepl;
985 if (SQLITE_ROW != sqlite3_step (stmt))
987 if (SQLITE_OK != sqlite3_reset (stmt))
988 LOG_SQLITE (plugin, NULL,
989 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
992 proc (proc_cls, NULL, 0, NULL, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0);
995 repl = sqlite3_column_int (stmt, 0);
996 if (SQLITE_OK != sqlite3_reset (stmt))
997 LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
999 stmt = plugin->selRepl;
1000 rvalue = GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK, UINT64_MAX);
1001 if (SQLITE_OK != sqlite3_bind_int64 (stmt, 1, rvalue))
1003 LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
1004 "sqlite3_bind_XXXX");
1005 if (SQLITE_OK != sqlite3_reset (stmt))
1006 LOG_SQLITE (plugin, NULL,
1007 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
1009 proc (proc_cls, NULL, 0, NULL, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0);
1012 if (SQLITE_OK != sqlite3_bind_int (stmt, 2, repl))
1014 LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
1015 "sqlite3_bind_XXXX");
1016 if (SQLITE_OK != sqlite3_reset (stmt))
1017 LOG_SQLITE (plugin, NULL,
1018 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
1020 proc (proc_cls, NULL, 0, NULL, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0);
1023 execute_get (plugin, stmt, &repl_proc, &rc);
1024 if (GNUNET_YES == rc.have_uid)
1026 if (SQLITE_OK != sqlite3_bind_int64 (plugin->updRepl, 1, rc.uid))
1028 LOG_SQLITE (plugin, NULL,
1029 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
1030 "sqlite3_bind_XXXX");
1031 if (SQLITE_OK != sqlite3_reset (plugin->updRepl))
1032 LOG_SQLITE (plugin, NULL,
1033 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
1037 if (SQLITE_DONE != sqlite3_step (plugin->updRepl))
1038 LOG_SQLITE (plugin, NULL,
1039 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
1041 if (SQLITE_OK != sqlite3_reset (plugin->updRepl))
1042 LOG_SQLITE (plugin, NULL,
1043 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
1051 * Get a random item that has expired or has low priority.
1052 * Call 'proc' with all values ZERO or NULL if the datastore is empty.
1054 * @param cls closure
1055 * @param proc function to call the value (once only).
1056 * @param proc_cls closure for proc
1059 sqlite_plugin_get_expiration (void *cls, PluginDatumProcessor proc,
1062 struct Plugin *plugin = cls;
1064 struct GNUNET_TIME_Absolute now;
1067 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "sqlite",
1068 "Getting random block based on expiration and priority order.\n");
1070 now = GNUNET_TIME_absolute_get ();
1071 stmt = plugin->selExpi;
1072 if (SQLITE_OK != sqlite3_bind_int64 (stmt, 1, now.abs_value))
1074 LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
1075 "sqlite3_bind_XXXX");
1076 if (SQLITE_OK != sqlite3_reset (stmt))
1077 LOG_SQLITE (plugin, NULL,
1078 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
1080 proc (proc_cls, NULL, 0, NULL, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0);
1083 execute_get (plugin, stmt, proc, proc_cls);
1089 * Get all of the keys in the datastore.
1091 * @param cls closure
1092 * @param proc function to call on each key
1093 * @param proc_cls closure for proc
1096 sqlite_plugin_get_keys (void *cls,
1097 PluginKeyProcessor proc,
1100 struct Plugin *plugin = cls;
1101 const GNUNET_HashCode *key;
1105 GNUNET_assert (proc != NULL);
1106 if (sq_prepare (plugin->dbh, "SELECT hash FROM gn090", &stmt) != SQLITE_OK)
1108 LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
1112 while (SQLITE_ROW == (ret = sqlite3_step (stmt)))
1114 key = sqlite3_column_blob (stmt, 1);
1115 if (sizeof (GNUNET_HashCode) == sqlite3_column_bytes (stmt, 1))
1116 proc (proc_cls, key, 1);
1118 if (SQLITE_DONE != ret)
1119 LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR, "sqlite_step");
1120 sqlite3_finalize (stmt);
1127 * @param cls our plugin context
1130 sqlite_plugin_drop (void *cls)
1132 struct Plugin *plugin = cls;
1134 plugin->drop_on_shutdown = GNUNET_YES;
1139 * Get an estimate of how much space the database is
1142 * @param cls the 'struct Plugin'
1143 * @return the size of the database on disk (estimate)
1145 static unsigned long long
1146 sqlite_plugin_estimate_size (void *cls)
1148 struct Plugin *plugin = cls;
1157 if (SQLITE_VERSION_NUMBER < 3006000)
1159 GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING, "datastore-sqlite",
1161 ("sqlite version to old to determine size, assuming zero\n"));
1164 CHECK (SQLITE_OK == sqlite3_exec (plugin->dbh, "VACUUM", NULL, NULL, ENULL));
1166 sqlite3_exec (plugin->dbh, "PRAGMA auto_vacuum=INCREMENTAL", NULL,
1168 CHECK (SQLITE_OK == sq_prepare (plugin->dbh, "PRAGMA page_count", &stmt));
1169 if (SQLITE_ROW == sqlite3_step (stmt))
1170 pages = sqlite3_column_int64 (stmt, 0);
1173 sqlite3_finalize (stmt);
1174 CHECK (SQLITE_OK == sq_prepare (plugin->dbh, "PRAGMA page_size", &stmt));
1175 CHECK (SQLITE_ROW == sqlite3_step (stmt));
1176 page_size = sqlite3_column_int64 (stmt, 0);
1177 sqlite3_finalize (stmt);
1178 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1180 ("Using sqlite page utilization to estimate payload (%llu pages of size %llu bytes)\n"),
1181 (unsigned long long) pages, (unsigned long long) page_size);
1182 return pages * page_size;
1187 * Entry point for the plugin.
1189 * @param cls the "struct GNUNET_DATASTORE_PluginEnvironment*"
1190 * @return NULL on error, othrewise the plugin context
1193 libgnunet_plugin_datastore_sqlite_init (void *cls)
1195 static struct Plugin plugin;
1196 struct GNUNET_DATASTORE_PluginEnvironment *env = cls;
1197 struct GNUNET_DATASTORE_PluginFunctions *api;
1199 if (plugin.env != NULL)
1200 return NULL; /* can only initialize once! */
1201 memset (&plugin, 0, sizeof (struct Plugin));
1203 if (GNUNET_OK != database_setup (env->cfg, &plugin))
1205 database_shutdown (&plugin);
1208 api = GNUNET_malloc (sizeof (struct GNUNET_DATASTORE_PluginFunctions));
1210 api->estimate_size = &sqlite_plugin_estimate_size;
1211 api->put = &sqlite_plugin_put;
1212 api->update = &sqlite_plugin_update;
1213 api->get_key = &sqlite_plugin_get_key;
1214 api->get_replication = &sqlite_plugin_get_replication;
1215 api->get_expiration = &sqlite_plugin_get_expiration;
1216 api->get_zero_anonymity = &sqlite_plugin_get_zero_anonymity;
1217 api->get_keys = &sqlite_plugin_get_keys;
1218 api->drop = &sqlite_plugin_drop;
1219 GNUNET_log_from (GNUNET_ERROR_TYPE_INFO, "sqlite",
1220 _("Sqlite database running\n"));
1226 * Exit point from the plugin.
1228 * @param cls the plugin context (as returned by "init")
1229 * @return always NULL
1232 libgnunet_plugin_datastore_sqlite_done (void *cls)
1235 struct GNUNET_DATASTORE_PluginFunctions *api = cls;
1236 struct Plugin *plugin = api->cls;
1239 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "sqlite",
1240 "sqlite plugin is done\n");
1244 if (plugin->drop_on_shutdown)
1245 fn = GNUNET_strdup (plugin->fn);
1247 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "sqlite",
1248 "Shutting down database\n");
1250 database_shutdown (plugin);
1255 if (0 != UNLINK (fn))
1256 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "unlink", fn);
1260 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "sqlite",
1261 "sqlite plugin is finished\n");
1266 /* end of plugin_datastore_sqlite.c */