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"
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 msg set to an error message
474 * @return #GNUNET_OK on success
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,
488 struct Plugin *plugin = cls;
492 struct GNUNET_HashCode vhash;
495 if (size > MAX_ITEM_SIZE)
496 return GNUNET_SYSERR;
497 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "sqlite",
498 "Storing in database block with type %u/key `%s'/priority %u/expiration in %s (%s).\n",
502 GNUNET_STRINGS_relative_time_to_string (GNUNET_TIME_absolute_get_remaining (expiration),
504 GNUNET_STRINGS_absolute_time_to_string (expiration));
505 GNUNET_CRYPTO_hash (data, size, &vhash);
506 stmt = plugin->insertContent;
507 rvalue = GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK, UINT64_MAX);
508 if ((SQLITE_OK != sqlite3_bind_int (stmt, 1, replication)) ||
509 (SQLITE_OK != sqlite3_bind_int (stmt, 2, type)) ||
510 (SQLITE_OK != sqlite3_bind_int (stmt, 3, priority)) ||
511 (SQLITE_OK != sqlite3_bind_int (stmt, 4, anonymity)) ||
512 (SQLITE_OK != sqlite3_bind_int64 (stmt, 5, expiration.abs_value_us)) ||
513 (SQLITE_OK != sqlite3_bind_int64 (stmt, 6, rvalue)) ||
515 sqlite3_bind_blob (stmt, 7, key, sizeof (struct GNUNET_HashCode),
516 SQLITE_TRANSIENT)) ||
518 sqlite3_bind_blob (stmt, 8, &vhash, sizeof (struct GNUNET_HashCode),
519 SQLITE_TRANSIENT)) ||
520 (SQLITE_OK != sqlite3_bind_blob (stmt, 9, data, size, SQLITE_TRANSIENT)))
522 LOG_SQLITE (plugin, msg, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
523 "sqlite3_bind_XXXX");
524 if (SQLITE_OK != sqlite3_reset (stmt))
525 LOG_SQLITE (plugin, NULL,
526 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
528 return GNUNET_SYSERR;
530 n = sqlite3_step (stmt);
534 plugin->env->duc (plugin->env->cls, size + GNUNET_DATASTORE_ENTRY_OVERHEAD);
535 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "sqlite",
536 "Stored new entry (%u bytes)\n",
537 size + GNUNET_DATASTORE_ENTRY_OVERHEAD);
542 LOG_SQLITE (plugin, msg, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
547 LOG_SQLITE (plugin, msg, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
549 if (SQLITE_OK != sqlite3_reset (stmt))
550 LOG_SQLITE (plugin, NULL,
551 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
553 database_shutdown (plugin);
554 database_setup (plugin->env->cfg, plugin);
555 return GNUNET_SYSERR;
557 if (SQLITE_OK != sqlite3_reset (stmt))
558 LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
565 * Update the priority for a particular key in the datastore. If
566 * the expiration time in value is different than the time found in
567 * the datastore, the higher value should be kept. For the
568 * anonymity level, the lower value is to be used. The specified
569 * priority should be added to the existing priority, ignoring the
572 * Note that it is possible for multiple values to match this put.
573 * In that case, all of the respective values are updated.
575 * @param cls the plugin context (state for this module)
576 * @param uid unique identifier of the datum
577 * @param delta by how much should the priority
578 * change? If priority + delta < 0 the
579 * priority should be set to 0 (never go
581 * @param expire new expiration time should be the
582 * MAX of any existing expiration time and
584 * @param msg set to an error message
585 * @return #GNUNET_OK on success
588 sqlite_plugin_update (void *cls,
591 struct GNUNET_TIME_Absolute expire,
594 struct Plugin *plugin = cls;
597 if ((SQLITE_OK != sqlite3_bind_int (plugin->updPrio, 1, delta)) ||
598 (SQLITE_OK != sqlite3_bind_int64 (plugin->updPrio, 2, expire.abs_value_us))
599 || (SQLITE_OK != sqlite3_bind_int64 (plugin->updPrio, 3, uid)))
601 LOG_SQLITE (plugin, msg, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
602 "sqlite3_bind_XXXX");
603 if (SQLITE_OK != sqlite3_reset (plugin->updPrio))
604 LOG_SQLITE (plugin, NULL,
605 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
607 return GNUNET_SYSERR;
610 n = sqlite3_step (plugin->updPrio);
611 if (SQLITE_OK != sqlite3_reset (plugin->updPrio))
612 LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
617 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "sqlite", "Block updated\n");
620 LOG_SQLITE (plugin, msg, GNUNET_ERROR_TYPE_WARNING | GNUNET_ERROR_TYPE_BULK,
624 LOG_SQLITE (plugin, msg, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
626 return GNUNET_SYSERR;
632 * Execute statement that gets a row and call the callback
633 * with the result. Resets the statement afterwards.
635 * @param plugin the plugin
636 * @param stmt the statement
637 * @param proc processor to call
638 * @param proc_cls closure for @a proc
641 execute_get (struct Plugin *plugin,
643 PluginDatumProcessor proc,
647 struct GNUNET_TIME_Absolute expiration;
648 unsigned long long rowid;
652 n = sqlite3_step (stmt);
656 size = sqlite3_column_bytes (stmt, 5);
657 rowid = sqlite3_column_int64 (stmt, 6);
658 if (sqlite3_column_bytes (stmt, 4) != sizeof (struct GNUNET_HashCode))
660 GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING, "sqlite",
661 _("Invalid data in database. Trying to fix (by deletion).\n"));
662 if (SQLITE_OK != sqlite3_reset (stmt))
663 LOG_SQLITE (plugin, NULL,
664 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
666 if (GNUNET_OK == delete_by_rowid (plugin, rowid))
667 plugin->env->duc (plugin->env->cls,
668 -(size + GNUNET_DATASTORE_ENTRY_OVERHEAD));
671 expiration.abs_value_us = sqlite3_column_int64 (stmt, 3);
672 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "sqlite",
673 "Found reply in database with expiration %s\n",
674 GNUNET_STRINGS_absolute_time_to_string (expiration));
675 ret = proc (proc_cls, sqlite3_column_blob (stmt, 4) /* key */ ,
676 size, sqlite3_column_blob (stmt, 5) /* data */ ,
677 sqlite3_column_int (stmt, 0) /* type */ ,
678 sqlite3_column_int (stmt, 1) /* priority */ ,
679 sqlite3_column_int (stmt, 2) /* anonymity */ ,
681 if (SQLITE_OK != sqlite3_reset (stmt))
682 LOG_SQLITE (plugin, NULL,
683 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
685 if ((GNUNET_NO == ret) && (GNUNET_OK == delete_by_rowid (plugin, rowid)))
686 plugin->env->duc (plugin->env->cls,
687 -(size + GNUNET_DATASTORE_ENTRY_OVERHEAD));
690 /* database must be empty */
691 if (SQLITE_OK != sqlite3_reset (stmt))
692 LOG_SQLITE (plugin, NULL,
693 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
700 LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
702 if (SQLITE_OK != sqlite3_reset (stmt))
703 LOG_SQLITE (plugin, NULL,
704 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
707 database_shutdown (plugin);
708 database_setup (plugin->env->cfg, plugin);
711 if (SQLITE_OK != sqlite3_reset (stmt))
712 LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
714 proc (proc_cls, NULL, 0, NULL, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0);
719 * Select a subset of the items in the datastore and call
720 * the given processor for the item.
722 * @param cls our plugin context
723 * @param offset offset of the result (modulo num-results);
724 * specific ordering does not matter for the offset
725 * @param type entries of which type should be considered?
726 * Use 0 for any type.
727 * @param proc function to call on each matching value;
728 * will be called once with a NULL value at the end
729 * @param proc_cls closure for @a proc
732 sqlite_plugin_get_zero_anonymity (void *cls, uint64_t offset,
733 enum GNUNET_BLOCK_Type type,
734 PluginDatumProcessor proc, void *proc_cls)
736 struct Plugin *plugin = cls;
739 GNUNET_assert (type != GNUNET_BLOCK_TYPE_ANY);
740 stmt = plugin->selZeroAnon;
741 if ((SQLITE_OK != sqlite3_bind_int (stmt, 1, type)) ||
742 (SQLITE_OK != sqlite3_bind_int64 (stmt, 2, offset)))
744 LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
745 "sqlite3_bind_XXXX");
746 if (SQLITE_OK != sqlite3_reset (stmt))
747 LOG_SQLITE (plugin, NULL,
748 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
750 proc (proc_cls, NULL, 0, NULL, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0);
753 execute_get (plugin, stmt, proc, proc_cls);
758 * Get results for a particular key in the datastore.
761 * @param offset offset (mod count).
762 * @param key key to match, never NULL
763 * @param vhash hash of the value, maybe NULL (to
764 * match all values that have the right key).
765 * Note that for DBlocks there is no difference
766 * betwen key and vhash, but for other blocks
768 * @param type entries of which type are relevant?
769 * Use 0 for any type.
770 * @param proc function to call on each matching value;
771 * will be called once with a NULL value at the end
772 * @param proc_cls closure for @a proc
775 sqlite_plugin_get_key (void *cls,
777 const struct GNUNET_HashCode *key,
778 const struct GNUNET_HashCode *vhash,
779 enum GNUNET_BLOCK_Type type,
780 PluginDatumProcessor proc,
783 struct Plugin *plugin = cls;
791 GNUNET_assert (proc != NULL);
792 GNUNET_assert (key != NULL);
793 GNUNET_snprintf (scratch, sizeof (scratch),
794 "SELECT count(*) FROM gn090 WHERE hash=?%s%s",
795 vhash == NULL ? "" : " AND vhash=?",
796 type == 0 ? "" : " AND type=?");
797 if (sq_prepare (plugin->dbh, scratch, &stmt) != SQLITE_OK)
799 LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
801 proc (proc_cls, NULL, 0, NULL, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0);
806 sqlite3_bind_blob (stmt, sqoff++, key, sizeof (struct GNUNET_HashCode),
808 if ((vhash != NULL) && (ret == SQLITE_OK))
810 sqlite3_bind_blob (stmt, sqoff++, vhash, sizeof (struct GNUNET_HashCode),
812 if ((type != 0) && (ret == SQLITE_OK))
813 ret = sqlite3_bind_int (stmt, sqoff++, type);
814 if (SQLITE_OK != ret)
816 LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR, "sqlite_bind");
817 sqlite3_finalize (stmt);
818 proc (proc_cls, NULL, 0, NULL, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0);
821 ret = sqlite3_step (stmt);
822 if (ret != SQLITE_ROW)
824 LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
826 sqlite3_finalize (stmt);
827 proc (proc_cls, NULL, 0, NULL, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0);
830 total = sqlite3_column_int (stmt, 0);
831 sqlite3_finalize (stmt);
834 proc (proc_cls, NULL, 0, NULL, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0);
837 limit_off = (int) (offset % total);
840 GNUNET_snprintf (scratch, sizeof (scratch),
841 "SELECT type, prio, anonLevel, expire, hash, value, _ROWID_ "
842 "FROM gn090 WHERE hash=?%s%s "
843 "ORDER BY _ROWID_ ASC LIMIT 1 OFFSET ?",
844 vhash == NULL ? "" : " AND vhash=?",
845 type == 0 ? "" : " AND type=?");
846 if (sq_prepare (plugin->dbh, scratch, &stmt) != SQLITE_OK)
848 LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
850 proc (proc_cls, NULL, 0, NULL, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0);
854 ret = sqlite3_bind_blob (stmt, sqoff++, key,
855 sizeof (struct GNUNET_HashCode),
857 if ((vhash != NULL) && (ret == SQLITE_OK))
858 ret = sqlite3_bind_blob (stmt, sqoff++, vhash,
859 sizeof (struct GNUNET_HashCode),
861 if ((type != 0) && (ret == SQLITE_OK))
862 ret = sqlite3_bind_int (stmt, sqoff++, type);
863 if (ret == SQLITE_OK)
864 ret = sqlite3_bind_int64 (stmt, sqoff++, limit_off);
865 if (ret != SQLITE_OK)
867 LOG_SQLITE (plugin, NULL,
868 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
870 proc (proc_cls, NULL, 0, NULL, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0);
873 execute_get (plugin, stmt, proc, proc_cls);
874 sqlite3_finalize (stmt);
879 * Context for #repl_proc() function.
885 * Function to call for the result (or the NULL).
887 PluginDatumProcessor proc;
890 * Closure for @e proc.
900 * Yes if UID was set.
907 * Wrapper for the processor for #sqlite_plugin_get_replication().
908 * Decrements the replication counter and calls the original
912 * @param key key for the content
913 * @param size number of bytes in @a data
914 * @param data content stored
915 * @param type type of the content
916 * @param priority priority of the content
917 * @param anonymity anonymity-level for the content
918 * @param expiration expiration time for the content
919 * @param uid unique identifier for the datum;
920 * maybe 0 if no unique identifier is available
921 * @return #GNUNET_OK for normal return,
922 * #GNUNET_NO to delete the item
925 repl_proc (void *cls,
926 const struct GNUNET_HashCode *key,
929 enum GNUNET_BLOCK_Type type,
932 struct GNUNET_TIME_Absolute expiration,
935 struct ReplCtx *rc = cls;
938 ret = rc->proc (rc->proc_cls,
948 rc->have_uid = GNUNET_YES;
955 * Get a random item for replication. Returns a single random item
956 * from those with the highest replication counters. The item's
957 * replication counter is decremented by one IF it was positive before.
958 * Call @a proc with all values ZERO or NULL if the datastore is empty.
961 * @param proc function to call the value (once only).
962 * @param proc_cls closure for @a proc
965 sqlite_plugin_get_replication (void *cls, PluginDatumProcessor proc,
968 struct Plugin *plugin = cls;
974 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "sqlite",
975 "Getting random block based on replication order.\n");
976 rc.have_uid = GNUNET_NO;
978 rc.proc_cls = proc_cls;
979 stmt = plugin->maxRepl;
980 if (SQLITE_ROW != sqlite3_step (stmt))
982 if (SQLITE_OK != sqlite3_reset (stmt))
983 LOG_SQLITE (plugin, NULL,
984 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
987 proc (proc_cls, NULL, 0, NULL, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0);
990 repl = sqlite3_column_int (stmt, 0);
991 if (SQLITE_OK != sqlite3_reset (stmt))
992 LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
994 stmt = plugin->selRepl;
995 rvalue = GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK, UINT64_MAX);
996 if (SQLITE_OK != sqlite3_bind_int64 (stmt, 1, rvalue))
998 LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
999 "sqlite3_bind_XXXX");
1000 if (SQLITE_OK != sqlite3_reset (stmt))
1001 LOG_SQLITE (plugin, NULL,
1002 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
1004 proc (proc_cls, NULL, 0, NULL, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0);
1007 if (SQLITE_OK != sqlite3_bind_int (stmt, 2, repl))
1009 LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
1010 "sqlite3_bind_XXXX");
1011 if (SQLITE_OK != sqlite3_reset (stmt))
1012 LOG_SQLITE (plugin, NULL,
1013 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
1015 proc (proc_cls, NULL, 0, NULL, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0);
1018 execute_get (plugin, stmt, &repl_proc, &rc);
1019 if (GNUNET_YES == rc.have_uid)
1021 if (SQLITE_OK != sqlite3_bind_int64 (plugin->updRepl, 1, rc.uid))
1023 LOG_SQLITE (plugin, NULL,
1024 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
1025 "sqlite3_bind_XXXX");
1026 if (SQLITE_OK != sqlite3_reset (plugin->updRepl))
1027 LOG_SQLITE (plugin, NULL,
1028 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
1032 if (SQLITE_DONE != sqlite3_step (plugin->updRepl))
1033 LOG_SQLITE (plugin, NULL,
1034 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
1036 if (SQLITE_OK != sqlite3_reset (plugin->updRepl))
1037 LOG_SQLITE (plugin, NULL,
1038 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
1045 * Get a random item that has expired or has low priority.
1046 * Call @a proc with all values ZERO or NULL if the datastore is empty.
1048 * @param cls closure
1049 * @param proc function to call the value (once only).
1050 * @param proc_cls closure for @a proc
1053 sqlite_plugin_get_expiration (void *cls, PluginDatumProcessor proc,
1056 struct Plugin *plugin = cls;
1058 struct GNUNET_TIME_Absolute now;
1060 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "sqlite",
1061 "Getting random block based on expiration and priority order.\n");
1062 now = GNUNET_TIME_absolute_get ();
1063 stmt = plugin->selExpi;
1064 if (SQLITE_OK != sqlite3_bind_int64 (stmt, 1, now.abs_value_us))
1066 LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
1067 "sqlite3_bind_XXXX");
1068 if (SQLITE_OK != sqlite3_reset (stmt))
1069 LOG_SQLITE (plugin, NULL,
1070 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
1072 proc (proc_cls, NULL, 0, NULL, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0);
1075 execute_get (plugin, stmt, proc, proc_cls);
1080 * Get all of the keys in the datastore.
1082 * @param cls closure
1083 * @param proc function to call on each key
1084 * @param proc_cls closure for @a proc
1087 sqlite_plugin_get_keys (void *cls,
1088 PluginKeyProcessor proc,
1091 struct Plugin *plugin = cls;
1092 const struct GNUNET_HashCode *key;
1096 GNUNET_assert (proc != NULL);
1097 if (sq_prepare (plugin->dbh, "SELECT hash FROM gn090", &stmt) != SQLITE_OK)
1099 LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
1103 while (SQLITE_ROW == (ret = sqlite3_step (stmt)))
1105 key = sqlite3_column_blob (stmt, 0);
1106 if (sizeof (struct GNUNET_HashCode) == sqlite3_column_bytes (stmt, 0))
1107 proc (proc_cls, key, 1);
1111 if (SQLITE_DONE != ret)
1112 LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR, "sqlite_step");
1113 sqlite3_finalize (stmt);
1120 * @param cls our plugin context
1123 sqlite_plugin_drop (void *cls)
1125 struct Plugin *plugin = cls;
1127 plugin->drop_on_shutdown = GNUNET_YES;
1132 * Get an estimate of how much space the database is
1135 * @param cls the `struct Plugin`
1136 * @return the size of the database on disk (estimate)
1138 static unsigned long long
1139 sqlite_plugin_estimate_size (void *cls)
1141 struct Plugin *plugin = cls;
1150 if (SQLITE_VERSION_NUMBER < 3006000)
1152 GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING, "datastore-sqlite",
1154 ("sqlite version to old to determine size, assuming zero\n"));
1157 CHECK (SQLITE_OK == sqlite3_exec (plugin->dbh, "VACUUM", NULL, NULL, ENULL));
1159 sqlite3_exec (plugin->dbh, "PRAGMA auto_vacuum=INCREMENTAL", NULL,
1161 CHECK (SQLITE_OK == sq_prepare (plugin->dbh, "PRAGMA page_count", &stmt));
1162 if (SQLITE_ROW == sqlite3_step (stmt))
1163 pages = sqlite3_column_int64 (stmt, 0);
1166 sqlite3_finalize (stmt);
1167 CHECK (SQLITE_OK == sq_prepare (plugin->dbh, "PRAGMA page_size", &stmt));
1168 CHECK (SQLITE_ROW == sqlite3_step (stmt));
1169 page_size = sqlite3_column_int64 (stmt, 0);
1170 sqlite3_finalize (stmt);
1171 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1173 ("Using sqlite page utilization to estimate payload (%llu pages of size %llu bytes)\n"),
1174 (unsigned long long) pages, (unsigned long long) page_size);
1175 return pages * page_size;
1180 * Entry point for the plugin.
1182 * @param cls the `struct GNUNET_DATASTORE_PluginEnvironment *`
1183 * @return NULL on error, othrewise the plugin context
1186 libgnunet_plugin_datastore_sqlite_init (void *cls)
1188 static struct Plugin plugin;
1189 struct GNUNET_DATASTORE_PluginEnvironment *env = cls;
1190 struct GNUNET_DATASTORE_PluginFunctions *api;
1192 if (plugin.env != NULL)
1193 return NULL; /* can only initialize once! */
1194 memset (&plugin, 0, sizeof (struct Plugin));
1196 if (GNUNET_OK != database_setup (env->cfg, &plugin))
1198 database_shutdown (&plugin);
1201 api = GNUNET_new (struct GNUNET_DATASTORE_PluginFunctions);
1203 api->estimate_size = &sqlite_plugin_estimate_size;
1204 api->put = &sqlite_plugin_put;
1205 api->update = &sqlite_plugin_update;
1206 api->get_key = &sqlite_plugin_get_key;
1207 api->get_replication = &sqlite_plugin_get_replication;
1208 api->get_expiration = &sqlite_plugin_get_expiration;
1209 api->get_zero_anonymity = &sqlite_plugin_get_zero_anonymity;
1210 api->get_keys = &sqlite_plugin_get_keys;
1211 api->drop = &sqlite_plugin_drop;
1212 GNUNET_log_from (GNUNET_ERROR_TYPE_INFO, "sqlite",
1213 _("Sqlite database running\n"));
1219 * Exit point from the plugin.
1221 * @param cls the plugin context (as returned by "init")
1222 * @return always NULL
1225 libgnunet_plugin_datastore_sqlite_done (void *cls)
1228 struct GNUNET_DATASTORE_PluginFunctions *api = cls;
1229 struct Plugin *plugin = api->cls;
1231 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "sqlite",
1232 "sqlite plugin is done\n");
1234 if (plugin->drop_on_shutdown)
1235 fn = GNUNET_strdup (plugin->fn);
1236 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "sqlite",
1237 "Shutting down database\n");
1238 database_shutdown (plugin);
1243 if (0 != UNLINK (fn))
1244 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "unlink", fn);
1247 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "sqlite",
1248 "sqlite plugin is finished\n");
1252 /* end of plugin_datastore_sqlite.c */