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, const char *zSql, sqlite3_stmt ** ppStmt)
144 sqlite3_prepare_v2 (dbh, zSql, strlen (zSql), ppStmt,
145 (const char **) &dummy);
146 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "sqlite",
147 "Prepared `%s' / %p: %d\n", zSql, *ppStmt, result);
153 * Create our database indices.
155 * @param dbh handle to the database
158 create_indices (sqlite3 * dbh)
162 sqlite3_exec (dbh, "CREATE INDEX IF NOT EXISTS idx_hash ON gn090 (hash)",
163 NULL, NULL, NULL)) ||
166 "CREATE INDEX IF NOT EXISTS idx_hash_vhash ON gn090 (hash,vhash)",
167 NULL, NULL, NULL)) ||
170 "CREATE INDEX IF NOT EXISTS idx_expire_repl ON gn090 (expire ASC,repl DESC)",
171 NULL, NULL, NULL)) ||
174 "CREATE INDEX IF NOT EXISTS idx_comb ON gn090 (anonLevel ASC,expire ASC,prio,type,hash)",
175 NULL, NULL, NULL)) ||
178 "CREATE INDEX IF NOT EXISTS idx_anon_type_hash ON gn090 (anonLevel ASC,type,hash)",
179 NULL, NULL, NULL)) ||
182 "CREATE INDEX IF NOT EXISTS idx_expire ON gn090 (expire ASC)",
183 NULL, NULL, NULL)) ||
186 "CREATE INDEX IF NOT EXISTS idx_repl_rvalue ON gn090 (repl,rvalue)",
187 NULL, NULL, NULL)) ||
190 "CREATE INDEX IF NOT EXISTS idx_repl ON gn090 (repl DESC)",
192 GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, "sqlite",
193 "Failed to create indices: %s\n", sqlite3_errmsg (dbh));
198 #define CHECK(a) GNUNET_break(a)
202 #define ENULL_DEFINED 1
203 #define CHECK(a) if (! a) { GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "%s\n", e); sqlite3_free(e); }
208 * Initialize the database connections and associated
209 * data structures (create tables and indices
210 * as needed as well).
212 * @param cfg our configuration
213 * @param plugin the plugin context (state for this module)
214 * @return GNUNET_OK on success
217 database_setup (const struct GNUNET_CONFIGURATION_Handle *cfg,
218 struct Plugin *plugin)
228 GNUNET_CONFIGURATION_get_value_filename (cfg, "datastore-sqlite",
229 "FILENAME", &afsdir))
231 GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR,
232 "datastore-sqlite", "FILENAME");
233 return GNUNET_SYSERR;
235 if (GNUNET_OK != GNUNET_DISK_file_test (afsdir))
237 if (GNUNET_OK != GNUNET_DISK_directory_create_for_file (afsdir))
240 GNUNET_free (afsdir);
241 return GNUNET_SYSERR;
243 /* database is new or got deleted, reset payload to zero! */
244 plugin->env->duc (plugin->env->cls, 0);
248 GNUNET_STRINGS_to_utf8 (afsdir, strlen (afsdir), nl_langinfo (CODESET));
250 plugin->fn = GNUNET_STRINGS_to_utf8 (afsdir, strlen (afsdir), "UTF-8"); /* good luck */
252 GNUNET_free (afsdir);
254 /* Open database and precompile statements */
255 if (sqlite3_open (plugin->fn, &plugin->dbh) != SQLITE_OK)
257 GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, "sqlite",
258 _("Unable to initialize SQLite: %s.\n"),
259 sqlite3_errmsg (plugin->dbh));
260 return GNUNET_SYSERR;
263 sqlite3_exec (plugin->dbh, "PRAGMA temp_store=MEMORY", NULL, NULL,
266 sqlite3_exec (plugin->dbh, "PRAGMA synchronous=OFF", NULL, NULL,
269 sqlite3_exec (plugin->dbh, "PRAGMA legacy_file_format=OFF", NULL, NULL,
272 sqlite3_exec (plugin->dbh, "PRAGMA auto_vacuum=INCREMENTAL", NULL,
275 sqlite3_exec (plugin->dbh, "PRAGMA locking_mode=EXCLUSIVE", NULL, NULL,
278 sqlite3_exec (plugin->dbh, "PRAGMA count_changes=OFF", NULL, NULL,
281 sqlite3_exec (plugin->dbh, "PRAGMA page_size=4092", NULL, NULL,
284 CHECK (SQLITE_OK == sqlite3_busy_timeout (plugin->dbh, BUSY_TIMEOUT_MS));
287 /* We have to do it here, because otherwise precompiling SQL might fail */
289 sq_prepare (plugin->dbh,
290 "SELECT 1 FROM sqlite_master WHERE tbl_name = 'gn090'",
292 if ((sqlite3_step (stmt) == SQLITE_DONE) &&
295 "CREATE TABLE gn090 (" " repl INT4 NOT NULL DEFAULT 0,"
296 " type INT4 NOT NULL DEFAULT 0," " prio INT4 NOT NULL DEFAULT 0,"
297 " anonLevel INT4 NOT NULL DEFAULT 0,"
298 " expire INT8 NOT NULL DEFAULT 0," " rvalue INT8 NOT NULL,"
299 " hash TEXT NOT NULL DEFAULT ''," " vhash TEXT NOT NULL DEFAULT '',"
300 " value BLOB NOT NULL DEFAULT '')", NULL, NULL, NULL) != SQLITE_OK))
302 LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR, "sqlite3_exec");
303 sqlite3_finalize (stmt);
304 return GNUNET_SYSERR;
306 sqlite3_finalize (stmt);
307 create_indices (plugin->dbh);
312 "SET prio = prio + ?, expire = MAX(expire,?) WHERE _ROWID_ = ?",
313 &plugin->updPrio) != SQLITE_OK) ||
316 "UPDATE gn090 " "SET repl = MAX (0, repl - 1) WHERE _ROWID_ = ?",
317 &plugin->updRepl) != SQLITE_OK) ||
320 "SELECT type,prio,anonLevel,expire,hash,value,_ROWID_ " "FROM gn090 "
321 #if SQLITE_VERSION_NUMBER >= 3007000
322 "INDEXED BY idx_repl_rvalue "
324 "WHERE repl=?2 AND " " (rvalue>=?1 OR "
325 " NOT EXISTS (SELECT 1 FROM gn090 "
326 #if SQLITE_VERSION_NUMBER >= 3007000
327 "INDEXED BY idx_repl_rvalue "
329 "WHERE repl=?2 AND rvalue>=?1 LIMIT 1) ) "
330 "ORDER BY rvalue ASC LIMIT 1", &plugin->selRepl) != SQLITE_OK) ||
331 (sq_prepare (plugin->dbh, "SELECT MAX(repl) FROM gn090"
332 #if SQLITE_VERSION_NUMBER >= 3007000
333 " INDEXED BY idx_repl_rvalue"
335 "", &plugin->maxRepl) != SQLITE_OK) ||
338 "SELECT type,prio,anonLevel,expire,hash,value,_ROWID_ " "FROM gn090 "
339 #if SQLITE_VERSION_NUMBER >= 3007000
340 "INDEXED BY idx_expire "
342 "WHERE NOT EXISTS (SELECT 1 FROM gn090 WHERE expire < ?1 LIMIT 1) OR (expire < ?1) "
343 "ORDER BY expire ASC LIMIT 1", &plugin->selExpi) != SQLITE_OK) ||
346 "SELECT type,prio,anonLevel,expire,hash,value,_ROWID_ " "FROM gn090 "
347 #if SQLITE_VERSION_NUMBER >= 3007000
348 "INDEXED BY idx_anon_type_hash "
350 "WHERE (anonLevel = 0 AND type=?1) "
351 "ORDER BY hash DESC LIMIT 1 OFFSET ?2",
352 &plugin->selZeroAnon) != SQLITE_OK) ||
355 "INSERT INTO gn090 (repl, type, prio, anonLevel, expire, rvalue, hash, vhash, value) "
356 "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)",
357 &plugin->insertContent) != SQLITE_OK) ||
359 (plugin->dbh, "DELETE FROM gn090 WHERE _ROWID_ = ?",
360 &plugin->delRow) != SQLITE_OK))
362 LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR, "precompiling");
363 return GNUNET_SYSERR;
371 * Shutdown database connection and associate data
373 * @param plugin the plugin context (state for this module)
376 database_shutdown (struct Plugin *plugin)
380 #if SQLITE_VERSION_NUMBER >= 3007000
384 if (plugin->delRow != NULL)
385 sqlite3_finalize (plugin->delRow);
386 if (plugin->updPrio != NULL)
387 sqlite3_finalize (plugin->updPrio);
388 if (plugin->updRepl != NULL)
389 sqlite3_finalize (plugin->updRepl);
390 if (plugin->selRepl != NULL)
391 sqlite3_finalize (plugin->selRepl);
392 if (plugin->maxRepl != NULL)
393 sqlite3_finalize (plugin->maxRepl);
394 if (plugin->selExpi != NULL)
395 sqlite3_finalize (plugin->selExpi);
396 if (plugin->selZeroAnon != NULL)
397 sqlite3_finalize (plugin->selZeroAnon);
398 if (plugin->insertContent != NULL)
399 sqlite3_finalize (plugin->insertContent);
400 result = sqlite3_close (plugin->dbh);
401 #if SQLITE_VERSION_NUMBER >= 3007000
402 if (result == SQLITE_BUSY)
404 GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING, "sqlite",
406 ("Tried to close sqlite without finalizing all prepared statements.\n"));
407 stmt = sqlite3_next_stmt (plugin->dbh, NULL);
410 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "sqlite",
411 "Closing statement %p\n", stmt);
412 result = sqlite3_finalize (stmt);
413 if (result != SQLITE_OK)
414 GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING, "sqlite",
415 "Failed to close statement %p: %d\n", stmt, result);
416 stmt = sqlite3_next_stmt (plugin->dbh, NULL);
418 result = sqlite3_close (plugin->dbh);
421 if (SQLITE_OK != result)
422 LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR, "sqlite3_close");
424 GNUNET_free_non_null (plugin->fn);
429 * Delete the database entry with the given
432 * @param plugin the plugin context (state for this module)
433 * @param rid the ID of the row to delete
436 delete_by_rowid (struct Plugin *plugin, unsigned long long rid)
438 if (SQLITE_OK != sqlite3_bind_int64 (plugin->delRow, 1, rid))
440 LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
441 "sqlite3_bind_XXXX");
442 if (SQLITE_OK != sqlite3_reset (plugin->delRow))
443 LOG_SQLITE (plugin, NULL,
444 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
446 return GNUNET_SYSERR;
448 if (SQLITE_DONE != sqlite3_step (plugin->delRow))
450 LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
452 if (SQLITE_OK != sqlite3_reset (plugin->delRow))
453 LOG_SQLITE (plugin, NULL,
454 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
456 return GNUNET_SYSERR;
458 if (SQLITE_OK != sqlite3_reset (plugin->delRow))
459 LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
466 * Store an item in the datastore.
469 * @param key key for the item
470 * @param size number of bytes in data
471 * @param data content stored
472 * @param type type of the content
473 * @param priority priority of the content
474 * @param anonymity anonymity-level for the content
475 * @param replication replication-level for the content
476 * @param expiration expiration time for the content
477 * @param msg set to an error message
478 * @return GNUNET_OK on success
481 sqlite_plugin_put (void *cls, const struct GNUNET_HashCode * key, uint32_t size,
482 const void *data, enum GNUNET_BLOCK_Type type,
483 uint32_t priority, uint32_t anonymity, uint32_t replication,
484 struct GNUNET_TIME_Absolute expiration, char **msg)
486 struct Plugin *plugin = cls;
490 struct GNUNET_HashCode vhash;
493 if (size > MAX_ITEM_SIZE)
494 return GNUNET_SYSERR;
495 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "sqlite",
496 "Storing in database block with type %u/key `%s'/priority %u/expiration in %llu ms (%lld).\n",
497 type, GNUNET_h2s (key), priority,
499 GNUNET_TIME_absolute_get_remaining (expiration).rel_value,
500 (long long) expiration.abs_value);
501 GNUNET_CRYPTO_hash (data, size, &vhash);
502 stmt = plugin->insertContent;
503 rvalue = GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK, UINT64_MAX);
504 if ((SQLITE_OK != sqlite3_bind_int (stmt, 1, replication)) ||
505 (SQLITE_OK != sqlite3_bind_int (stmt, 2, type)) ||
506 (SQLITE_OK != sqlite3_bind_int (stmt, 3, priority)) ||
507 (SQLITE_OK != sqlite3_bind_int (stmt, 4, anonymity)) ||
508 (SQLITE_OK != sqlite3_bind_int64 (stmt, 5, expiration.abs_value)) ||
509 (SQLITE_OK != sqlite3_bind_int64 (stmt, 6, rvalue)) ||
511 sqlite3_bind_blob (stmt, 7, key, sizeof (struct GNUNET_HashCode),
512 SQLITE_TRANSIENT)) ||
514 sqlite3_bind_blob (stmt, 8, &vhash, sizeof (struct GNUNET_HashCode),
515 SQLITE_TRANSIENT)) ||
516 (SQLITE_OK != sqlite3_bind_blob (stmt, 9, data, size, SQLITE_TRANSIENT)))
518 LOG_SQLITE (plugin, msg, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
519 "sqlite3_bind_XXXX");
520 if (SQLITE_OK != sqlite3_reset (stmt))
521 LOG_SQLITE (plugin, NULL,
522 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
524 return GNUNET_SYSERR;
526 n = sqlite3_step (stmt);
530 plugin->env->duc (plugin->env->cls, size + GNUNET_DATASTORE_ENTRY_OVERHEAD);
531 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "sqlite",
532 "Stored new entry (%u bytes)\n",
533 size + GNUNET_DATASTORE_ENTRY_OVERHEAD);
538 LOG_SQLITE (plugin, msg, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
543 LOG_SQLITE (plugin, msg, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
545 if (SQLITE_OK != sqlite3_reset (stmt))
546 LOG_SQLITE (plugin, NULL,
547 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
549 database_shutdown (plugin);
550 database_setup (plugin->env->cfg, plugin);
551 return GNUNET_SYSERR;
553 if (SQLITE_OK != sqlite3_reset (stmt))
554 LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
561 * Update the priority for a particular key in the datastore. If
562 * the expiration time in value is different than the time found in
563 * the datastore, the higher value should be kept. For the
564 * anonymity level, the lower value is to be used. The specified
565 * priority should be added to the existing priority, ignoring the
568 * Note that it is possible for multiple values to match this put.
569 * In that case, all of the respective values are updated.
571 * @param cls the plugin context (state for this module)
572 * @param uid unique identifier of the datum
573 * @param delta by how much should the priority
574 * change? If priority + delta < 0 the
575 * priority should be set to 0 (never go
577 * @param expire new expiration time should be the
578 * MAX of any existing expiration time and
580 * @param msg set to an error message
581 * @return GNUNET_OK on success
584 sqlite_plugin_update (void *cls, uint64_t uid, int delta,
585 struct GNUNET_TIME_Absolute expire, char **msg)
587 struct Plugin *plugin = cls;
590 if ((SQLITE_OK != sqlite3_bind_int (plugin->updPrio, 1, delta)) ||
591 (SQLITE_OK != sqlite3_bind_int64 (plugin->updPrio, 2, expire.abs_value))
592 || (SQLITE_OK != sqlite3_bind_int64 (plugin->updPrio, 3, uid)))
594 LOG_SQLITE (plugin, msg, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
595 "sqlite3_bind_XXXX");
596 if (SQLITE_OK != sqlite3_reset (plugin->updPrio))
597 LOG_SQLITE (plugin, NULL,
598 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
600 return GNUNET_SYSERR;
603 n = sqlite3_step (plugin->updPrio);
604 if (SQLITE_OK != sqlite3_reset (plugin->updPrio))
605 LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
610 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "sqlite", "Block updated\n");
613 LOG_SQLITE (plugin, msg, GNUNET_ERROR_TYPE_WARNING | GNUNET_ERROR_TYPE_BULK,
617 LOG_SQLITE (plugin, msg, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
619 return GNUNET_SYSERR;
625 * Execute statement that gets a row and call the callback
626 * with the result. Resets the statement afterwards.
628 * @param plugin the plugin
629 * @param stmt the statement
630 * @param proc processor to call
631 * @param proc_cls closure for 'proc'
634 execute_get (struct Plugin *plugin, sqlite3_stmt * stmt,
635 PluginDatumProcessor proc, void *proc_cls)
638 struct GNUNET_TIME_Absolute expiration;
639 unsigned long long rowid;
643 n = sqlite3_step (stmt);
647 size = sqlite3_column_bytes (stmt, 5);
648 rowid = sqlite3_column_int64 (stmt, 6);
649 if (sqlite3_column_bytes (stmt, 4) != sizeof (struct GNUNET_HashCode))
651 GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING, "sqlite",
653 ("Invalid data in database. Trying to fix (by deletion).\n"));
654 if (SQLITE_OK != sqlite3_reset (stmt))
655 LOG_SQLITE (plugin, NULL,
656 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
658 if (GNUNET_OK == delete_by_rowid (plugin, rowid))
659 plugin->env->duc (plugin->env->cls,
660 -(size + GNUNET_DATASTORE_ENTRY_OVERHEAD));
663 expiration.abs_value = sqlite3_column_int64 (stmt, 3);
664 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "sqlite",
665 "Found reply in database with expiration %llu\n",
666 (unsigned long long) expiration.abs_value);
667 ret = proc (proc_cls, sqlite3_column_blob (stmt, 4) /* key */ ,
668 size, sqlite3_column_blob (stmt, 5) /* data */ ,
669 sqlite3_column_int (stmt, 0) /* type */ ,
670 sqlite3_column_int (stmt, 1) /* priority */ ,
671 sqlite3_column_int (stmt, 2) /* anonymity */ ,
673 if (SQLITE_OK != sqlite3_reset (stmt))
674 LOG_SQLITE (plugin, NULL,
675 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
677 if ((GNUNET_NO == ret) && (GNUNET_OK == delete_by_rowid (plugin, rowid)))
678 plugin->env->duc (plugin->env->cls,
679 -(size + GNUNET_DATASTORE_ENTRY_OVERHEAD));
682 /* database must be empty */
683 if (SQLITE_OK != sqlite3_reset (stmt))
684 LOG_SQLITE (plugin, NULL,
685 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
692 LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
694 if (SQLITE_OK != sqlite3_reset (stmt))
695 LOG_SQLITE (plugin, NULL,
696 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
699 database_shutdown (plugin);
700 database_setup (plugin->env->cfg, plugin);
703 if (SQLITE_OK != sqlite3_reset (stmt))
704 LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
706 proc (proc_cls, NULL, 0, NULL, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0);
712 * Select a subset of the items in the datastore and call
713 * the given processor for the item.
715 * @param cls our plugin context
716 * @param offset offset of the result (modulo num-results);
717 * specific ordering does not matter for the offset
718 * @param type entries of which type should be considered?
719 * Use 0 for any type.
720 * @param proc function to call on each matching value;
721 * will be called once with a NULL value at the end
722 * @param proc_cls closure for proc
725 sqlite_plugin_get_zero_anonymity (void *cls, uint64_t offset,
726 enum GNUNET_BLOCK_Type type,
727 PluginDatumProcessor proc, void *proc_cls)
729 struct Plugin *plugin = cls;
732 GNUNET_assert (type != GNUNET_BLOCK_TYPE_ANY);
733 stmt = plugin->selZeroAnon;
734 if ((SQLITE_OK != sqlite3_bind_int (stmt, 1, type)) ||
735 (SQLITE_OK != sqlite3_bind_int64 (stmt, 2, offset)))
737 LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
738 "sqlite3_bind_XXXX");
739 if (SQLITE_OK != sqlite3_reset (stmt))
740 LOG_SQLITE (plugin, NULL,
741 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
743 proc (proc_cls, NULL, 0, NULL, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0);
746 execute_get (plugin, stmt, proc, proc_cls);
752 * Get results for a particular key in the datastore.
755 * @param offset offset (mod count).
756 * @param key key to match, never NULL
757 * @param vhash hash of the value, maybe NULL (to
758 * match all values that have the right key).
759 * Note that for DBlocks there is no difference
760 * betwen key and vhash, but for other blocks
762 * @param type entries of which type are relevant?
763 * Use 0 for any type.
764 * @param proc function to call on each matching value;
765 * will be called once with a NULL value at the end
766 * @param proc_cls closure for proc
769 sqlite_plugin_get_key (void *cls, uint64_t offset, const struct GNUNET_HashCode * key,
770 const struct GNUNET_HashCode * vhash,
771 enum GNUNET_BLOCK_Type type, PluginDatumProcessor proc,
774 struct Plugin *plugin = cls;
782 GNUNET_assert (proc != NULL);
783 GNUNET_assert (key != NULL);
784 GNUNET_snprintf (scratch, sizeof (scratch),
785 "SELECT count(*) FROM gn090 WHERE hash=?%s%s",
786 vhash == NULL ? "" : " AND vhash=?",
787 type == 0 ? "" : " AND type=?");
788 if (sq_prepare (plugin->dbh, scratch, &stmt) != SQLITE_OK)
790 LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
792 proc (proc_cls, NULL, 0, NULL, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0);
797 sqlite3_bind_blob (stmt, sqoff++, key, sizeof (struct GNUNET_HashCode),
799 if ((vhash != NULL) && (ret == SQLITE_OK))
801 sqlite3_bind_blob (stmt, sqoff++, vhash, sizeof (struct GNUNET_HashCode),
803 if ((type != 0) && (ret == SQLITE_OK))
804 ret = sqlite3_bind_int (stmt, sqoff++, type);
805 if (SQLITE_OK != ret)
807 LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR, "sqlite_bind");
808 sqlite3_finalize (stmt);
809 proc (proc_cls, NULL, 0, NULL, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0);
812 ret = sqlite3_step (stmt);
813 if (ret != SQLITE_ROW)
815 LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
817 sqlite3_finalize (stmt);
818 proc (proc_cls, NULL, 0, NULL, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0);
821 total = sqlite3_column_int (stmt, 0);
822 sqlite3_finalize (stmt);
825 proc (proc_cls, NULL, 0, NULL, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0);
828 limit_off = (int) (offset % total);
831 GNUNET_snprintf (scratch, sizeof (scratch),
832 "SELECT type, prio, anonLevel, expire, hash, value, _ROWID_ "
833 "FROM gn090 WHERE hash=?%s%s "
834 "ORDER BY _ROWID_ ASC LIMIT 1 OFFSET ?",
835 vhash == NULL ? "" : " AND vhash=?",
836 type == 0 ? "" : " AND type=?");
837 if (sq_prepare (plugin->dbh, scratch, &stmt) != SQLITE_OK)
839 LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
841 proc (proc_cls, NULL, 0, NULL, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0);
846 sqlite3_bind_blob (stmt, sqoff++, key, sizeof (struct GNUNET_HashCode),
848 if ((vhash != NULL) && (ret == SQLITE_OK))
850 sqlite3_bind_blob (stmt, sqoff++, vhash, sizeof (struct GNUNET_HashCode),
852 if ((type != 0) && (ret == SQLITE_OK))
853 ret = sqlite3_bind_int (stmt, sqoff++, type);
854 if (ret == SQLITE_OK)
855 ret = sqlite3_bind_int64 (stmt, sqoff++, limit_off);
856 if (ret != SQLITE_OK)
858 LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
860 proc (proc_cls, NULL, 0, NULL, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0);
863 execute_get (plugin, stmt, proc, proc_cls);
864 sqlite3_finalize (stmt);
870 * Context for 'repl_proc' function.
876 * Function to call for the result (or the NULL).
878 PluginDatumProcessor proc;
891 * Yes if UID was set.
898 * Wrapper for the processor for 'sqlite_plugin_replication_get'.
899 * Decrements the replication counter and calls the original
903 * @param key key for the content
904 * @param size number of bytes in data
905 * @param data content stored
906 * @param type type of the content
907 * @param priority priority of the content
908 * @param anonymity anonymity-level for the content
909 * @param expiration expiration time for the content
910 * @param uid unique identifier for the datum;
911 * maybe 0 if no unique identifier is available
913 * @return GNUNET_OK for normal return,
914 * GNUNET_NO to delete the item
917 repl_proc (void *cls, const struct GNUNET_HashCode * key, uint32_t size,
918 const void *data, enum GNUNET_BLOCK_Type type, uint32_t priority,
919 uint32_t anonymity, struct GNUNET_TIME_Absolute expiration,
922 struct ReplCtx *rc = cls;
926 rc->proc (rc->proc_cls, key, size, data, type, priority, anonymity,
931 rc->have_uid = GNUNET_YES;
938 * Get a random item for replication. Returns a single random item
939 * from those with the highest replication counters. The item's
940 * replication counter is decremented by one IF it was positive before.
941 * Call 'proc' with all values ZERO or NULL if the datastore is empty.
944 * @param proc function to call the value (once only).
945 * @param proc_cls closure for proc
948 sqlite_plugin_get_replication (void *cls, PluginDatumProcessor proc,
951 struct Plugin *plugin = cls;
957 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "sqlite",
958 "Getting random block based on replication order.\n");
959 rc.have_uid = GNUNET_NO;
961 rc.proc_cls = proc_cls;
962 stmt = plugin->maxRepl;
963 if (SQLITE_ROW != sqlite3_step (stmt))
965 if (SQLITE_OK != sqlite3_reset (stmt))
966 LOG_SQLITE (plugin, NULL,
967 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
970 proc (proc_cls, NULL, 0, NULL, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0);
973 repl = sqlite3_column_int (stmt, 0);
974 if (SQLITE_OK != sqlite3_reset (stmt))
975 LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
977 stmt = plugin->selRepl;
978 rvalue = GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK, UINT64_MAX);
979 if (SQLITE_OK != sqlite3_bind_int64 (stmt, 1, rvalue))
981 LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
982 "sqlite3_bind_XXXX");
983 if (SQLITE_OK != sqlite3_reset (stmt))
984 LOG_SQLITE (plugin, NULL,
985 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 if (SQLITE_OK != sqlite3_bind_int (stmt, 2, repl))
992 LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
993 "sqlite3_bind_XXXX");
994 if (SQLITE_OK != sqlite3_reset (stmt))
995 LOG_SQLITE (plugin, NULL,
996 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 execute_get (plugin, stmt, &repl_proc, &rc);
1002 if (GNUNET_YES == rc.have_uid)
1004 if (SQLITE_OK != sqlite3_bind_int64 (plugin->updRepl, 1, rc.uid))
1006 LOG_SQLITE (plugin, NULL,
1007 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
1008 "sqlite3_bind_XXXX");
1009 if (SQLITE_OK != sqlite3_reset (plugin->updRepl))
1010 LOG_SQLITE (plugin, NULL,
1011 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
1015 if (SQLITE_DONE != sqlite3_step (plugin->updRepl))
1016 LOG_SQLITE (plugin, NULL,
1017 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
1019 if (SQLITE_OK != sqlite3_reset (plugin->updRepl))
1020 LOG_SQLITE (plugin, NULL,
1021 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
1029 * Get a random item that has expired or has low priority.
1030 * Call 'proc' with all values ZERO or NULL if the datastore is empty.
1032 * @param cls closure
1033 * @param proc function to call the value (once only).
1034 * @param proc_cls closure for proc
1037 sqlite_plugin_get_expiration (void *cls, PluginDatumProcessor proc,
1040 struct Plugin *plugin = cls;
1042 struct GNUNET_TIME_Absolute now;
1044 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "sqlite",
1045 "Getting random block based on expiration and priority order.\n");
1046 now = GNUNET_TIME_absolute_get ();
1047 stmt = plugin->selExpi;
1048 if (SQLITE_OK != sqlite3_bind_int64 (stmt, 1, now.abs_value))
1050 LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
1051 "sqlite3_bind_XXXX");
1052 if (SQLITE_OK != sqlite3_reset (stmt))
1053 LOG_SQLITE (plugin, NULL,
1054 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
1056 proc (proc_cls, NULL, 0, NULL, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0);
1059 execute_get (plugin, stmt, proc, proc_cls);
1065 * Get all of the keys in the datastore.
1067 * @param cls closure
1068 * @param proc function to call on each key
1069 * @param proc_cls closure for proc
1072 sqlite_plugin_get_keys (void *cls,
1073 PluginKeyProcessor proc,
1076 struct Plugin *plugin = cls;
1077 const struct GNUNET_HashCode *key;
1081 GNUNET_assert (proc != NULL);
1082 if (sq_prepare (plugin->dbh, "SELECT hash FROM gn090", &stmt) != SQLITE_OK)
1084 LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
1088 while (SQLITE_ROW == (ret = sqlite3_step (stmt)))
1090 key = sqlite3_column_blob (stmt, 1);
1091 if (sizeof (struct GNUNET_HashCode) == sqlite3_column_bytes (stmt, 1))
1092 proc (proc_cls, key, 1);
1094 if (SQLITE_DONE != ret)
1095 LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR, "sqlite_step");
1096 sqlite3_finalize (stmt);
1103 * @param cls our plugin context
1106 sqlite_plugin_drop (void *cls)
1108 struct Plugin *plugin = cls;
1110 plugin->drop_on_shutdown = GNUNET_YES;
1115 * Get an estimate of how much space the database is
1118 * @param cls the 'struct Plugin'
1119 * @return the size of the database on disk (estimate)
1121 static unsigned long long
1122 sqlite_plugin_estimate_size (void *cls)
1124 struct Plugin *plugin = cls;
1133 if (SQLITE_VERSION_NUMBER < 3006000)
1135 GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING, "datastore-sqlite",
1137 ("sqlite version to old to determine size, assuming zero\n"));
1140 CHECK (SQLITE_OK == sqlite3_exec (plugin->dbh, "VACUUM", NULL, NULL, ENULL));
1142 sqlite3_exec (plugin->dbh, "PRAGMA auto_vacuum=INCREMENTAL", NULL,
1144 CHECK (SQLITE_OK == sq_prepare (plugin->dbh, "PRAGMA page_count", &stmt));
1145 if (SQLITE_ROW == sqlite3_step (stmt))
1146 pages = sqlite3_column_int64 (stmt, 0);
1149 sqlite3_finalize (stmt);
1150 CHECK (SQLITE_OK == sq_prepare (plugin->dbh, "PRAGMA page_size", &stmt));
1151 CHECK (SQLITE_ROW == sqlite3_step (stmt));
1152 page_size = sqlite3_column_int64 (stmt, 0);
1153 sqlite3_finalize (stmt);
1154 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1156 ("Using sqlite page utilization to estimate payload (%llu pages of size %llu bytes)\n"),
1157 (unsigned long long) pages, (unsigned long long) page_size);
1158 return pages * page_size;
1163 * Entry point for the plugin.
1165 * @param cls the "struct GNUNET_DATASTORE_PluginEnvironment*"
1166 * @return NULL on error, othrewise the plugin context
1169 libgnunet_plugin_datastore_sqlite_init (void *cls)
1171 static struct Plugin plugin;
1172 struct GNUNET_DATASTORE_PluginEnvironment *env = cls;
1173 struct GNUNET_DATASTORE_PluginFunctions *api;
1175 if (plugin.env != NULL)
1176 return NULL; /* can only initialize once! */
1177 memset (&plugin, 0, sizeof (struct Plugin));
1179 if (GNUNET_OK != database_setup (env->cfg, &plugin))
1181 database_shutdown (&plugin);
1184 api = GNUNET_malloc (sizeof (struct GNUNET_DATASTORE_PluginFunctions));
1186 api->estimate_size = &sqlite_plugin_estimate_size;
1187 api->put = &sqlite_plugin_put;
1188 api->update = &sqlite_plugin_update;
1189 api->get_key = &sqlite_plugin_get_key;
1190 api->get_replication = &sqlite_plugin_get_replication;
1191 api->get_expiration = &sqlite_plugin_get_expiration;
1192 api->get_zero_anonymity = &sqlite_plugin_get_zero_anonymity;
1193 api->get_keys = &sqlite_plugin_get_keys;
1194 api->drop = &sqlite_plugin_drop;
1195 GNUNET_log_from (GNUNET_ERROR_TYPE_INFO, "sqlite",
1196 _("Sqlite database running\n"));
1202 * Exit point from the plugin.
1204 * @param cls the plugin context (as returned by "init")
1205 * @return always NULL
1208 libgnunet_plugin_datastore_sqlite_done (void *cls)
1211 struct GNUNET_DATASTORE_PluginFunctions *api = cls;
1212 struct Plugin *plugin = api->cls;
1214 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "sqlite",
1215 "sqlite plugin is done\n");
1217 if (plugin->drop_on_shutdown)
1218 fn = GNUNET_strdup (plugin->fn);
1219 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "sqlite",
1220 "Shutting down database\n");
1221 database_shutdown (plugin);
1226 if (0 != UNLINK (fn))
1227 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "unlink", fn);
1230 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "sqlite",
1231 "sqlite plugin is finished\n");
1235 /* end of plugin_datastore_sqlite.c */