2 * This file is part of GNUnet
3 * Copyright (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"
33 * We allocate items on the stack at times. To prevent a stack
34 * overflow, we impose a limit on the maximum size for the data per
35 * item. 64k should be enough.
37 #define MAX_ITEM_SIZE 65536
40 * After how many ms "busy" should a DB operation fail for good?
41 * A low value makes sure that we are more responsive to requests
42 * (especially PUTs). A high value guarantees a higher success
43 * rate (SELECTs in iterate can take several seconds despite LIMIT=1).
45 * The default value of 250ms should ensure that users do not experience
46 * huge latencies while at the same time allowing operations to succeed
47 * with reasonable probability.
49 #define BUSY_TIMEOUT_MS 250
53 * Log an error message at log-level 'level' that indicates
54 * a failure of the command 'cmd' on file 'filename'
55 * with the message given by strerror(errno).
57 #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)
62 * Context for all functions in this plugin.
67 * Our execution environment.
69 struct GNUNET_DATASTORE_PluginEnvironment *env;
77 * Native SQLite database handle.
82 * Precompiled SQL for deletion.
87 * Precompiled SQL for update.
89 sqlite3_stmt *updPrio;
92 * Get maximum repl value in database.
94 sqlite3_stmt *maxRepl;
97 * Precompiled SQL for replication decrement.
99 sqlite3_stmt *updRepl;
102 * Precompiled SQL for replication selection.
104 sqlite3_stmt *selRepl;
107 * Precompiled SQL for expiration selection.
109 sqlite3_stmt *selExpi;
112 * Precompiled SQL for expiration selection.
114 sqlite3_stmt *selZeroAnon;
117 * Precompiled SQL for insertion.
119 sqlite3_stmt *insertContent;
122 * Should the database be dropped on shutdown?
124 int drop_on_shutdown;
130 * @brief Prepare a SQL statement
132 * @param dbh handle to the database
133 * @param zSql SQL statement, UTF-8 encoded
134 * @param ppStmt set to the prepared statement
135 * @return 0 on success
138 sq_prepare (sqlite3 *dbh,
140 sqlite3_stmt **ppStmt)
146 sqlite3_prepare_v2 (dbh, zSql, strlen (zSql), ppStmt,
147 (const char **) &dummy);
148 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "sqlite",
149 "Prepared `%s' / %p: %d\n", zSql, *ppStmt, result);
155 * Create our database indices.
157 * @param dbh handle to the database
160 create_indices (sqlite3 * dbh)
164 sqlite3_exec (dbh, "CREATE INDEX IF NOT EXISTS idx_hash ON gn090 (hash)",
165 NULL, NULL, NULL)) ||
168 "CREATE INDEX IF NOT EXISTS idx_hash_vhash ON gn090 (hash,vhash)",
169 NULL, NULL, NULL)) ||
172 "CREATE INDEX IF NOT EXISTS idx_expire_repl ON gn090 (expire ASC,repl DESC)",
173 NULL, NULL, NULL)) ||
176 "CREATE INDEX IF NOT EXISTS idx_comb ON gn090 (anonLevel ASC,expire ASC,prio,type,hash)",
177 NULL, NULL, NULL)) ||
180 "CREATE INDEX IF NOT EXISTS idx_anon_type_hash ON gn090 (anonLevel ASC,type,hash)",
181 NULL, NULL, NULL)) ||
184 "CREATE INDEX IF NOT EXISTS idx_expire ON gn090 (expire ASC)",
185 NULL, NULL, NULL)) ||
188 "CREATE INDEX IF NOT EXISTS idx_repl_rvalue ON gn090 (repl,rvalue)",
189 NULL, NULL, NULL)) ||
192 "CREATE INDEX IF NOT EXISTS idx_repl ON gn090 (repl DESC)",
194 GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, "sqlite",
195 "Failed to create indices: %s\n", sqlite3_errmsg (dbh));
200 #define CHECK(a) GNUNET_break(a)
204 #define ENULL_DEFINED 1
205 #define CHECK(a) if (! a) { GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "%s\n", e); sqlite3_free(e); }
210 * Initialize the database connections and associated
211 * data structures (create tables and indices
212 * as needed as well).
214 * @param cfg our configuration
215 * @param plugin the plugin context (state for this module)
216 * @return #GNUNET_OK on success
219 database_setup (const struct GNUNET_CONFIGURATION_Handle *cfg,
220 struct Plugin *plugin)
230 GNUNET_CONFIGURATION_get_value_filename (cfg, "datastore-sqlite",
231 "FILENAME", &afsdir))
233 GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR,
234 "datastore-sqlite", "FILENAME");
235 return GNUNET_SYSERR;
237 if (GNUNET_OK != GNUNET_DISK_file_test (afsdir))
239 if (GNUNET_OK != GNUNET_DISK_directory_create_for_file (afsdir))
242 GNUNET_free (afsdir);
243 return GNUNET_SYSERR;
245 /* database is new or got deleted, reset payload to zero! */
246 plugin->env->duc (plugin->env->cls, 0);
248 /* afsdir should be UTF-8-encoded. If it isn't, it's a bug */
251 /* Open database and precompile statements */
252 if (sqlite3_open (plugin->fn, &plugin->dbh) != SQLITE_OK)
254 GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, "sqlite",
255 _("Unable to initialize SQLite: %s.\n"),
256 sqlite3_errmsg (plugin->dbh));
257 return GNUNET_SYSERR;
260 sqlite3_exec (plugin->dbh, "PRAGMA temp_store=MEMORY", NULL, NULL,
263 sqlite3_exec (plugin->dbh, "PRAGMA synchronous=OFF", NULL, NULL,
266 sqlite3_exec (plugin->dbh, "PRAGMA legacy_file_format=OFF", NULL, NULL,
269 sqlite3_exec (plugin->dbh, "PRAGMA auto_vacuum=INCREMENTAL", NULL,
272 sqlite3_exec (plugin->dbh, "PRAGMA locking_mode=EXCLUSIVE", NULL, NULL,
275 sqlite3_exec (plugin->dbh, "PRAGMA page_size=4092", NULL, NULL,
278 CHECK (SQLITE_OK == sqlite3_busy_timeout (plugin->dbh, BUSY_TIMEOUT_MS));
281 /* We have to do it here, because otherwise precompiling SQL might fail */
283 sq_prepare (plugin->dbh,
284 "SELECT 1 FROM sqlite_master WHERE tbl_name = 'gn090'",
286 if ((sqlite3_step (stmt) == SQLITE_DONE) &&
289 "CREATE TABLE gn090 (" " repl INT4 NOT NULL DEFAULT 0,"
290 " type INT4 NOT NULL DEFAULT 0," " prio INT4 NOT NULL DEFAULT 0,"
291 " anonLevel INT4 NOT NULL DEFAULT 0,"
292 " expire INT8 NOT NULL DEFAULT 0," " rvalue INT8 NOT NULL,"
293 " hash TEXT NOT NULL DEFAULT ''," " vhash TEXT NOT NULL DEFAULT '',"
294 " value BLOB NOT NULL DEFAULT '')", NULL, NULL, NULL) != SQLITE_OK))
296 LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR, "sqlite3_exec");
297 sqlite3_finalize (stmt);
298 return GNUNET_SYSERR;
300 sqlite3_finalize (stmt);
301 create_indices (plugin->dbh);
306 "SET prio = prio + ?, expire = MAX(expire,?) WHERE _ROWID_ = ?",
307 &plugin->updPrio) != SQLITE_OK) ||
310 "UPDATE gn090 " "SET repl = MAX (0, repl - 1) WHERE _ROWID_ = ?",
311 &plugin->updRepl) != SQLITE_OK) ||
314 "SELECT type,prio,anonLevel,expire,hash,value,_ROWID_ " "FROM gn090 "
315 #if SQLITE_VERSION_NUMBER >= 3007000
316 "INDEXED BY idx_repl_rvalue "
318 "WHERE repl=?2 AND " " (rvalue>=?1 OR "
319 " NOT EXISTS (SELECT 1 FROM gn090 "
320 #if SQLITE_VERSION_NUMBER >= 3007000
321 "INDEXED BY idx_repl_rvalue "
323 "WHERE repl=?2 AND rvalue>=?1 LIMIT 1) ) "
324 "ORDER BY rvalue ASC LIMIT 1", &plugin->selRepl) != SQLITE_OK) ||
325 (sq_prepare (plugin->dbh, "SELECT MAX(repl) FROM gn090"
326 #if SQLITE_VERSION_NUMBER >= 3007000
327 " INDEXED BY idx_repl_rvalue"
329 "", &plugin->maxRepl) != SQLITE_OK) ||
332 "SELECT type,prio,anonLevel,expire,hash,value,_ROWID_ " "FROM gn090 "
333 #if SQLITE_VERSION_NUMBER >= 3007000
334 "INDEXED BY idx_expire "
336 "WHERE NOT EXISTS (SELECT 1 FROM gn090 WHERE expire < ?1 LIMIT 1) OR (expire < ?1) "
337 "ORDER BY expire ASC LIMIT 1", &plugin->selExpi) != SQLITE_OK) ||
340 "SELECT type,prio,anonLevel,expire,hash,value,_ROWID_ " "FROM gn090 "
341 #if SQLITE_VERSION_NUMBER >= 3007000
342 "INDEXED BY idx_anon_type_hash "
344 "WHERE (anonLevel = 0 AND type=?1) "
345 "ORDER BY hash DESC LIMIT 1 OFFSET ?2",
346 &plugin->selZeroAnon) != SQLITE_OK) ||
349 "INSERT INTO gn090 (repl, type, prio, anonLevel, expire, rvalue, hash, vhash, value) "
350 "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)",
351 &plugin->insertContent) != SQLITE_OK) ||
353 (plugin->dbh, "DELETE FROM gn090 WHERE _ROWID_ = ?",
354 &plugin->delRow) != SQLITE_OK))
356 LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR, "precompiling");
357 return GNUNET_SYSERR;
365 * Shutdown database connection and associate data
368 * @param plugin the plugin context (state for this module)
371 database_shutdown (struct Plugin *plugin)
375 #if SQLITE_VERSION_NUMBER >= 3007000
379 if (plugin->delRow != NULL)
380 sqlite3_finalize (plugin->delRow);
381 if (plugin->updPrio != NULL)
382 sqlite3_finalize (plugin->updPrio);
383 if (plugin->updRepl != NULL)
384 sqlite3_finalize (plugin->updRepl);
385 if (plugin->selRepl != NULL)
386 sqlite3_finalize (plugin->selRepl);
387 if (plugin->maxRepl != NULL)
388 sqlite3_finalize (plugin->maxRepl);
389 if (plugin->selExpi != NULL)
390 sqlite3_finalize (plugin->selExpi);
391 if (plugin->selZeroAnon != NULL)
392 sqlite3_finalize (plugin->selZeroAnon);
393 if (plugin->insertContent != NULL)
394 sqlite3_finalize (plugin->insertContent);
395 result = sqlite3_close (plugin->dbh);
396 #if SQLITE_VERSION_NUMBER >= 3007000
397 if (result == SQLITE_BUSY)
399 GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING, "sqlite",
401 ("Tried to close sqlite without finalizing all prepared statements.\n"));
402 stmt = sqlite3_next_stmt (plugin->dbh, NULL);
405 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "sqlite",
406 "Closing statement %p\n", stmt);
407 result = sqlite3_finalize (stmt);
408 if (result != SQLITE_OK)
409 GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING, "sqlite",
410 "Failed to close statement %p: %d\n", stmt, result);
411 stmt = sqlite3_next_stmt (plugin->dbh, NULL);
413 result = sqlite3_close (plugin->dbh);
416 if (SQLITE_OK != result)
417 LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR, "sqlite3_close");
419 GNUNET_free_non_null (plugin->fn);
424 * Delete the database entry with the given
427 * @param plugin the plugin context (state for this module)
428 * @param rid the ID of the row to delete
431 delete_by_rowid (struct Plugin *plugin,
432 unsigned long long rid)
434 if (SQLITE_OK != sqlite3_bind_int64 (plugin->delRow, 1, rid))
436 LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
437 "sqlite3_bind_XXXX");
438 if (SQLITE_OK != sqlite3_reset (plugin->delRow))
439 LOG_SQLITE (plugin, NULL,
440 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
442 return GNUNET_SYSERR;
444 if (SQLITE_DONE != sqlite3_step (plugin->delRow))
446 LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
448 if (SQLITE_OK != sqlite3_reset (plugin->delRow))
449 LOG_SQLITE (plugin, NULL,
450 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
452 return GNUNET_SYSERR;
454 if (SQLITE_OK != sqlite3_reset (plugin->delRow))
455 LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
462 * Store an item in the datastore.
465 * @param key key for the item
466 * @param size number of bytes in @a data
467 * @param data content stored
468 * @param type type of the content
469 * @param priority priority of the content
470 * @param anonymity anonymity-level for the content
471 * @param replication replication-level for the content
472 * @param expiration expiration time for the content
473 * @param cont continuation called with success or failure status
474 * @param cont_cls continuation closure
477 sqlite_plugin_put (void *cls,
478 const struct GNUNET_HashCode *key,
481 enum GNUNET_BLOCK_Type type,
484 uint32_t replication,
485 struct GNUNET_TIME_Absolute expiration,
489 struct Plugin *plugin = cls;
493 struct GNUNET_HashCode vhash;
497 if (size > MAX_ITEM_SIZE)
499 cont (cont_cls, key, size, GNUNET_SYSERR, _("Data too large"));
502 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "sqlite",
503 "Storing in database block with type %u/key `%s'/priority %u/expiration in %s (%s).\n",
507 GNUNET_STRINGS_relative_time_to_string (GNUNET_TIME_absolute_get_remaining (expiration),
509 GNUNET_STRINGS_absolute_time_to_string (expiration));
510 GNUNET_CRYPTO_hash (data, size, &vhash);
511 stmt = plugin->insertContent;
512 rvalue = GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK, UINT64_MAX);
513 if ((SQLITE_OK != sqlite3_bind_int (stmt, 1, replication)) ||
514 (SQLITE_OK != sqlite3_bind_int (stmt, 2, type)) ||
515 (SQLITE_OK != sqlite3_bind_int (stmt, 3, priority)) ||
516 (SQLITE_OK != sqlite3_bind_int (stmt, 4, anonymity)) ||
517 (SQLITE_OK != sqlite3_bind_int64 (stmt, 5, expiration.abs_value_us)) ||
518 (SQLITE_OK != sqlite3_bind_int64 (stmt, 6, rvalue)) ||
520 sqlite3_bind_blob (stmt, 7, key, sizeof (struct GNUNET_HashCode),
521 SQLITE_TRANSIENT)) ||
523 sqlite3_bind_blob (stmt, 8, &vhash, sizeof (struct GNUNET_HashCode),
524 SQLITE_TRANSIENT)) ||
525 (SQLITE_OK != sqlite3_bind_blob (stmt, 9, data, size, SQLITE_TRANSIENT)))
527 LOG_SQLITE (plugin, &msg, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
528 "sqlite3_bind_XXXX");
529 if (SQLITE_OK != sqlite3_reset (stmt))
530 LOG_SQLITE (plugin, NULL,
531 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
533 cont (cont_cls, key, size, GNUNET_SYSERR, msg);
534 GNUNET_free_non_null(msg);
537 n = sqlite3_step (stmt);
541 plugin->env->duc (plugin->env->cls, size + GNUNET_DATASTORE_ENTRY_OVERHEAD);
542 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "sqlite",
543 "Stored new entry (%u bytes)\n",
544 size + GNUNET_DATASTORE_ENTRY_OVERHEAD);
549 LOG_SQLITE (plugin, &msg, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
554 LOG_SQLITE (plugin, &msg, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
556 if (SQLITE_OK != sqlite3_reset (stmt))
557 LOG_SQLITE (plugin, NULL,
558 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
560 database_shutdown (plugin);
561 database_setup (plugin->env->cfg, plugin);
562 cont (cont_cls, key, size, GNUNET_SYSERR, msg);
563 GNUNET_free_non_null(msg);
566 if (SQLITE_OK != sqlite3_reset (stmt))
567 LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
569 cont (cont_cls, key, size, ret, msg);
570 GNUNET_free_non_null(msg);
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 cont continuation called with success or failure status
595 * @param cons_cls continuation closure
598 sqlite_plugin_update (void *cls,
601 struct GNUNET_TIME_Absolute expire,
602 PluginUpdateCont cont,
605 struct Plugin *plugin = cls;
609 if ((SQLITE_OK != sqlite3_bind_int (plugin->updPrio, 1, delta)) ||
610 (SQLITE_OK != sqlite3_bind_int64 (plugin->updPrio, 2, expire.abs_value_us))
611 || (SQLITE_OK != sqlite3_bind_int64 (plugin->updPrio, 3, uid)))
613 LOG_SQLITE (plugin, &msg, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
614 "sqlite3_bind_XXXX");
615 if (SQLITE_OK != sqlite3_reset (plugin->updPrio))
616 LOG_SQLITE (plugin, NULL,
617 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
619 cont (cont_cls, GNUNET_SYSERR, msg);
620 GNUNET_free_non_null(msg);
623 n = sqlite3_step (plugin->updPrio);
624 if (SQLITE_OK != sqlite3_reset (plugin->updPrio))
625 LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
630 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "sqlite", "Block updated\n");
631 cont (cont_cls, GNUNET_OK, NULL);
634 LOG_SQLITE (plugin, &msg,
635 GNUNET_ERROR_TYPE_WARNING | GNUNET_ERROR_TYPE_BULK,
637 cont (cont_cls, GNUNET_NO, msg);
638 GNUNET_free_non_null(msg);
641 LOG_SQLITE (plugin, &msg, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
643 cont (cont_cls, GNUNET_SYSERR, msg);
644 GNUNET_free_non_null(msg);
651 * Execute statement that gets a row and call the callback
652 * with the result. Resets the statement afterwards.
654 * @param plugin the plugin
655 * @param stmt the statement
656 * @param proc processor to call
657 * @param proc_cls closure for @a proc
660 execute_get (struct Plugin *plugin,
662 PluginDatumProcessor proc,
666 struct GNUNET_TIME_Absolute expiration;
667 unsigned long long rowid;
671 n = sqlite3_step (stmt);
675 size = sqlite3_column_bytes (stmt, 5);
676 rowid = sqlite3_column_int64 (stmt, 6);
677 if (sqlite3_column_bytes (stmt, 4) != sizeof (struct GNUNET_HashCode))
679 GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING, "sqlite",
680 _("Invalid data in database. Trying to fix (by deletion).\n"));
681 if (SQLITE_OK != sqlite3_reset (stmt))
682 LOG_SQLITE (plugin, NULL,
683 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
685 if (GNUNET_OK == delete_by_rowid (plugin, rowid))
686 plugin->env->duc (plugin->env->cls,
687 -(size + GNUNET_DATASTORE_ENTRY_OVERHEAD));
690 expiration.abs_value_us = sqlite3_column_int64 (stmt, 3);
691 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "sqlite",
692 "Found reply in database with expiration %s\n",
693 GNUNET_STRINGS_absolute_time_to_string (expiration));
694 ret = proc (proc_cls, sqlite3_column_blob (stmt, 4) /* key */ ,
695 size, sqlite3_column_blob (stmt, 5) /* data */ ,
696 sqlite3_column_int (stmt, 0) /* type */ ,
697 sqlite3_column_int (stmt, 1) /* priority */ ,
698 sqlite3_column_int (stmt, 2) /* anonymity */ ,
700 if (SQLITE_OK != sqlite3_reset (stmt))
701 LOG_SQLITE (plugin, NULL,
702 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
704 if ((GNUNET_NO == ret) && (GNUNET_OK == delete_by_rowid (plugin, rowid)))
705 plugin->env->duc (plugin->env->cls,
706 -(size + GNUNET_DATASTORE_ENTRY_OVERHEAD));
709 /* database must be empty */
710 if (SQLITE_OK != sqlite3_reset (stmt))
711 LOG_SQLITE (plugin, NULL,
712 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
719 LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
721 if (SQLITE_OK != sqlite3_reset (stmt))
722 LOG_SQLITE (plugin, NULL,
723 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
726 database_shutdown (plugin);
727 database_setup (plugin->env->cfg, plugin);
730 if (SQLITE_OK != sqlite3_reset (stmt))
731 LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
733 proc (proc_cls, NULL, 0, NULL, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0);
738 * Select a subset of the items in the datastore and call
739 * the given processor for the item.
741 * @param cls our plugin context
742 * @param offset offset of the result (modulo num-results);
743 * specific ordering does not matter for the offset
744 * @param type entries of which type should be considered?
745 * Use 0 for any type.
746 * @param proc function to call on each matching value;
747 * will be called once with a NULL value at the end
748 * @param proc_cls closure for @a proc
751 sqlite_plugin_get_zero_anonymity (void *cls, uint64_t offset,
752 enum GNUNET_BLOCK_Type type,
753 PluginDatumProcessor proc, void *proc_cls)
755 struct Plugin *plugin = cls;
758 GNUNET_assert (type != GNUNET_BLOCK_TYPE_ANY);
759 stmt = plugin->selZeroAnon;
760 if ((SQLITE_OK != sqlite3_bind_int (stmt, 1, type)) ||
761 (SQLITE_OK != sqlite3_bind_int64 (stmt, 2, offset)))
763 LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
764 "sqlite3_bind_XXXX");
765 if (SQLITE_OK != sqlite3_reset (stmt))
766 LOG_SQLITE (plugin, NULL,
767 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
769 proc (proc_cls, NULL, 0, NULL, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0);
772 execute_get (plugin, stmt, proc, proc_cls);
777 * Get results for a particular key in the datastore.
780 * @param offset offset (mod count).
781 * @param key key to match, never NULL
782 * @param vhash hash of the value, maybe NULL (to
783 * match all values that have the right key).
784 * Note that for DBlocks there is no difference
785 * betwen key and vhash, but for other blocks
787 * @param type entries of which type are relevant?
788 * Use 0 for any type.
789 * @param proc function to call on each matching value;
790 * will be called once with a NULL value at the end
791 * @param proc_cls closure for @a proc
794 sqlite_plugin_get_key (void *cls,
796 const struct GNUNET_HashCode *key,
797 const struct GNUNET_HashCode *vhash,
798 enum GNUNET_BLOCK_Type type,
799 PluginDatumProcessor proc,
802 struct Plugin *plugin = cls;
810 GNUNET_assert (proc != NULL);
811 GNUNET_assert (key != NULL);
812 GNUNET_snprintf (scratch, sizeof (scratch),
813 "SELECT count(*) FROM gn090 WHERE hash=?%s%s",
814 vhash == NULL ? "" : " AND vhash=?",
815 type == 0 ? "" : " AND type=?");
816 if (sq_prepare (plugin->dbh, scratch, &stmt) != SQLITE_OK)
818 LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
820 proc (proc_cls, NULL, 0, NULL, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0);
825 sqlite3_bind_blob (stmt, sqoff++, key, sizeof (struct GNUNET_HashCode),
827 if ((vhash != NULL) && (ret == SQLITE_OK))
829 sqlite3_bind_blob (stmt, sqoff++, vhash, sizeof (struct GNUNET_HashCode),
831 if ((type != 0) && (ret == SQLITE_OK))
832 ret = sqlite3_bind_int (stmt, sqoff++, type);
833 if (SQLITE_OK != ret)
835 LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR, "sqlite_bind");
836 sqlite3_finalize (stmt);
837 proc (proc_cls, NULL, 0, NULL, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0);
840 ret = sqlite3_step (stmt);
841 if (ret != SQLITE_ROW)
843 LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
845 sqlite3_finalize (stmt);
846 proc (proc_cls, NULL, 0, NULL, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0);
849 total = sqlite3_column_int (stmt, 0);
850 sqlite3_finalize (stmt);
853 proc (proc_cls, NULL, 0, NULL, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0);
856 limit_off = (int) (offset % total);
859 GNUNET_snprintf (scratch, sizeof (scratch),
860 "SELECT type, prio, anonLevel, expire, hash, value, _ROWID_ "
861 "FROM gn090 WHERE hash=?%s%s "
862 "ORDER BY _ROWID_ ASC LIMIT 1 OFFSET ?",
863 vhash == NULL ? "" : " AND vhash=?",
864 type == 0 ? "" : " AND type=?");
865 if (sq_prepare (plugin->dbh, scratch, &stmt) != SQLITE_OK)
867 LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
869 proc (proc_cls, NULL, 0, NULL, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0);
873 ret = sqlite3_bind_blob (stmt, sqoff++, key,
874 sizeof (struct GNUNET_HashCode),
876 if ((vhash != NULL) && (ret == SQLITE_OK))
877 ret = sqlite3_bind_blob (stmt, sqoff++, vhash,
878 sizeof (struct GNUNET_HashCode),
880 if ((type != 0) && (ret == SQLITE_OK))
881 ret = sqlite3_bind_int (stmt, sqoff++, type);
882 if (ret == SQLITE_OK)
883 ret = sqlite3_bind_int64 (stmt, sqoff++, limit_off);
884 if (ret != SQLITE_OK)
886 LOG_SQLITE (plugin, NULL,
887 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
889 proc (proc_cls, NULL, 0, NULL, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0);
892 execute_get (plugin, stmt, proc, proc_cls);
893 sqlite3_finalize (stmt);
898 * Context for #repl_proc() function.
904 * Function to call for the result (or the NULL).
906 PluginDatumProcessor proc;
909 * Closure for @e proc.
919 * Yes if UID was set.
926 * Wrapper for the processor for #sqlite_plugin_get_replication().
927 * Decrements the replication counter and calls the original
931 * @param key key for the content
932 * @param size number of bytes in @a data
933 * @param data content stored
934 * @param type type of the content
935 * @param priority priority of the content
936 * @param anonymity anonymity-level for the content
937 * @param expiration expiration time for the content
938 * @param uid unique identifier for the datum;
939 * maybe 0 if no unique identifier is available
940 * @return #GNUNET_OK for normal return,
941 * #GNUNET_NO to delete the item
944 repl_proc (void *cls,
945 const struct GNUNET_HashCode *key,
948 enum GNUNET_BLOCK_Type type,
951 struct GNUNET_TIME_Absolute expiration,
954 struct ReplCtx *rc = cls;
957 ret = rc->proc (rc->proc_cls,
967 rc->have_uid = GNUNET_YES;
974 * Get a random item for replication. Returns a single random item
975 * from those with the highest replication counters. The item's
976 * replication counter is decremented by one IF it was positive before.
977 * Call @a proc with all values ZERO or NULL if the datastore is empty.
980 * @param proc function to call the value (once only).
981 * @param proc_cls closure for @a proc
984 sqlite_plugin_get_replication (void *cls, PluginDatumProcessor proc,
987 struct Plugin *plugin = cls;
993 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "sqlite",
994 "Getting random block based on replication order.\n");
995 rc.have_uid = GNUNET_NO;
997 rc.proc_cls = proc_cls;
998 stmt = plugin->maxRepl;
999 if (SQLITE_ROW != sqlite3_step (stmt))
1001 if (SQLITE_OK != sqlite3_reset (stmt))
1002 LOG_SQLITE (plugin, NULL,
1003 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
1006 proc (proc_cls, NULL, 0, NULL, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0);
1009 repl = sqlite3_column_int (stmt, 0);
1010 if (SQLITE_OK != sqlite3_reset (stmt))
1011 LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
1013 stmt = plugin->selRepl;
1014 rvalue = GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK, UINT64_MAX);
1015 if (SQLITE_OK != sqlite3_bind_int64 (stmt, 1, rvalue))
1017 LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
1018 "sqlite3_bind_XXXX");
1019 if (SQLITE_OK != sqlite3_reset (stmt))
1020 LOG_SQLITE (plugin, NULL,
1021 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
1023 proc (proc_cls, NULL, 0, NULL, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0);
1026 if (SQLITE_OK != sqlite3_bind_int (stmt, 2, repl))
1028 LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
1029 "sqlite3_bind_XXXX");
1030 if (SQLITE_OK != sqlite3_reset (stmt))
1031 LOG_SQLITE (plugin, NULL,
1032 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
1034 proc (proc_cls, NULL, 0, NULL, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0);
1037 execute_get (plugin, stmt, &repl_proc, &rc);
1038 if (GNUNET_YES == rc.have_uid)
1040 if (SQLITE_OK != sqlite3_bind_int64 (plugin->updRepl, 1, rc.uid))
1042 LOG_SQLITE (plugin, NULL,
1043 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
1044 "sqlite3_bind_XXXX");
1045 if (SQLITE_OK != sqlite3_reset (plugin->updRepl))
1046 LOG_SQLITE (plugin, NULL,
1047 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
1051 if (SQLITE_DONE != sqlite3_step (plugin->updRepl))
1052 LOG_SQLITE (plugin, NULL,
1053 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
1055 if (SQLITE_OK != sqlite3_reset (plugin->updRepl))
1056 LOG_SQLITE (plugin, NULL,
1057 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
1064 * Get a random item that has expired or has low priority.
1065 * Call @a proc with all values ZERO or NULL if the datastore is empty.
1067 * @param cls closure
1068 * @param proc function to call the value (once only).
1069 * @param proc_cls closure for @a proc
1072 sqlite_plugin_get_expiration (void *cls, PluginDatumProcessor proc,
1075 struct Plugin *plugin = cls;
1077 struct GNUNET_TIME_Absolute now;
1079 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "sqlite",
1080 "Getting random block based on expiration and priority order.\n");
1081 now = GNUNET_TIME_absolute_get ();
1082 stmt = plugin->selExpi;
1083 if (SQLITE_OK != sqlite3_bind_int64 (stmt, 1, now.abs_value_us))
1085 LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
1086 "sqlite3_bind_XXXX");
1087 if (SQLITE_OK != sqlite3_reset (stmt))
1088 LOG_SQLITE (plugin, NULL,
1089 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
1091 proc (proc_cls, NULL, 0, NULL, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0);
1094 execute_get (plugin, stmt, proc, proc_cls);
1099 * Get all of the keys in the datastore.
1101 * @param cls closure
1102 * @param proc function to call on each key
1103 * @param proc_cls closure for @a proc
1106 sqlite_plugin_get_keys (void *cls,
1107 PluginKeyProcessor proc,
1110 struct Plugin *plugin = cls;
1111 const struct GNUNET_HashCode *key;
1115 GNUNET_assert (proc != NULL);
1116 if (sq_prepare (plugin->dbh, "SELECT hash FROM gn090", &stmt) != SQLITE_OK)
1118 LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
1120 proc (proc_cls, NULL, 0);
1123 while (SQLITE_ROW == (ret = sqlite3_step (stmt)))
1125 key = sqlite3_column_blob (stmt, 0);
1126 if (sizeof (struct GNUNET_HashCode) == sqlite3_column_bytes (stmt, 0))
1127 proc (proc_cls, key, 1);
1131 if (SQLITE_DONE != ret)
1132 LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR, "sqlite_step");
1133 sqlite3_finalize (stmt);
1134 proc (proc_cls, NULL, 0);
1141 * @param cls our plugin context
1144 sqlite_plugin_drop (void *cls)
1146 struct Plugin *plugin = cls;
1148 plugin->drop_on_shutdown = GNUNET_YES;
1153 * Get an estimate of how much space the database is
1156 * @param cls the `struct Plugin`
1157 * @return the size of the database on disk (estimate)
1160 sqlite_plugin_estimate_size (void *cls, unsigned long long *estimate)
1162 struct Plugin *plugin = cls;
1171 if (NULL == estimate)
1173 if (SQLITE_VERSION_NUMBER < 3006000)
1175 GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING, "datastore-sqlite",
1177 ("sqlite version to old to determine size, assuming zero\n"));
1181 CHECK (SQLITE_OK == sqlite3_exec (plugin->dbh, "VACUUM", NULL, NULL, ENULL));
1183 sqlite3_exec (plugin->dbh, "PRAGMA auto_vacuum=INCREMENTAL", NULL,
1185 CHECK (SQLITE_OK == sq_prepare (plugin->dbh, "PRAGMA page_count", &stmt));
1186 if (SQLITE_ROW == sqlite3_step (stmt))
1187 pages = sqlite3_column_int64 (stmt, 0);
1190 sqlite3_finalize (stmt);
1191 CHECK (SQLITE_OK == sq_prepare (plugin->dbh, "PRAGMA page_size", &stmt));
1192 CHECK (SQLITE_ROW == sqlite3_step (stmt));
1193 page_size = sqlite3_column_int64 (stmt, 0);
1194 sqlite3_finalize (stmt);
1195 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1197 ("Using sqlite page utilization to estimate payload (%llu pages of size %llu bytes)\n"),
1198 (unsigned long long) pages, (unsigned long long) page_size);
1199 *estimate = pages * page_size;
1204 * Entry point for the plugin.
1206 * @param cls the `struct GNUNET_DATASTORE_PluginEnvironment *`
1207 * @return NULL on error, othrewise the plugin context
1210 libgnunet_plugin_datastore_sqlite_init (void *cls)
1212 static struct Plugin plugin;
1213 struct GNUNET_DATASTORE_PluginEnvironment *env = cls;
1214 struct GNUNET_DATASTORE_PluginFunctions *api;
1216 if (plugin.env != NULL)
1217 return NULL; /* can only initialize once! */
1218 memset (&plugin, 0, sizeof (struct Plugin));
1220 if (GNUNET_OK != database_setup (env->cfg, &plugin))
1222 database_shutdown (&plugin);
1225 api = GNUNET_new (struct GNUNET_DATASTORE_PluginFunctions);
1227 api->estimate_size = &sqlite_plugin_estimate_size;
1228 api->put = &sqlite_plugin_put;
1229 api->update = &sqlite_plugin_update;
1230 api->get_key = &sqlite_plugin_get_key;
1231 api->get_replication = &sqlite_plugin_get_replication;
1232 api->get_expiration = &sqlite_plugin_get_expiration;
1233 api->get_zero_anonymity = &sqlite_plugin_get_zero_anonymity;
1234 api->get_keys = &sqlite_plugin_get_keys;
1235 api->drop = &sqlite_plugin_drop;
1236 GNUNET_log_from (GNUNET_ERROR_TYPE_INFO, "sqlite",
1237 _("Sqlite database running\n"));
1243 * Exit point from the plugin.
1245 * @param cls the plugin context (as returned by "init")
1246 * @return always NULL
1249 libgnunet_plugin_datastore_sqlite_done (void *cls)
1252 struct GNUNET_DATASTORE_PluginFunctions *api = cls;
1253 struct Plugin *plugin = api->cls;
1255 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "sqlite",
1256 "sqlite plugin is done\n");
1258 if (plugin->drop_on_shutdown)
1259 fn = GNUNET_strdup (plugin->fn);
1260 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "sqlite",
1261 "Shutting down database\n");
1262 database_shutdown (plugin);
1267 if (0 != UNLINK (fn))
1268 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "unlink", fn);
1271 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "sqlite",
1272 "sqlite plugin is finished\n");
1276 /* end of plugin_datastore_sqlite.c */