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);
423 if (result != SQLITE_OK)
424 GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING, "sqlite",
425 "Failed to close statement %p: %d\n", stmt, result);
426 stmt = sqlite3_next_stmt (plugin->dbh, NULL);
428 result = sqlite3_close (plugin->dbh);
431 if (SQLITE_OK != result)
432 LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR, "sqlite3_close");
434 GNUNET_free_non_null (plugin->fn);
439 * Delete the database entry with the given
442 * @param plugin the plugin context (state for this module)
443 * @param rid the ID of the row to delete
446 delete_by_rowid (struct Plugin *plugin, unsigned long long rid)
448 if (SQLITE_OK != sqlite3_bind_int64 (plugin->delRow, 1, rid))
450 LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
451 "sqlite3_bind_XXXX");
452 if (SQLITE_OK != sqlite3_reset (plugin->delRow))
453 LOG_SQLITE (plugin, NULL,
454 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
456 return GNUNET_SYSERR;
458 if (SQLITE_DONE != sqlite3_step (plugin->delRow))
460 LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
462 if (SQLITE_OK != sqlite3_reset (plugin->delRow))
463 LOG_SQLITE (plugin, NULL,
464 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
466 return GNUNET_SYSERR;
468 if (SQLITE_OK != sqlite3_reset (plugin->delRow))
469 LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
476 * Store an item in the datastore.
479 * @param key key for the item
480 * @param size number of bytes in data
481 * @param data content stored
482 * @param type type of the content
483 * @param priority priority of the content
484 * @param anonymity anonymity-level for the content
485 * @param replication replication-level for the content
486 * @param expiration expiration time for the content
487 * @param msg set to an error message
488 * @return GNUNET_OK on success
491 sqlite_plugin_put (void *cls, const GNUNET_HashCode * key, uint32_t size,
492 const void *data, enum GNUNET_BLOCK_Type type,
493 uint32_t priority, uint32_t anonymity, uint32_t replication,
494 struct GNUNET_TIME_Absolute expiration, char **msg)
496 struct Plugin *plugin = cls;
500 GNUNET_HashCode vhash;
503 if (size > MAX_ITEM_SIZE)
504 return GNUNET_SYSERR;
506 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "sqlite",
507 "Storing in database block with type %u/key `%s'/priority %u/expiration in %llu ms (%lld).\n",
508 type, GNUNET_h2s (key), priority,
510 GNUNET_TIME_absolute_get_remaining (expiration).rel_value,
511 (long long) expiration.abs_value);
513 GNUNET_CRYPTO_hash (data, size, &vhash);
514 stmt = plugin->insertContent;
515 rvalue = GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK, UINT64_MAX);
516 if ((SQLITE_OK != sqlite3_bind_int (stmt, 1, replication)) ||
517 (SQLITE_OK != sqlite3_bind_int (stmt, 2, type)) ||
518 (SQLITE_OK != sqlite3_bind_int (stmt, 3, priority)) ||
519 (SQLITE_OK != sqlite3_bind_int (stmt, 4, anonymity)) ||
520 (SQLITE_OK != sqlite3_bind_int64 (stmt, 5, expiration.abs_value)) ||
521 (SQLITE_OK != sqlite3_bind_int64 (stmt, 6, rvalue)) ||
523 sqlite3_bind_blob (stmt, 7, key, sizeof (GNUNET_HashCode),
524 SQLITE_TRANSIENT)) ||
526 sqlite3_bind_blob (stmt, 8, &vhash, sizeof (GNUNET_HashCode),
527 SQLITE_TRANSIENT)) ||
528 (SQLITE_OK != sqlite3_bind_blob (stmt, 9, data, size, SQLITE_TRANSIENT)))
530 LOG_SQLITE (plugin, msg, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
531 "sqlite3_bind_XXXX");
532 if (SQLITE_OK != sqlite3_reset (stmt))
533 LOG_SQLITE (plugin, NULL,
534 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
536 return GNUNET_SYSERR;
538 n = sqlite3_step (stmt);
542 plugin->env->duc (plugin->env->cls, size + GNUNET_DATASTORE_ENTRY_OVERHEAD);
544 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "sqlite",
545 "Stored new entry (%u bytes)\n",
546 size + GNUNET_DATASTORE_ENTRY_OVERHEAD);
552 LOG_SQLITE (plugin, msg, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
557 LOG_SQLITE (plugin, msg, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
559 if (SQLITE_OK != sqlite3_reset (stmt))
560 LOG_SQLITE (plugin, NULL,
561 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
563 database_shutdown (plugin);
564 database_setup (plugin->env->cfg, plugin);
565 return GNUNET_SYSERR;
567 if (SQLITE_OK != sqlite3_reset (stmt))
568 LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
575 * Update the priority for a particular key in the datastore. If
576 * the expiration time in value is different than the time found in
577 * the datastore, the higher value should be kept. For the
578 * anonymity level, the lower value is to be used. The specified
579 * priority should be added to the existing priority, ignoring the
582 * Note that it is possible for multiple values to match this put.
583 * In that case, all of the respective values are updated.
585 * @param cls the plugin context (state for this module)
586 * @param uid unique identifier of the datum
587 * @param delta by how much should the priority
588 * change? If priority + delta < 0 the
589 * priority should be set to 0 (never go
591 * @param expire new expiration time should be the
592 * MAX of any existing expiration time and
594 * @param msg set to an error message
595 * @return GNUNET_OK on success
598 sqlite_plugin_update (void *cls, uint64_t uid, int delta,
599 struct GNUNET_TIME_Absolute expire, char **msg)
601 struct Plugin *plugin = cls;
604 if ((SQLITE_OK != sqlite3_bind_int (plugin->updPrio, 1, delta)) ||
605 (SQLITE_OK != sqlite3_bind_int64 (plugin->updPrio, 2, expire.abs_value))
606 || (SQLITE_OK != sqlite3_bind_int64 (plugin->updPrio, 3, uid)))
608 LOG_SQLITE (plugin, msg, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
609 "sqlite3_bind_XXXX");
610 if (SQLITE_OK != sqlite3_reset (plugin->updPrio))
611 LOG_SQLITE (plugin, NULL,
612 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
614 return GNUNET_SYSERR;
617 n = sqlite3_step (plugin->updPrio);
618 if (SQLITE_OK != sqlite3_reset (plugin->updPrio))
619 LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
625 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "sqlite", "Block updated\n");
629 LOG_SQLITE (plugin, msg, GNUNET_ERROR_TYPE_WARNING | GNUNET_ERROR_TYPE_BULK,
633 LOG_SQLITE (plugin, msg, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
635 return GNUNET_SYSERR;
641 * Execute statement that gets a row and call the callback
642 * with the result. Resets the statement afterwards.
644 * @param plugin the plugin
645 * @param stmt the statement
646 * @param proc processor to call
647 * @param proc_cls closure for 'proc'
650 execute_get (struct Plugin *plugin, sqlite3_stmt * stmt,
651 PluginDatumProcessor proc, void *proc_cls)
654 struct GNUNET_TIME_Absolute expiration;
655 unsigned long long rowid;
659 n = sqlite3_step (stmt);
663 size = sqlite3_column_bytes (stmt, 5);
664 rowid = sqlite3_column_int64 (stmt, 6);
665 if (sqlite3_column_bytes (stmt, 4) != sizeof (GNUNET_HashCode))
667 GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING, "sqlite",
669 ("Invalid data in database. Trying to fix (by deletion).\n"));
670 if (SQLITE_OK != sqlite3_reset (stmt))
671 LOG_SQLITE (plugin, NULL,
672 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
674 if (GNUNET_OK == delete_by_rowid (plugin, rowid))
675 plugin->env->duc (plugin->env->cls,
676 -(size + GNUNET_DATASTORE_ENTRY_OVERHEAD));
679 expiration.abs_value = sqlite3_column_int64 (stmt, 3);
681 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "sqlite",
682 "Found reply in database with expiration %llu\n",
683 (unsigned long long) expiration.abs_value);
685 ret = proc (proc_cls, sqlite3_column_blob (stmt, 4) /* key */ ,
686 size, sqlite3_column_blob (stmt, 5) /* data */ ,
687 sqlite3_column_int (stmt, 0) /* type */ ,
688 sqlite3_column_int (stmt, 1) /* priority */ ,
689 sqlite3_column_int (stmt, 2) /* anonymity */ ,
691 if (SQLITE_OK != sqlite3_reset (stmt))
692 LOG_SQLITE (plugin, NULL,
693 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
695 if ((GNUNET_NO == ret) && (GNUNET_OK == delete_by_rowid (plugin, rowid)))
696 plugin->env->duc (plugin->env->cls,
697 -(size + GNUNET_DATASTORE_ENTRY_OVERHEAD));
700 /* database must be empty */
701 if (SQLITE_OK != sqlite3_reset (stmt))
702 LOG_SQLITE (plugin, NULL,
703 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
710 LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
712 if (SQLITE_OK != sqlite3_reset (stmt))
713 LOG_SQLITE (plugin, NULL,
714 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
717 database_shutdown (plugin);
718 database_setup (plugin->env->cfg, plugin);
721 if (SQLITE_OK != sqlite3_reset (stmt))
722 LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
724 proc (proc_cls, NULL, 0, NULL, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0);
730 * Select a subset of the items in the datastore and call
731 * the given processor for the item.
733 * @param cls our plugin context
734 * @param offset offset of the result (modulo num-results);
735 * specific ordering does not matter for the offset
736 * @param type entries of which type should be considered?
737 * Use 0 for any type.
738 * @param proc function to call on each matching value;
739 * will be called once with a NULL value at the end
740 * @param proc_cls closure for proc
743 sqlite_plugin_get_zero_anonymity (void *cls, uint64_t offset,
744 enum GNUNET_BLOCK_Type type,
745 PluginDatumProcessor proc, void *proc_cls)
747 struct Plugin *plugin = cls;
750 GNUNET_assert (type != GNUNET_BLOCK_TYPE_ANY);
751 stmt = plugin->selZeroAnon;
752 if ((SQLITE_OK != sqlite3_bind_int (stmt, 1, type)) ||
753 (SQLITE_OK != sqlite3_bind_int64 (stmt, 2, offset)))
755 LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
756 "sqlite3_bind_XXXX");
757 if (SQLITE_OK != sqlite3_reset (stmt))
758 LOG_SQLITE (plugin, NULL,
759 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
761 proc (proc_cls, NULL, 0, NULL, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0);
764 execute_get (plugin, stmt, proc, proc_cls);
770 * Get results for a particular key in the datastore.
773 * @param offset offset (mod count).
774 * @param key key to match, never NULL
775 * @param vhash hash of the value, maybe NULL (to
776 * match all values that have the right key).
777 * Note that for DBlocks there is no difference
778 * betwen key and vhash, but for other blocks
780 * @param type entries of which type are relevant?
781 * Use 0 for any type.
782 * @param proc function to call on each matching value;
783 * will be called once with a NULL value at the end
784 * @param proc_cls closure for proc
787 sqlite_plugin_get_key (void *cls, uint64_t offset, const GNUNET_HashCode * key,
788 const GNUNET_HashCode * vhash,
789 enum GNUNET_BLOCK_Type type, PluginDatumProcessor proc,
792 struct Plugin *plugin = cls;
800 GNUNET_assert (proc != NULL);
801 GNUNET_assert (key != NULL);
802 GNUNET_snprintf (scratch, sizeof (scratch),
803 "SELECT count(*) FROM gn090 WHERE hash=?%s%s",
804 vhash == NULL ? "" : " AND vhash=?",
805 type == 0 ? "" : " AND type=?");
806 if (sq_prepare (plugin->dbh, scratch, &stmt) != SQLITE_OK)
808 LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
810 proc (proc_cls, NULL, 0, NULL, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0);
815 sqlite3_bind_blob (stmt, sqoff++, key, sizeof (GNUNET_HashCode),
817 if ((vhash != NULL) && (ret == SQLITE_OK))
819 sqlite3_bind_blob (stmt, sqoff++, vhash, sizeof (GNUNET_HashCode),
821 if ((type != 0) && (ret == SQLITE_OK))
822 ret = sqlite3_bind_int (stmt, sqoff++, type);
823 if (SQLITE_OK != ret)
825 LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR, "sqlite_bind");
826 sqlite3_finalize (stmt);
827 proc (proc_cls, NULL, 0, NULL, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0);
830 ret = sqlite3_step (stmt);
831 if (ret != SQLITE_ROW)
833 LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
835 sqlite3_finalize (stmt);
836 proc (proc_cls, NULL, 0, NULL, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0);
839 total = sqlite3_column_int (stmt, 0);
840 sqlite3_finalize (stmt);
843 proc (proc_cls, NULL, 0, NULL, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0);
846 limit_off = (int) (offset % total);
849 GNUNET_snprintf (scratch, sizeof (scratch),
850 "SELECT type, prio, anonLevel, expire, hash, value, _ROWID_ "
851 "FROM gn090 WHERE hash=?%s%s "
852 "ORDER BY _ROWID_ ASC LIMIT 1 OFFSET ?",
853 vhash == NULL ? "" : " AND vhash=?",
854 type == 0 ? "" : " AND type=?");
855 if (sq_prepare (plugin->dbh, scratch, &stmt) != SQLITE_OK)
857 LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
859 proc (proc_cls, NULL, 0, NULL, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0);
864 sqlite3_bind_blob (stmt, sqoff++, key, sizeof (GNUNET_HashCode),
866 if ((vhash != NULL) && (ret == SQLITE_OK))
868 sqlite3_bind_blob (stmt, sqoff++, vhash, sizeof (GNUNET_HashCode),
870 if ((type != 0) && (ret == SQLITE_OK))
871 ret = sqlite3_bind_int (stmt, sqoff++, type);
872 if (ret == SQLITE_OK)
873 ret = sqlite3_bind_int64 (stmt, sqoff++, limit_off);
874 if (ret != SQLITE_OK)
876 LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
878 proc (proc_cls, NULL, 0, NULL, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0);
881 execute_get (plugin, stmt, proc, proc_cls);
882 sqlite3_finalize (stmt);
888 * Context for 'repl_proc' function.
894 * Function to call for the result (or the NULL).
896 PluginDatumProcessor proc;
909 * Yes if UID was set.
916 * Wrapper for the processor for 'sqlite_plugin_replication_get'.
917 * Decrements the replication counter and calls the original
921 * @param key key for the content
922 * @param size number of bytes in data
923 * @param data content stored
924 * @param type type of the content
925 * @param priority priority of the content
926 * @param anonymity anonymity-level for the content
927 * @param expiration expiration time for the content
928 * @param uid unique identifier for the datum;
929 * maybe 0 if no unique identifier is available
931 * @return GNUNET_OK for normal return,
932 * GNUNET_NO to delete the item
935 repl_proc (void *cls, const GNUNET_HashCode * key, uint32_t size,
936 const void *data, enum GNUNET_BLOCK_Type type, uint32_t priority,
937 uint32_t anonymity, struct GNUNET_TIME_Absolute expiration,
940 struct ReplCtx *rc = cls;
944 rc->proc (rc->proc_cls, key, size, data, type, priority, anonymity,
949 rc->have_uid = GNUNET_YES;
956 * Get a random item for replication. Returns a single random item
957 * from those with the highest replication counters. The item's
958 * replication counter is decremented by one IF it was positive before.
959 * Call 'proc' with all values ZERO or NULL if the datastore is empty.
962 * @param proc function to call the value (once only).
963 * @param proc_cls closure for proc
966 sqlite_plugin_get_replication (void *cls, PluginDatumProcessor proc,
969 struct Plugin *plugin = cls;
976 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "sqlite",
977 "Getting random block based on replication order.\n");
979 rc.have_uid = GNUNET_NO;
981 rc.proc_cls = proc_cls;
982 stmt = plugin->maxRepl;
983 if (SQLITE_ROW != sqlite3_step (stmt))
985 if (SQLITE_OK != sqlite3_reset (stmt))
986 LOG_SQLITE (plugin, NULL,
987 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
990 proc (proc_cls, NULL, 0, NULL, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0);
993 repl = sqlite3_column_int (stmt, 0);
994 if (SQLITE_OK != sqlite3_reset (stmt))
995 LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
997 stmt = plugin->selRepl;
998 rvalue = GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK, UINT64_MAX);
999 if (SQLITE_OK != sqlite3_bind_int64 (stmt, 1, rvalue))
1001 LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
1002 "sqlite3_bind_XXXX");
1003 if (SQLITE_OK != sqlite3_reset (stmt))
1004 LOG_SQLITE (plugin, NULL,
1005 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
1007 proc (proc_cls, NULL, 0, NULL, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0);
1010 if (SQLITE_OK != sqlite3_bind_int (stmt, 2, repl))
1012 LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
1013 "sqlite3_bind_XXXX");
1014 if (SQLITE_OK != sqlite3_reset (stmt))
1015 LOG_SQLITE (plugin, NULL,
1016 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
1018 proc (proc_cls, NULL, 0, NULL, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0);
1021 execute_get (plugin, stmt, &repl_proc, &rc);
1022 if (GNUNET_YES == rc.have_uid)
1024 if (SQLITE_OK != sqlite3_bind_int64 (plugin->updRepl, 1, rc.uid))
1026 LOG_SQLITE (plugin, NULL,
1027 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
1028 "sqlite3_bind_XXXX");
1029 if (SQLITE_OK != sqlite3_reset (plugin->updRepl))
1030 LOG_SQLITE (plugin, NULL,
1031 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
1035 if (SQLITE_DONE != sqlite3_step (plugin->updRepl))
1036 LOG_SQLITE (plugin, NULL,
1037 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
1039 if (SQLITE_OK != sqlite3_reset (plugin->updRepl))
1040 LOG_SQLITE (plugin, NULL,
1041 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
1049 * Get a random item that has expired or has low priority.
1050 * Call 'proc' with all values ZERO or NULL if the datastore is empty.
1052 * @param cls closure
1053 * @param proc function to call the value (once only).
1054 * @param proc_cls closure for proc
1057 sqlite_plugin_get_expiration (void *cls, PluginDatumProcessor proc,
1060 struct Plugin *plugin = cls;
1062 struct GNUNET_TIME_Absolute now;
1065 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "sqlite",
1066 "Getting random block based on expiration and priority order.\n");
1068 now = GNUNET_TIME_absolute_get ();
1069 stmt = plugin->selExpi;
1070 if (SQLITE_OK != sqlite3_bind_int64 (stmt, 1, now.abs_value))
1072 LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
1073 "sqlite3_bind_XXXX");
1074 if (SQLITE_OK != sqlite3_reset (stmt))
1075 LOG_SQLITE (plugin, NULL,
1076 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
1078 proc (proc_cls, NULL, 0, NULL, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0);
1081 execute_get (plugin, stmt, proc, proc_cls);
1087 * Get all of the keys in the datastore.
1089 * @param cls closure
1090 * @param proc function to call on each key
1091 * @param proc_cls closure for proc
1094 sqlite_plugin_get_keys (void *cls,
1095 PluginKeyProcessor proc,
1098 struct Plugin *plugin = cls;
1099 const GNUNET_HashCode *key;
1103 GNUNET_assert (proc != NULL);
1104 if (sq_prepare (plugin->dbh, "SELECT hash FROM gn090", &stmt) != SQLITE_OK)
1106 LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
1110 while (SQLITE_ROW == (ret = sqlite3_step (stmt)))
1112 key = sqlite3_column_blob (stmt, 1);
1113 if (sizeof (GNUNET_HashCode) == sqlite3_column_bytes (stmt, 1))
1114 proc (proc_cls, key, 1);
1116 if (SQLITE_DONE != ret)
1117 LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR, "sqlite_step");
1118 sqlite3_finalize (stmt);
1125 * @param cls our plugin context
1128 sqlite_plugin_drop (void *cls)
1130 struct Plugin *plugin = cls;
1132 plugin->drop_on_shutdown = GNUNET_YES;
1137 * Get an estimate of how much space the database is
1140 * @param cls the 'struct Plugin'
1141 * @return the size of the database on disk (estimate)
1143 static unsigned long long
1144 sqlite_plugin_estimate_size (void *cls)
1146 struct Plugin *plugin = cls;
1155 if (SQLITE_VERSION_NUMBER < 3006000)
1157 GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING, "datastore-sqlite",
1159 ("sqlite version to old to determine size, assuming zero\n"));
1162 CHECK (SQLITE_OK == sqlite3_exec (plugin->dbh, "VACUUM", NULL, NULL, ENULL));
1164 sqlite3_exec (plugin->dbh, "PRAGMA auto_vacuum=INCREMENTAL", NULL,
1166 CHECK (SQLITE_OK == sq_prepare (plugin->dbh, "PRAGMA page_count", &stmt));
1167 if (SQLITE_ROW == sqlite3_step (stmt))
1168 pages = sqlite3_column_int64 (stmt, 0);
1171 sqlite3_finalize (stmt);
1172 CHECK (SQLITE_OK == sq_prepare (plugin->dbh, "PRAGMA page_size", &stmt));
1173 CHECK (SQLITE_ROW == sqlite3_step (stmt));
1174 page_size = sqlite3_column_int64 (stmt, 0);
1175 sqlite3_finalize (stmt);
1176 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1178 ("Using sqlite page utilization to estimate payload (%llu pages of size %llu bytes)\n"),
1179 (unsigned long long) pages, (unsigned long long) page_size);
1180 return pages * page_size;
1185 * Entry point for the plugin.
1187 * @param cls the "struct GNUNET_DATASTORE_PluginEnvironment*"
1188 * @return NULL on error, othrewise the plugin context
1191 libgnunet_plugin_datastore_sqlite_init (void *cls)
1193 static struct Plugin plugin;
1194 struct GNUNET_DATASTORE_PluginEnvironment *env = cls;
1195 struct GNUNET_DATASTORE_PluginFunctions *api;
1197 if (plugin.env != NULL)
1198 return NULL; /* can only initialize once! */
1199 memset (&plugin, 0, sizeof (struct Plugin));
1201 if (GNUNET_OK != database_setup (env->cfg, &plugin))
1203 database_shutdown (&plugin);
1206 api = GNUNET_malloc (sizeof (struct GNUNET_DATASTORE_PluginFunctions));
1208 api->estimate_size = &sqlite_plugin_estimate_size;
1209 api->put = &sqlite_plugin_put;
1210 api->update = &sqlite_plugin_update;
1211 api->get_key = &sqlite_plugin_get_key;
1212 api->get_replication = &sqlite_plugin_get_replication;
1213 api->get_expiration = &sqlite_plugin_get_expiration;
1214 api->get_zero_anonymity = &sqlite_plugin_get_zero_anonymity;
1215 api->get_keys = &sqlite_plugin_get_keys;
1216 api->drop = &sqlite_plugin_drop;
1217 GNUNET_log_from (GNUNET_ERROR_TYPE_INFO, "sqlite",
1218 _("Sqlite database running\n"));
1224 * Exit point from the plugin.
1226 * @param cls the plugin context (as returned by "init")
1227 * @return always NULL
1230 libgnunet_plugin_datastore_sqlite_done (void *cls)
1233 struct GNUNET_DATASTORE_PluginFunctions *api = cls;
1234 struct Plugin *plugin = api->cls;
1237 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "sqlite",
1238 "sqlite plugin is done\n");
1242 if (plugin->drop_on_shutdown)
1243 fn = GNUNET_strdup (plugin->fn);
1245 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "sqlite",
1246 "Shutting down database\n");
1248 database_shutdown (plugin);
1253 if (0 != UNLINK (fn))
1254 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "unlink", fn);
1258 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "sqlite",
1259 "sqlite plugin is finished\n");
1264 /* end of plugin_datastore_sqlite.c */