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_NO
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_ "
330 #if SQLITE_VERSION_NUMBER >= 3007000
331 "INDEXED BY idx_repl_rvalue "
335 " NOT EXISTS (SELECT 1 FROM gn090 "
336 #if SQLITE_VERSION_NUMBER >= 3007000
337 "INDEXED BY idx_repl_rvalue "
339 "WHERE repl=?2 AND rvalue>=?1 LIMIT 1) ) "
340 "ORDER BY rvalue ASC LIMIT 1", &plugin->selRepl) != SQLITE_OK) ||
342 (plugin->dbh, "SELECT MAX(repl) FROM gn090"
343 #if SQLITE_VERSION_NUMBER >= 3007000
344 " INDEXED BY idx_repl_rvalue"
347 &plugin->maxRepl) != SQLITE_OK) ||
350 "SELECT type,prio,anonLevel,expire,hash,value,_ROWID_ "
352 #if SQLITE_VERSION_NUMBER >= 3007000
353 "INDEXED BY idx_expire "
355 "WHERE NOT EXISTS (SELECT 1 FROM gn090 WHERE expire < ?1 LIMIT 1) OR (expire < ?1) "
356 "ORDER BY expire ASC LIMIT 1", &plugin->selExpi) != SQLITE_OK) ||
359 "SELECT type,prio,anonLevel,expire,hash,value,_ROWID_ "
361 #if SQLITE_VERSION_NUMBER >= 3007000
362 "INDEXED BY idx_anon_type_hash "
364 "WHERE (anonLevel = 0 AND type=?1) "
365 "ORDER BY hash DESC LIMIT 1 OFFSET ?2",
366 &plugin->selZeroAnon) != SQLITE_OK) ||
369 "INSERT INTO gn090 (repl, type, prio, anonLevel, expire, rvalue, hash, vhash, value) "
370 "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)",
371 &plugin->insertContent) != SQLITE_OK) ||
373 (plugin->dbh, "DELETE FROM gn090 WHERE _ROWID_ = ?",
374 &plugin->delRow) != SQLITE_OK))
376 LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR, "precompiling");
377 return GNUNET_SYSERR;
385 * Shutdown database connection and associate data
387 * @param plugin the plugin context (state for this module)
390 database_shutdown (struct Plugin *plugin)
394 #if SQLITE_VERSION_NUMBER >= 3007000
398 if (plugin->delRow != NULL)
399 sqlite3_finalize (plugin->delRow);
400 if (plugin->updPrio != NULL)
401 sqlite3_finalize (plugin->updPrio);
402 if (plugin->updRepl != NULL)
403 sqlite3_finalize (plugin->updRepl);
404 if (plugin->selRepl != NULL)
405 sqlite3_finalize (plugin->selRepl);
406 if (plugin->maxRepl != NULL)
407 sqlite3_finalize (plugin->maxRepl);
408 if (plugin->selExpi != NULL)
409 sqlite3_finalize (plugin->selExpi);
410 if (plugin->selZeroAnon != NULL)
411 sqlite3_finalize (plugin->selZeroAnon);
412 if (plugin->insertContent != NULL)
413 sqlite3_finalize (plugin->insertContent);
414 result = sqlite3_close (plugin->dbh);
415 #if SQLITE_VERSION_NUMBER >= 3007000
416 if (result == SQLITE_BUSY)
418 GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING, "sqlite",
420 ("Tried to close sqlite without finalizing all prepared statements.\n"));
421 stmt = sqlite3_next_stmt (plugin->dbh, NULL);
425 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "sqlite",
426 "Closing statement %p\n", stmt);
428 result = sqlite3_finalize (stmt);
430 if (result != SQLITE_OK)
431 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "sqlite",
432 "Failed to close statement %p: %d\n", stmt, result);
434 stmt = sqlite3_next_stmt (plugin->dbh, NULL);
436 result = sqlite3_close (plugin->dbh);
439 if (SQLITE_OK != result)
440 LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR, "sqlite3_close");
442 GNUNET_free_non_null (plugin->fn);
447 * Delete the database entry with the given
450 * @param plugin the plugin context (state for this module)
451 * @param rid the ID of the row to delete
454 delete_by_rowid (struct Plugin *plugin, unsigned long long rid)
456 if (SQLITE_OK != sqlite3_bind_int64 (plugin->delRow, 1, rid))
458 LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
459 "sqlite3_bind_XXXX");
460 if (SQLITE_OK != sqlite3_reset (plugin->delRow))
461 LOG_SQLITE (plugin, NULL,
462 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
464 return GNUNET_SYSERR;
466 if (SQLITE_DONE != sqlite3_step (plugin->delRow))
468 LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
470 if (SQLITE_OK != sqlite3_reset (plugin->delRow))
471 LOG_SQLITE (plugin, NULL,
472 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
474 return GNUNET_SYSERR;
476 if (SQLITE_OK != sqlite3_reset (plugin->delRow))
477 LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
484 * Store an item in the datastore.
487 * @param key key for the item
488 * @param size number of bytes in data
489 * @param data content stored
490 * @param type type of the content
491 * @param priority priority of the content
492 * @param anonymity anonymity-level for the content
493 * @param replication replication-level for the content
494 * @param expiration expiration time for the content
495 * @param msg set to an error message
496 * @return GNUNET_OK on success
499 sqlite_plugin_put (void *cls, const GNUNET_HashCode * key, uint32_t size,
500 const void *data, enum GNUNET_BLOCK_Type type,
501 uint32_t priority, uint32_t anonymity, uint32_t replication,
502 struct GNUNET_TIME_Absolute expiration, char **msg)
504 struct Plugin *plugin = cls;
508 GNUNET_HashCode vhash;
511 if (size > MAX_ITEM_SIZE)
512 return GNUNET_SYSERR;
514 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "sqlite",
515 "Storing in database block with type %u/key `%s'/priority %u/expiration in %llu ms (%lld).\n",
516 type, GNUNET_h2s (key), priority,
518 GNUNET_TIME_absolute_get_remaining (expiration).rel_value,
519 (long long) expiration.abs_value);
521 GNUNET_CRYPTO_hash (data, size, &vhash);
522 stmt = plugin->insertContent;
523 rvalue = GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK, UINT64_MAX);
524 if ((SQLITE_OK != sqlite3_bind_int (stmt, 1, replication)) ||
525 (SQLITE_OK != sqlite3_bind_int (stmt, 2, type)) ||
526 (SQLITE_OK != sqlite3_bind_int (stmt, 3, priority)) ||
527 (SQLITE_OK != sqlite3_bind_int (stmt, 4, anonymity)) ||
528 (SQLITE_OK != sqlite3_bind_int64 (stmt, 5, expiration.abs_value)) ||
529 (SQLITE_OK != sqlite3_bind_int64 (stmt, 6, rvalue)) ||
531 sqlite3_bind_blob (stmt, 7, key, sizeof (GNUNET_HashCode),
532 SQLITE_TRANSIENT)) ||
534 sqlite3_bind_blob (stmt, 8, &vhash, sizeof (GNUNET_HashCode),
535 SQLITE_TRANSIENT)) ||
536 (SQLITE_OK != sqlite3_bind_blob (stmt, 9, data, size, SQLITE_TRANSIENT)))
538 LOG_SQLITE (plugin, msg, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
539 "sqlite3_bind_XXXX");
540 if (SQLITE_OK != sqlite3_reset (stmt))
541 LOG_SQLITE (plugin, NULL,
542 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
544 return GNUNET_SYSERR;
546 n = sqlite3_step (stmt);
550 plugin->env->duc (plugin->env->cls, size + GNUNET_DATASTORE_ENTRY_OVERHEAD);
552 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "sqlite",
553 "Stored new entry (%u bytes)\n",
554 size + GNUNET_DATASTORE_ENTRY_OVERHEAD);
560 LOG_SQLITE (plugin, msg, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
565 LOG_SQLITE (plugin, msg, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
567 if (SQLITE_OK != sqlite3_reset (stmt))
568 LOG_SQLITE (plugin, NULL,
569 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
571 database_shutdown (plugin);
572 database_setup (plugin->env->cfg, plugin);
573 return GNUNET_SYSERR;
575 if (SQLITE_OK != sqlite3_reset (stmt))
576 LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
583 * Update the priority for a particular key in the datastore. If
584 * the expiration time in value is different than the time found in
585 * the datastore, the higher value should be kept. For the
586 * anonymity level, the lower value is to be used. The specified
587 * priority should be added to the existing priority, ignoring the
590 * Note that it is possible for multiple values to match this put.
591 * In that case, all of the respective values are updated.
593 * @param cls the plugin context (state for this module)
594 * @param uid unique identifier of the datum
595 * @param delta by how much should the priority
596 * change? If priority + delta < 0 the
597 * priority should be set to 0 (never go
599 * @param expire new expiration time should be the
600 * MAX of any existing expiration time and
602 * @param msg set to an error message
603 * @return GNUNET_OK on success
606 sqlite_plugin_update (void *cls, uint64_t uid, int delta,
607 struct GNUNET_TIME_Absolute expire, char **msg)
609 struct Plugin *plugin = cls;
612 if ((SQLITE_OK != sqlite3_bind_int (plugin->updPrio, 1, delta)) ||
613 (SQLITE_OK != sqlite3_bind_int64 (plugin->updPrio, 2, expire.abs_value))
614 || (SQLITE_OK != sqlite3_bind_int64 (plugin->updPrio, 3, uid)))
616 LOG_SQLITE (plugin, msg, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
617 "sqlite3_bind_XXXX");
618 if (SQLITE_OK != sqlite3_reset (plugin->updPrio))
619 LOG_SQLITE (plugin, NULL,
620 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
622 return GNUNET_SYSERR;
625 n = sqlite3_step (plugin->updPrio);
626 if (SQLITE_OK != sqlite3_reset (plugin->updPrio))
627 LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
633 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "sqlite", "Block updated\n");
637 LOG_SQLITE (plugin, msg, GNUNET_ERROR_TYPE_WARNING | GNUNET_ERROR_TYPE_BULK,
641 LOG_SQLITE (plugin, msg, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
643 return GNUNET_SYSERR;
649 * Execute statement that gets a row and call the callback
650 * with the result. Resets the statement afterwards.
652 * @param plugin the plugin
653 * @param stmt the statement
654 * @param proc processor to call
655 * @param proc_cls closure for 'proc'
658 execute_get (struct Plugin *plugin, sqlite3_stmt * stmt,
659 PluginDatumProcessor proc, void *proc_cls)
662 struct GNUNET_TIME_Absolute expiration;
663 unsigned long long rowid;
667 n = sqlite3_step (stmt);
671 size = sqlite3_column_bytes (stmt, 5);
672 rowid = sqlite3_column_int64 (stmt, 6);
673 if (sqlite3_column_bytes (stmt, 4) != sizeof (GNUNET_HashCode))
675 GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING, "sqlite",
677 ("Invalid data in database. Trying to fix (by deletion).\n"));
678 if (SQLITE_OK != sqlite3_reset (stmt))
679 LOG_SQLITE (plugin, NULL,
680 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
682 if (GNUNET_OK == delete_by_rowid (plugin, rowid))
683 plugin->env->duc (plugin->env->cls,
684 -(size + GNUNET_DATASTORE_ENTRY_OVERHEAD));
687 expiration.abs_value = sqlite3_column_int64 (stmt, 3);
689 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "sqlite",
690 "Found reply in database with expiration %llu\n",
691 (unsigned long long) expiration.abs_value);
693 ret = proc (proc_cls, sqlite3_column_blob (stmt, 4) /* key */ ,
694 size, sqlite3_column_blob (stmt, 5) /* data */ ,
695 sqlite3_column_int (stmt, 0) /* type */ ,
696 sqlite3_column_int (stmt, 1) /* priority */ ,
697 sqlite3_column_int (stmt, 2) /* anonymity */ ,
699 if (SQLITE_OK != sqlite3_reset (stmt))
700 LOG_SQLITE (plugin, NULL,
701 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
703 if ((GNUNET_NO == ret) && (GNUNET_OK == delete_by_rowid (plugin, rowid)))
704 plugin->env->duc (plugin->env->cls,
705 -(size + GNUNET_DATASTORE_ENTRY_OVERHEAD));
708 /* database must be empty */
709 if (SQLITE_OK != sqlite3_reset (stmt))
710 LOG_SQLITE (plugin, NULL,
711 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
718 LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
720 if (SQLITE_OK != sqlite3_reset (stmt))
721 LOG_SQLITE (plugin, NULL,
722 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
725 database_shutdown (plugin);
726 database_setup (plugin->env->cfg, plugin);
729 if (SQLITE_OK != sqlite3_reset (stmt))
730 LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
732 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 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);
778 * Get results for a particular key in the datastore.
781 * @param offset offset (mod count).
782 * @param key key to match, never NULL
783 * @param vhash hash of the value, maybe NULL (to
784 * match all values that have the right key).
785 * Note that for DBlocks there is no difference
786 * betwen key and vhash, but for other blocks
788 * @param type entries of which type are relevant?
789 * Use 0 for any type.
790 * @param proc function to call on each matching value;
791 * will be called once with a NULL value at the end
792 * @param proc_cls closure for proc
795 sqlite_plugin_get_key (void *cls, uint64_t offset, const GNUNET_HashCode * key,
796 const GNUNET_HashCode * vhash,
797 enum GNUNET_BLOCK_Type type, PluginDatumProcessor proc,
800 struct Plugin *plugin = cls;
808 GNUNET_assert (proc != NULL);
809 GNUNET_assert (key != NULL);
810 GNUNET_snprintf (scratch, sizeof (scratch),
811 "SELECT count(*) FROM gn090 WHERE hash=?%s%s",
812 vhash == NULL ? "" : " AND vhash=?",
813 type == 0 ? "" : " AND type=?");
814 if (sq_prepare (plugin->dbh, scratch, &stmt) != SQLITE_OK)
816 LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
818 proc (proc_cls, NULL, 0, NULL, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0);
823 sqlite3_bind_blob (stmt, sqoff++, key, sizeof (GNUNET_HashCode),
825 if ((vhash != NULL) && (ret == SQLITE_OK))
827 sqlite3_bind_blob (stmt, sqoff++, vhash, sizeof (GNUNET_HashCode),
829 if ((type != 0) && (ret == SQLITE_OK))
830 ret = sqlite3_bind_int (stmt, sqoff++, type);
831 if (SQLITE_OK != ret)
833 LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR, "sqlite_bind");
834 sqlite3_finalize (stmt);
835 proc (proc_cls, NULL, 0, NULL, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0);
838 ret = sqlite3_step (stmt);
839 if (ret != SQLITE_ROW)
841 LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
843 sqlite3_finalize (stmt);
844 proc (proc_cls, NULL, 0, NULL, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0);
847 total = sqlite3_column_int (stmt, 0);
848 sqlite3_finalize (stmt);
851 proc (proc_cls, NULL, 0, NULL, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0);
854 limit_off = (int) (offset % total);
857 GNUNET_snprintf (scratch, sizeof (scratch),
858 "SELECT type, prio, anonLevel, expire, hash, value, _ROWID_ "
859 "FROM gn090 WHERE hash=?%s%s "
860 "ORDER BY _ROWID_ ASC LIMIT 1 OFFSET ?",
861 vhash == NULL ? "" : " AND vhash=?",
862 type == 0 ? "" : " AND type=?");
863 if (sq_prepare (plugin->dbh, scratch, &stmt) != SQLITE_OK)
865 LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
867 proc (proc_cls, NULL, 0, NULL, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0);
872 sqlite3_bind_blob (stmt, sqoff++, key, sizeof (GNUNET_HashCode),
874 if ((vhash != NULL) && (ret == SQLITE_OK))
876 sqlite3_bind_blob (stmt, sqoff++, vhash, sizeof (GNUNET_HashCode),
878 if ((type != 0) && (ret == SQLITE_OK))
879 ret = sqlite3_bind_int (stmt, sqoff++, type);
880 if (ret == SQLITE_OK)
881 ret = sqlite3_bind_int64 (stmt, sqoff++, limit_off);
882 if (ret != SQLITE_OK)
884 LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
886 proc (proc_cls, NULL, 0, NULL, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0);
889 execute_get (plugin, stmt, proc, proc_cls);
890 sqlite3_finalize (stmt);
896 * Context for 'repl_proc' function.
902 * Function to call for the result (or the NULL).
904 PluginDatumProcessor proc;
917 * Yes if UID was set.
924 * Wrapper for the processor for 'sqlite_plugin_replication_get'.
925 * Decrements the replication counter and calls the original
929 * @param key key for the content
930 * @param size number of bytes in data
931 * @param data content stored
932 * @param type type of the content
933 * @param priority priority of the content
934 * @param anonymity anonymity-level for the content
935 * @param expiration expiration time for the content
936 * @param uid unique identifier for the datum;
937 * maybe 0 if no unique identifier is available
939 * @return GNUNET_OK for normal return,
940 * GNUNET_NO to delete the item
943 repl_proc (void *cls, const GNUNET_HashCode * key, uint32_t size,
944 const void *data, enum GNUNET_BLOCK_Type type, uint32_t priority,
945 uint32_t anonymity, struct GNUNET_TIME_Absolute expiration,
948 struct ReplCtx *rc = cls;
952 rc->proc (rc->proc_cls, key, size, data, type, priority, anonymity,
957 rc->have_uid = GNUNET_YES;
964 * Get a random item for replication. Returns a single random item
965 * from those with the highest replication counters. The item's
966 * replication counter is decremented by one IF it was positive before.
967 * Call 'proc' with all values ZERO or NULL if the datastore is empty.
970 * @param proc function to call the value (once only).
971 * @param proc_cls closure for proc
974 sqlite_plugin_get_replication (void *cls, PluginDatumProcessor proc,
977 struct Plugin *plugin = cls;
984 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "sqlite",
985 "Getting random block based on replication order.\n");
987 rc.have_uid = GNUNET_NO;
989 rc.proc_cls = proc_cls;
990 stmt = plugin->maxRepl;
991 if (SQLITE_ROW != sqlite3_step (stmt))
993 if (SQLITE_OK != sqlite3_reset (stmt))
994 LOG_SQLITE (plugin, NULL,
995 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
998 proc (proc_cls, NULL, 0, NULL, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0);
1001 repl = sqlite3_column_int (stmt, 0);
1002 if (SQLITE_OK != sqlite3_reset (stmt))
1003 LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
1005 stmt = plugin->selRepl;
1006 rvalue = GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK, UINT64_MAX);
1007 if (SQLITE_OK != sqlite3_bind_int64 (stmt, 1, rvalue))
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 if (SQLITE_OK != sqlite3_bind_int (stmt, 2, repl))
1020 LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
1021 "sqlite3_bind_XXXX");
1022 if (SQLITE_OK != sqlite3_reset (stmt))
1023 LOG_SQLITE (plugin, NULL,
1024 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
1026 proc (proc_cls, NULL, 0, NULL, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0);
1029 execute_get (plugin, stmt, &repl_proc, &rc);
1030 if (GNUNET_YES == rc.have_uid)
1032 if (SQLITE_OK != sqlite3_bind_int64 (plugin->updRepl, 1, rc.uid))
1034 LOG_SQLITE (plugin, NULL,
1035 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
1036 "sqlite3_bind_XXXX");
1037 if (SQLITE_OK != sqlite3_reset (plugin->updRepl))
1038 LOG_SQLITE (plugin, NULL,
1039 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
1043 if (SQLITE_DONE != sqlite3_step (plugin->updRepl))
1044 LOG_SQLITE (plugin, NULL,
1045 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
1047 if (SQLITE_OK != sqlite3_reset (plugin->updRepl))
1048 LOG_SQLITE (plugin, NULL,
1049 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
1057 * Get a random item that has expired or has low priority.
1058 * Call 'proc' with all values ZERO or NULL if the datastore is empty.
1060 * @param cls closure
1061 * @param proc function to call the value (once only).
1062 * @param proc_cls closure for proc
1065 sqlite_plugin_get_expiration (void *cls, PluginDatumProcessor proc,
1068 struct Plugin *plugin = cls;
1070 struct GNUNET_TIME_Absolute now;
1073 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "sqlite",
1074 "Getting random block based on expiration and priority order.\n");
1076 now = GNUNET_TIME_absolute_get ();
1077 stmt = plugin->selExpi;
1078 if (SQLITE_OK != sqlite3_bind_int64 (stmt, 1, now.abs_value))
1080 LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
1081 "sqlite3_bind_XXXX");
1082 if (SQLITE_OK != sqlite3_reset (stmt))
1083 LOG_SQLITE (plugin, NULL,
1084 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
1086 proc (proc_cls, NULL, 0, NULL, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0);
1089 execute_get (plugin, stmt, proc, proc_cls);
1096 * @param cls our plugin context
1099 sqlite_plugin_drop (void *cls)
1101 struct Plugin *plugin = cls;
1103 plugin->drop_on_shutdown = GNUNET_YES;
1108 * Get an estimate of how much space the database is
1111 * @param cls the 'struct Plugin'
1112 * @return the size of the database on disk (estimate)
1114 static unsigned long long
1115 sqlite_plugin_estimate_size (void *cls)
1117 struct Plugin *plugin = cls;
1126 if (SQLITE_VERSION_NUMBER < 3006000)
1128 GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING, "datastore-sqlite",
1130 ("sqlite version to old to determine size, assuming zero\n"));
1133 CHECK (SQLITE_OK == sqlite3_exec (plugin->dbh, "VACUUM", NULL, NULL, ENULL));
1135 sqlite3_exec (plugin->dbh, "PRAGMA auto_vacuum=INCREMENTAL", NULL,
1137 CHECK (SQLITE_OK == sq_prepare (plugin->dbh, "PRAGMA page_count", &stmt));
1138 if (SQLITE_ROW == sqlite3_step (stmt))
1139 pages = sqlite3_column_int64 (stmt, 0);
1142 sqlite3_finalize (stmt);
1143 CHECK (SQLITE_OK == sq_prepare (plugin->dbh, "PRAGMA page_size", &stmt));
1144 CHECK (SQLITE_ROW == sqlite3_step (stmt));
1145 page_size = sqlite3_column_int64 (stmt, 0);
1146 sqlite3_finalize (stmt);
1147 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1149 ("Using sqlite page utilization to estimate payload (%llu pages of size %llu bytes)\n"),
1150 (unsigned long long) pages, (unsigned long long) page_size);
1151 return pages * page_size;
1156 * Entry point for the plugin.
1158 * @param cls the "struct GNUNET_DATASTORE_PluginEnvironment*"
1159 * @return NULL on error, othrewise the plugin context
1162 libgnunet_plugin_datastore_sqlite_init (void *cls)
1164 static struct Plugin plugin;
1165 struct GNUNET_DATASTORE_PluginEnvironment *env = cls;
1166 struct GNUNET_DATASTORE_PluginFunctions *api;
1168 if (plugin.env != NULL)
1169 return NULL; /* can only initialize once! */
1170 memset (&plugin, 0, sizeof (struct Plugin));
1172 if (GNUNET_OK != database_setup (env->cfg, &plugin))
1174 database_shutdown (&plugin);
1177 api = GNUNET_malloc (sizeof (struct GNUNET_DATASTORE_PluginFunctions));
1179 api->estimate_size = &sqlite_plugin_estimate_size;
1180 api->put = &sqlite_plugin_put;
1181 api->update = &sqlite_plugin_update;
1182 api->get_key = &sqlite_plugin_get_key;
1183 api->get_replication = &sqlite_plugin_get_replication;
1184 api->get_expiration = &sqlite_plugin_get_expiration;
1185 api->get_zero_anonymity = &sqlite_plugin_get_zero_anonymity;
1186 api->drop = &sqlite_plugin_drop;
1187 GNUNET_log_from (GNUNET_ERROR_TYPE_INFO, "sqlite",
1188 _("Sqlite database running\n"));
1194 * Exit point from the plugin.
1196 * @param cls the plugin context (as returned by "init")
1197 * @return always NULL
1200 libgnunet_plugin_datastore_sqlite_done (void *cls)
1203 struct GNUNET_DATASTORE_PluginFunctions *api = cls;
1204 struct Plugin *plugin = api->cls;
1207 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "sqlite",
1208 "sqlite plugin is done\n");
1212 if (plugin->drop_on_shutdown)
1213 fn = GNUNET_strdup (plugin->fn);
1215 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "sqlite",
1216 "Shutting down database\n");
1218 database_shutdown (plugin);
1223 if (0 != UNLINK (fn))
1224 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "unlink", fn);
1228 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "sqlite",
1229 "sqlite plugin is finished\n");
1234 /* end of plugin_datastore_sqlite.c */