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);
246 /* afsdir should be UTF-8-encoded. If it isn't, it's a bug */
249 /* Open database and precompile statements */
250 if (sqlite3_open (plugin->fn, &plugin->dbh) != SQLITE_OK)
252 GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, "sqlite",
253 _("Unable to initialize SQLite: %s.\n"),
254 sqlite3_errmsg (plugin->dbh));
255 return GNUNET_SYSERR;
258 sqlite3_exec (plugin->dbh, "PRAGMA temp_store=MEMORY", NULL, NULL,
261 sqlite3_exec (plugin->dbh, "PRAGMA synchronous=OFF", NULL, NULL,
264 sqlite3_exec (plugin->dbh, "PRAGMA legacy_file_format=OFF", NULL, NULL,
267 sqlite3_exec (plugin->dbh, "PRAGMA auto_vacuum=INCREMENTAL", NULL,
270 sqlite3_exec (plugin->dbh, "PRAGMA locking_mode=EXCLUSIVE", NULL, NULL,
273 sqlite3_exec (plugin->dbh, "PRAGMA count_changes=OFF", NULL, NULL,
276 sqlite3_exec (plugin->dbh, "PRAGMA page_size=4092", NULL, NULL,
279 CHECK (SQLITE_OK == sqlite3_busy_timeout (plugin->dbh, BUSY_TIMEOUT_MS));
282 /* We have to do it here, because otherwise precompiling SQL might fail */
284 sq_prepare (plugin->dbh,
285 "SELECT 1 FROM sqlite_master WHERE tbl_name = 'gn090'",
287 if ((sqlite3_step (stmt) == SQLITE_DONE) &&
290 "CREATE TABLE gn090 (" " repl INT4 NOT NULL DEFAULT 0,"
291 " type INT4 NOT NULL DEFAULT 0," " prio INT4 NOT NULL DEFAULT 0,"
292 " anonLevel INT4 NOT NULL DEFAULT 0,"
293 " expire INT8 NOT NULL DEFAULT 0," " rvalue INT8 NOT NULL,"
294 " hash TEXT NOT NULL DEFAULT ''," " vhash TEXT NOT NULL DEFAULT '',"
295 " value BLOB NOT NULL DEFAULT '')", NULL, NULL, NULL) != SQLITE_OK))
297 LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR, "sqlite3_exec");
298 sqlite3_finalize (stmt);
299 return GNUNET_SYSERR;
301 sqlite3_finalize (stmt);
302 create_indices (plugin->dbh);
307 "SET prio = prio + ?, expire = MAX(expire,?) WHERE _ROWID_ = ?",
308 &plugin->updPrio) != SQLITE_OK) ||
311 "UPDATE gn090 " "SET repl = MAX (0, repl - 1) WHERE _ROWID_ = ?",
312 &plugin->updRepl) != SQLITE_OK) ||
315 "SELECT type,prio,anonLevel,expire,hash,value,_ROWID_ " "FROM gn090 "
316 #if SQLITE_VERSION_NUMBER >= 3007000
317 "INDEXED BY idx_repl_rvalue "
319 "WHERE repl=?2 AND " " (rvalue>=?1 OR "
320 " NOT EXISTS (SELECT 1 FROM gn090 "
321 #if SQLITE_VERSION_NUMBER >= 3007000
322 "INDEXED BY idx_repl_rvalue "
324 "WHERE repl=?2 AND rvalue>=?1 LIMIT 1) ) "
325 "ORDER BY rvalue ASC LIMIT 1", &plugin->selRepl) != SQLITE_OK) ||
326 (sq_prepare (plugin->dbh, "SELECT MAX(repl) FROM gn090"
327 #if SQLITE_VERSION_NUMBER >= 3007000
328 " INDEXED BY idx_repl_rvalue"
330 "", &plugin->maxRepl) != SQLITE_OK) ||
333 "SELECT type,prio,anonLevel,expire,hash,value,_ROWID_ " "FROM gn090 "
334 #if SQLITE_VERSION_NUMBER >= 3007000
335 "INDEXED BY idx_expire "
337 "WHERE NOT EXISTS (SELECT 1 FROM gn090 WHERE expire < ?1 LIMIT 1) OR (expire < ?1) "
338 "ORDER BY expire ASC LIMIT 1", &plugin->selExpi) != SQLITE_OK) ||
341 "SELECT type,prio,anonLevel,expire,hash,value,_ROWID_ " "FROM gn090 "
342 #if SQLITE_VERSION_NUMBER >= 3007000
343 "INDEXED BY idx_anon_type_hash "
345 "WHERE (anonLevel = 0 AND type=?1) "
346 "ORDER BY hash DESC LIMIT 1 OFFSET ?2",
347 &plugin->selZeroAnon) != SQLITE_OK) ||
350 "INSERT INTO gn090 (repl, type, prio, anonLevel, expire, rvalue, hash, vhash, value) "
351 "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)",
352 &plugin->insertContent) != SQLITE_OK) ||
354 (plugin->dbh, "DELETE FROM gn090 WHERE _ROWID_ = ?",
355 &plugin->delRow) != SQLITE_OK))
357 LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR, "precompiling");
358 return GNUNET_SYSERR;
366 * 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, unsigned long long rid)
433 if (SQLITE_OK != sqlite3_bind_int64 (plugin->delRow, 1, rid))
435 LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
436 "sqlite3_bind_XXXX");
437 if (SQLITE_OK != sqlite3_reset (plugin->delRow))
438 LOG_SQLITE (plugin, NULL,
439 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
441 return GNUNET_SYSERR;
443 if (SQLITE_DONE != sqlite3_step (plugin->delRow))
445 LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
447 if (SQLITE_OK != sqlite3_reset (plugin->delRow))
448 LOG_SQLITE (plugin, NULL,
449 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
451 return GNUNET_SYSERR;
453 if (SQLITE_OK != sqlite3_reset (plugin->delRow))
454 LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
461 * Store an item in the datastore.
464 * @param key key for the item
465 * @param size number of bytes in data
466 * @param data content stored
467 * @param type type of the content
468 * @param priority priority of the content
469 * @param anonymity anonymity-level for the content
470 * @param replication replication-level for the content
471 * @param expiration expiration time for the content
472 * @param msg set to an error message
473 * @return #GNUNET_OK on success
476 sqlite_plugin_put (void *cls, const struct GNUNET_HashCode * key, uint32_t size,
477 const void *data, enum GNUNET_BLOCK_Type type,
478 uint32_t priority, uint32_t anonymity, uint32_t replication,
479 struct GNUNET_TIME_Absolute expiration, char **msg)
481 struct Plugin *plugin = cls;
485 struct GNUNET_HashCode vhash;
488 if (size > MAX_ITEM_SIZE)
489 return GNUNET_SYSERR;
490 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "sqlite",
491 "Storing in database block with type %u/key `%s'/priority %u/expiration in %s (%s).\n",
492 type, GNUNET_h2s (key), priority,
494 GNUNET_STRINGS_relative_time_to_string (GNUNET_TIME_absolute_get_remaining (expiration),
496 GNUNET_STRINGS_absolute_time_to_string (expiration));
497 GNUNET_CRYPTO_hash (data, size, &vhash);
498 stmt = plugin->insertContent;
499 rvalue = GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK, UINT64_MAX);
500 if ((SQLITE_OK != sqlite3_bind_int (stmt, 1, replication)) ||
501 (SQLITE_OK != sqlite3_bind_int (stmt, 2, type)) ||
502 (SQLITE_OK != sqlite3_bind_int (stmt, 3, priority)) ||
503 (SQLITE_OK != sqlite3_bind_int (stmt, 4, anonymity)) ||
504 (SQLITE_OK != sqlite3_bind_int64 (stmt, 5, expiration.abs_value_us)) ||
505 (SQLITE_OK != sqlite3_bind_int64 (stmt, 6, rvalue)) ||
507 sqlite3_bind_blob (stmt, 7, key, sizeof (struct GNUNET_HashCode),
508 SQLITE_TRANSIENT)) ||
510 sqlite3_bind_blob (stmt, 8, &vhash, sizeof (struct GNUNET_HashCode),
511 SQLITE_TRANSIENT)) ||
512 (SQLITE_OK != sqlite3_bind_blob (stmt, 9, data, size, SQLITE_TRANSIENT)))
514 LOG_SQLITE (plugin, msg, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
515 "sqlite3_bind_XXXX");
516 if (SQLITE_OK != sqlite3_reset (stmt))
517 LOG_SQLITE (plugin, NULL,
518 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
520 return GNUNET_SYSERR;
522 n = sqlite3_step (stmt);
526 plugin->env->duc (plugin->env->cls, size + GNUNET_DATASTORE_ENTRY_OVERHEAD);
527 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "sqlite",
528 "Stored new entry (%u bytes)\n",
529 size + GNUNET_DATASTORE_ENTRY_OVERHEAD);
534 LOG_SQLITE (plugin, msg, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
539 LOG_SQLITE (plugin, msg, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
541 if (SQLITE_OK != sqlite3_reset (stmt))
542 LOG_SQLITE (plugin, NULL,
543 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
545 database_shutdown (plugin);
546 database_setup (plugin->env->cfg, plugin);
547 return GNUNET_SYSERR;
549 if (SQLITE_OK != sqlite3_reset (stmt))
550 LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
557 * Update the priority for a particular key in the datastore. If
558 * the expiration time in value is different than the time found in
559 * the datastore, the higher value should be kept. For the
560 * anonymity level, the lower value is to be used. The specified
561 * priority should be added to the existing priority, ignoring the
564 * Note that it is possible for multiple values to match this put.
565 * In that case, all of the respective values are updated.
567 * @param cls the plugin context (state for this module)
568 * @param uid unique identifier of the datum
569 * @param delta by how much should the priority
570 * change? If priority + delta < 0 the
571 * priority should be set to 0 (never go
573 * @param expire new expiration time should be the
574 * MAX of any existing expiration time and
576 * @param msg set to an error message
577 * @return GNUNET_OK on success
580 sqlite_plugin_update (void *cls, uint64_t uid, int delta,
581 struct GNUNET_TIME_Absolute expire, char **msg)
583 struct Plugin *plugin = cls;
586 if ((SQLITE_OK != sqlite3_bind_int (plugin->updPrio, 1, delta)) ||
587 (SQLITE_OK != sqlite3_bind_int64 (plugin->updPrio, 2, expire.abs_value_us))
588 || (SQLITE_OK != sqlite3_bind_int64 (plugin->updPrio, 3, uid)))
590 LOG_SQLITE (plugin, msg, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
591 "sqlite3_bind_XXXX");
592 if (SQLITE_OK != sqlite3_reset (plugin->updPrio))
593 LOG_SQLITE (plugin, NULL,
594 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
596 return GNUNET_SYSERR;
599 n = sqlite3_step (plugin->updPrio);
600 if (SQLITE_OK != sqlite3_reset (plugin->updPrio))
601 LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
606 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "sqlite", "Block updated\n");
609 LOG_SQLITE (plugin, msg, GNUNET_ERROR_TYPE_WARNING | GNUNET_ERROR_TYPE_BULK,
613 LOG_SQLITE (plugin, msg, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
615 return GNUNET_SYSERR;
621 * Execute statement that gets a row and call the callback
622 * with the result. Resets the statement afterwards.
624 * @param plugin the plugin
625 * @param stmt the statement
626 * @param proc processor to call
627 * @param proc_cls closure for 'proc'
630 execute_get (struct Plugin *plugin, sqlite3_stmt * stmt,
631 PluginDatumProcessor proc, void *proc_cls)
634 struct GNUNET_TIME_Absolute expiration;
635 unsigned long long rowid;
639 n = sqlite3_step (stmt);
643 size = sqlite3_column_bytes (stmt, 5);
644 rowid = sqlite3_column_int64 (stmt, 6);
645 if (sqlite3_column_bytes (stmt, 4) != sizeof (struct GNUNET_HashCode))
647 GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING, "sqlite",
649 ("Invalid data in database. Trying to fix (by deletion).\n"));
650 if (SQLITE_OK != sqlite3_reset (stmt))
651 LOG_SQLITE (plugin, NULL,
652 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
654 if (GNUNET_OK == delete_by_rowid (plugin, rowid))
655 plugin->env->duc (plugin->env->cls,
656 -(size + GNUNET_DATASTORE_ENTRY_OVERHEAD));
659 expiration.abs_value_us = sqlite3_column_int64 (stmt, 3);
660 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "sqlite",
661 "Found reply in database with expiration %s\n",
662 GNUNET_STRINGS_absolute_time_to_string (expiration));
663 ret = proc (proc_cls, sqlite3_column_blob (stmt, 4) /* key */ ,
664 size, sqlite3_column_blob (stmt, 5) /* data */ ,
665 sqlite3_column_int (stmt, 0) /* type */ ,
666 sqlite3_column_int (stmt, 1) /* priority */ ,
667 sqlite3_column_int (stmt, 2) /* anonymity */ ,
669 if (SQLITE_OK != sqlite3_reset (stmt))
670 LOG_SQLITE (plugin, NULL,
671 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
673 if ((GNUNET_NO == ret) && (GNUNET_OK == delete_by_rowid (plugin, rowid)))
674 plugin->env->duc (plugin->env->cls,
675 -(size + GNUNET_DATASTORE_ENTRY_OVERHEAD));
678 /* database must be empty */
679 if (SQLITE_OK != sqlite3_reset (stmt))
680 LOG_SQLITE (plugin, NULL,
681 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
688 LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
690 if (SQLITE_OK != sqlite3_reset (stmt))
691 LOG_SQLITE (plugin, NULL,
692 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
695 database_shutdown (plugin);
696 database_setup (plugin->env->cfg, plugin);
699 if (SQLITE_OK != sqlite3_reset (stmt))
700 LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
702 proc (proc_cls, NULL, 0, NULL, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0);
708 * Select a subset of the items in the datastore and call
709 * the given processor for the item.
711 * @param cls our plugin context
712 * @param offset offset of the result (modulo num-results);
713 * specific ordering does not matter for the offset
714 * @param type entries of which type should be considered?
715 * Use 0 for any type.
716 * @param proc function to call on each matching value;
717 * will be called once with a NULL value at the end
718 * @param proc_cls closure for proc
721 sqlite_plugin_get_zero_anonymity (void *cls, uint64_t offset,
722 enum GNUNET_BLOCK_Type type,
723 PluginDatumProcessor proc, void *proc_cls)
725 struct Plugin *plugin = cls;
728 GNUNET_assert (type != GNUNET_BLOCK_TYPE_ANY);
729 stmt = plugin->selZeroAnon;
730 if ((SQLITE_OK != sqlite3_bind_int (stmt, 1, type)) ||
731 (SQLITE_OK != sqlite3_bind_int64 (stmt, 2, offset)))
733 LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
734 "sqlite3_bind_XXXX");
735 if (SQLITE_OK != sqlite3_reset (stmt))
736 LOG_SQLITE (plugin, NULL,
737 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
739 proc (proc_cls, NULL, 0, NULL, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0);
742 execute_get (plugin, stmt, proc, proc_cls);
748 * Get results for a particular key in the datastore.
751 * @param offset offset (mod count).
752 * @param key key to match, never NULL
753 * @param vhash hash of the value, maybe NULL (to
754 * match all values that have the right key).
755 * Note that for DBlocks there is no difference
756 * betwen key and vhash, but for other blocks
758 * @param type entries of which type are relevant?
759 * Use 0 for any type.
760 * @param proc function to call on each matching value;
761 * will be called once with a NULL value at the end
762 * @param proc_cls closure for proc
765 sqlite_plugin_get_key (void *cls, uint64_t offset, const struct GNUNET_HashCode * key,
766 const struct GNUNET_HashCode * vhash,
767 enum GNUNET_BLOCK_Type type, PluginDatumProcessor proc,
770 struct Plugin *plugin = cls;
778 GNUNET_assert (proc != NULL);
779 GNUNET_assert (key != NULL);
780 GNUNET_snprintf (scratch, sizeof (scratch),
781 "SELECT count(*) FROM gn090 WHERE hash=?%s%s",
782 vhash == NULL ? "" : " AND vhash=?",
783 type == 0 ? "" : " AND type=?");
784 if (sq_prepare (plugin->dbh, scratch, &stmt) != SQLITE_OK)
786 LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
788 proc (proc_cls, NULL, 0, NULL, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0);
793 sqlite3_bind_blob (stmt, sqoff++, key, sizeof (struct GNUNET_HashCode),
795 if ((vhash != NULL) && (ret == SQLITE_OK))
797 sqlite3_bind_blob (stmt, sqoff++, vhash, sizeof (struct GNUNET_HashCode),
799 if ((type != 0) && (ret == SQLITE_OK))
800 ret = sqlite3_bind_int (stmt, sqoff++, type);
801 if (SQLITE_OK != ret)
803 LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR, "sqlite_bind");
804 sqlite3_finalize (stmt);
805 proc (proc_cls, NULL, 0, NULL, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0);
808 ret = sqlite3_step (stmt);
809 if (ret != SQLITE_ROW)
811 LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
813 sqlite3_finalize (stmt);
814 proc (proc_cls, NULL, 0, NULL, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0);
817 total = sqlite3_column_int (stmt, 0);
818 sqlite3_finalize (stmt);
821 proc (proc_cls, NULL, 0, NULL, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0);
824 limit_off = (int) (offset % total);
827 GNUNET_snprintf (scratch, sizeof (scratch),
828 "SELECT type, prio, anonLevel, expire, hash, value, _ROWID_ "
829 "FROM gn090 WHERE hash=?%s%s "
830 "ORDER BY _ROWID_ ASC LIMIT 1 OFFSET ?",
831 vhash == NULL ? "" : " AND vhash=?",
832 type == 0 ? "" : " AND type=?");
833 if (sq_prepare (plugin->dbh, scratch, &stmt) != SQLITE_OK)
835 LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
837 proc (proc_cls, NULL, 0, NULL, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0);
842 sqlite3_bind_blob (stmt, sqoff++, key, sizeof (struct GNUNET_HashCode),
844 if ((vhash != NULL) && (ret == SQLITE_OK))
846 sqlite3_bind_blob (stmt, sqoff++, vhash, sizeof (struct GNUNET_HashCode),
848 if ((type != 0) && (ret == SQLITE_OK))
849 ret = sqlite3_bind_int (stmt, sqoff++, type);
850 if (ret == SQLITE_OK)
851 ret = sqlite3_bind_int64 (stmt, sqoff++, limit_off);
852 if (ret != SQLITE_OK)
854 LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
856 proc (proc_cls, NULL, 0, NULL, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0);
859 execute_get (plugin, stmt, proc, proc_cls);
860 sqlite3_finalize (stmt);
866 * Context for 'repl_proc' function.
872 * Function to call for the result (or the NULL).
874 PluginDatumProcessor proc;
887 * Yes if UID was set.
894 * Wrapper for the processor for 'sqlite_plugin_replication_get'.
895 * Decrements the replication counter and calls the original
899 * @param key key for the content
900 * @param size number of bytes in data
901 * @param data content stored
902 * @param type type of the content
903 * @param priority priority of the content
904 * @param anonymity anonymity-level for the content
905 * @param expiration expiration time for the content
906 * @param uid unique identifier for the datum;
907 * maybe 0 if no unique identifier is available
909 * @return GNUNET_OK for normal return,
910 * GNUNET_NO to delete the item
913 repl_proc (void *cls, const struct GNUNET_HashCode * key, uint32_t size,
914 const void *data, enum GNUNET_BLOCK_Type type, uint32_t priority,
915 uint32_t anonymity, struct GNUNET_TIME_Absolute expiration,
918 struct ReplCtx *rc = cls;
922 rc->proc (rc->proc_cls, key, size, data, type, priority, anonymity,
927 rc->have_uid = GNUNET_YES;
934 * Get a random item for replication. Returns a single random item
935 * from those with the highest replication counters. The item's
936 * replication counter is decremented by one IF it was positive before.
937 * Call 'proc' with all values ZERO or NULL if the datastore is empty.
940 * @param proc function to call the value (once only).
941 * @param proc_cls closure for proc
944 sqlite_plugin_get_replication (void *cls, PluginDatumProcessor proc,
947 struct Plugin *plugin = cls;
953 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "sqlite",
954 "Getting random block based on replication order.\n");
955 rc.have_uid = GNUNET_NO;
957 rc.proc_cls = proc_cls;
958 stmt = plugin->maxRepl;
959 if (SQLITE_ROW != sqlite3_step (stmt))
961 if (SQLITE_OK != sqlite3_reset (stmt))
962 LOG_SQLITE (plugin, NULL,
963 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
966 proc (proc_cls, NULL, 0, NULL, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0);
969 repl = sqlite3_column_int (stmt, 0);
970 if (SQLITE_OK != sqlite3_reset (stmt))
971 LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
973 stmt = plugin->selRepl;
974 rvalue = GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK, UINT64_MAX);
975 if (SQLITE_OK != sqlite3_bind_int64 (stmt, 1, rvalue))
977 LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
978 "sqlite3_bind_XXXX");
979 if (SQLITE_OK != sqlite3_reset (stmt))
980 LOG_SQLITE (plugin, NULL,
981 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
983 proc (proc_cls, NULL, 0, NULL, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0);
986 if (SQLITE_OK != sqlite3_bind_int (stmt, 2, repl))
988 LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
989 "sqlite3_bind_XXXX");
990 if (SQLITE_OK != sqlite3_reset (stmt))
991 LOG_SQLITE (plugin, NULL,
992 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
994 proc (proc_cls, NULL, 0, NULL, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0);
997 execute_get (plugin, stmt, &repl_proc, &rc);
998 if (GNUNET_YES == rc.have_uid)
1000 if (SQLITE_OK != sqlite3_bind_int64 (plugin->updRepl, 1, rc.uid))
1002 LOG_SQLITE (plugin, NULL,
1003 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
1004 "sqlite3_bind_XXXX");
1005 if (SQLITE_OK != sqlite3_reset (plugin->updRepl))
1006 LOG_SQLITE (plugin, NULL,
1007 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
1011 if (SQLITE_DONE != sqlite3_step (plugin->updRepl))
1012 LOG_SQLITE (plugin, NULL,
1013 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
1015 if (SQLITE_OK != sqlite3_reset (plugin->updRepl))
1016 LOG_SQLITE (plugin, NULL,
1017 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
1025 * Get a random item that has expired or has low priority.
1026 * Call 'proc' with all values ZERO or NULL if the datastore is empty.
1028 * @param cls closure
1029 * @param proc function to call the value (once only).
1030 * @param proc_cls closure for proc
1033 sqlite_plugin_get_expiration (void *cls, PluginDatumProcessor proc,
1036 struct Plugin *plugin = cls;
1038 struct GNUNET_TIME_Absolute now;
1040 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "sqlite",
1041 "Getting random block based on expiration and priority order.\n");
1042 now = GNUNET_TIME_absolute_get ();
1043 stmt = plugin->selExpi;
1044 if (SQLITE_OK != sqlite3_bind_int64 (stmt, 1, now.abs_value_us))
1046 LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
1047 "sqlite3_bind_XXXX");
1048 if (SQLITE_OK != sqlite3_reset (stmt))
1049 LOG_SQLITE (plugin, NULL,
1050 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
1052 proc (proc_cls, NULL, 0, NULL, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0);
1055 execute_get (plugin, stmt, proc, proc_cls);
1061 * Get all of the keys in the datastore.
1063 * @param cls closure
1064 * @param proc function to call on each key
1065 * @param proc_cls closure for proc
1068 sqlite_plugin_get_keys (void *cls,
1069 PluginKeyProcessor proc,
1072 struct Plugin *plugin = cls;
1073 const struct GNUNET_HashCode *key;
1077 GNUNET_assert (proc != NULL);
1078 if (sq_prepare (plugin->dbh, "SELECT hash FROM gn090", &stmt) != SQLITE_OK)
1080 LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
1084 while (SQLITE_ROW == (ret = sqlite3_step (stmt)))
1086 key = sqlite3_column_blob (stmt, 0);
1087 if (sizeof (struct GNUNET_HashCode) == sqlite3_column_bytes (stmt, 0))
1088 proc (proc_cls, key, 1);
1092 if (SQLITE_DONE != ret)
1093 LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR, "sqlite_step");
1094 sqlite3_finalize (stmt);
1101 * @param cls our plugin context
1104 sqlite_plugin_drop (void *cls)
1106 struct Plugin *plugin = cls;
1108 plugin->drop_on_shutdown = GNUNET_YES;
1113 * Get an estimate of how much space the database is
1116 * @param cls the 'struct Plugin'
1117 * @return the size of the database on disk (estimate)
1119 static unsigned long long
1120 sqlite_plugin_estimate_size (void *cls)
1122 struct Plugin *plugin = cls;
1131 if (SQLITE_VERSION_NUMBER < 3006000)
1133 GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING, "datastore-sqlite",
1135 ("sqlite version to old to determine size, assuming zero\n"));
1138 CHECK (SQLITE_OK == sqlite3_exec (plugin->dbh, "VACUUM", NULL, NULL, ENULL));
1140 sqlite3_exec (plugin->dbh, "PRAGMA auto_vacuum=INCREMENTAL", NULL,
1142 CHECK (SQLITE_OK == sq_prepare (plugin->dbh, "PRAGMA page_count", &stmt));
1143 if (SQLITE_ROW == sqlite3_step (stmt))
1144 pages = sqlite3_column_int64 (stmt, 0);
1147 sqlite3_finalize (stmt);
1148 CHECK (SQLITE_OK == sq_prepare (plugin->dbh, "PRAGMA page_size", &stmt));
1149 CHECK (SQLITE_ROW == sqlite3_step (stmt));
1150 page_size = sqlite3_column_int64 (stmt, 0);
1151 sqlite3_finalize (stmt);
1152 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1154 ("Using sqlite page utilization to estimate payload (%llu pages of size %llu bytes)\n"),
1155 (unsigned long long) pages, (unsigned long long) page_size);
1156 return pages * page_size;
1161 * Entry point for the plugin.
1163 * @param cls the "struct GNUNET_DATASTORE_PluginEnvironment*"
1164 * @return NULL on error, othrewise the plugin context
1167 libgnunet_plugin_datastore_sqlite_init (void *cls)
1169 static struct Plugin plugin;
1170 struct GNUNET_DATASTORE_PluginEnvironment *env = cls;
1171 struct GNUNET_DATASTORE_PluginFunctions *api;
1173 if (plugin.env != NULL)
1174 return NULL; /* can only initialize once! */
1175 memset (&plugin, 0, sizeof (struct Plugin));
1177 if (GNUNET_OK != database_setup (env->cfg, &plugin))
1179 database_shutdown (&plugin);
1182 api = GNUNET_malloc (sizeof (struct GNUNET_DATASTORE_PluginFunctions));
1184 api->estimate_size = &sqlite_plugin_estimate_size;
1185 api->put = &sqlite_plugin_put;
1186 api->update = &sqlite_plugin_update;
1187 api->get_key = &sqlite_plugin_get_key;
1188 api->get_replication = &sqlite_plugin_get_replication;
1189 api->get_expiration = &sqlite_plugin_get_expiration;
1190 api->get_zero_anonymity = &sqlite_plugin_get_zero_anonymity;
1191 api->get_keys = &sqlite_plugin_get_keys;
1192 api->drop = &sqlite_plugin_drop;
1193 GNUNET_log_from (GNUNET_ERROR_TYPE_INFO, "sqlite",
1194 _("Sqlite database running\n"));
1200 * Exit point from the plugin.
1202 * @param cls the plugin context (as returned by "init")
1203 * @return always NULL
1206 libgnunet_plugin_datastore_sqlite_done (void *cls)
1209 struct GNUNET_DATASTORE_PluginFunctions *api = cls;
1210 struct Plugin *plugin = api->cls;
1212 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "sqlite",
1213 "sqlite plugin is done\n");
1215 if (plugin->drop_on_shutdown)
1216 fn = GNUNET_strdup (plugin->fn);
1217 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "sqlite",
1218 "Shutting down database\n");
1219 database_shutdown (plugin);
1224 if (0 != UNLINK (fn))
1225 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");
1233 /* end of plugin_datastore_sqlite.c */