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 %llu ms (%lld).\n",
492 type, GNUNET_h2s (key), priority,
494 GNUNET_TIME_absolute_get_remaining (expiration).rel_value,
495 (long long) expiration.abs_value);
496 GNUNET_CRYPTO_hash (data, size, &vhash);
497 stmt = plugin->insertContent;
498 rvalue = GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK, UINT64_MAX);
499 if ((SQLITE_OK != sqlite3_bind_int (stmt, 1, replication)) ||
500 (SQLITE_OK != sqlite3_bind_int (stmt, 2, type)) ||
501 (SQLITE_OK != sqlite3_bind_int (stmt, 3, priority)) ||
502 (SQLITE_OK != sqlite3_bind_int (stmt, 4, anonymity)) ||
503 (SQLITE_OK != sqlite3_bind_int64 (stmt, 5, expiration.abs_value)) ||
504 (SQLITE_OK != sqlite3_bind_int64 (stmt, 6, rvalue)) ||
506 sqlite3_bind_blob (stmt, 7, key, sizeof (struct GNUNET_HashCode),
507 SQLITE_TRANSIENT)) ||
509 sqlite3_bind_blob (stmt, 8, &vhash, sizeof (struct GNUNET_HashCode),
510 SQLITE_TRANSIENT)) ||
511 (SQLITE_OK != sqlite3_bind_blob (stmt, 9, data, size, SQLITE_TRANSIENT)))
513 LOG_SQLITE (plugin, msg, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
514 "sqlite3_bind_XXXX");
515 if (SQLITE_OK != sqlite3_reset (stmt))
516 LOG_SQLITE (plugin, NULL,
517 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
519 return GNUNET_SYSERR;
521 n = sqlite3_step (stmt);
525 plugin->env->duc (plugin->env->cls, size + GNUNET_DATASTORE_ENTRY_OVERHEAD);
526 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "sqlite",
527 "Stored new entry (%u bytes)\n",
528 size + GNUNET_DATASTORE_ENTRY_OVERHEAD);
533 LOG_SQLITE (plugin, msg, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
538 LOG_SQLITE (plugin, msg, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
540 if (SQLITE_OK != sqlite3_reset (stmt))
541 LOG_SQLITE (plugin, NULL,
542 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
544 database_shutdown (plugin);
545 database_setup (plugin->env->cfg, plugin);
546 return GNUNET_SYSERR;
548 if (SQLITE_OK != sqlite3_reset (stmt))
549 LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
556 * Update the priority for a particular key in the datastore. If
557 * the expiration time in value is different than the time found in
558 * the datastore, the higher value should be kept. For the
559 * anonymity level, the lower value is to be used. The specified
560 * priority should be added to the existing priority, ignoring the
563 * Note that it is possible for multiple values to match this put.
564 * In that case, all of the respective values are updated.
566 * @param cls the plugin context (state for this module)
567 * @param uid unique identifier of the datum
568 * @param delta by how much should the priority
569 * change? If priority + delta < 0 the
570 * priority should be set to 0 (never go
572 * @param expire new expiration time should be the
573 * MAX of any existing expiration time and
575 * @param msg set to an error message
576 * @return GNUNET_OK on success
579 sqlite_plugin_update (void *cls, uint64_t uid, int delta,
580 struct GNUNET_TIME_Absolute expire, char **msg)
582 struct Plugin *plugin = cls;
585 if ((SQLITE_OK != sqlite3_bind_int (plugin->updPrio, 1, delta)) ||
586 (SQLITE_OK != sqlite3_bind_int64 (plugin->updPrio, 2, expire.abs_value))
587 || (SQLITE_OK != sqlite3_bind_int64 (plugin->updPrio, 3, uid)))
589 LOG_SQLITE (plugin, msg, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
590 "sqlite3_bind_XXXX");
591 if (SQLITE_OK != sqlite3_reset (plugin->updPrio))
592 LOG_SQLITE (plugin, NULL,
593 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
595 return GNUNET_SYSERR;
598 n = sqlite3_step (plugin->updPrio);
599 if (SQLITE_OK != sqlite3_reset (plugin->updPrio))
600 LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
605 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "sqlite", "Block updated\n");
608 LOG_SQLITE (plugin, msg, GNUNET_ERROR_TYPE_WARNING | GNUNET_ERROR_TYPE_BULK,
612 LOG_SQLITE (plugin, msg, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
614 return GNUNET_SYSERR;
620 * Execute statement that gets a row and call the callback
621 * with the result. Resets the statement afterwards.
623 * @param plugin the plugin
624 * @param stmt the statement
625 * @param proc processor to call
626 * @param proc_cls closure for 'proc'
629 execute_get (struct Plugin *plugin, sqlite3_stmt * stmt,
630 PluginDatumProcessor proc, void *proc_cls)
633 struct GNUNET_TIME_Absolute expiration;
634 unsigned long long rowid;
638 n = sqlite3_step (stmt);
642 size = sqlite3_column_bytes (stmt, 5);
643 rowid = sqlite3_column_int64 (stmt, 6);
644 if (sqlite3_column_bytes (stmt, 4) != sizeof (struct GNUNET_HashCode))
646 GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING, "sqlite",
648 ("Invalid data in database. Trying to fix (by deletion).\n"));
649 if (SQLITE_OK != sqlite3_reset (stmt))
650 LOG_SQLITE (plugin, NULL,
651 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
653 if (GNUNET_OK == delete_by_rowid (plugin, rowid))
654 plugin->env->duc (plugin->env->cls,
655 -(size + GNUNET_DATASTORE_ENTRY_OVERHEAD));
658 expiration.abs_value = sqlite3_column_int64 (stmt, 3);
659 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "sqlite",
660 "Found reply in database with expiration %llu\n",
661 (unsigned long long) expiration.abs_value);
662 ret = proc (proc_cls, sqlite3_column_blob (stmt, 4) /* key */ ,
663 size, sqlite3_column_blob (stmt, 5) /* data */ ,
664 sqlite3_column_int (stmt, 0) /* type */ ,
665 sqlite3_column_int (stmt, 1) /* priority */ ,
666 sqlite3_column_int (stmt, 2) /* anonymity */ ,
668 if (SQLITE_OK != sqlite3_reset (stmt))
669 LOG_SQLITE (plugin, NULL,
670 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
672 if ((GNUNET_NO == ret) && (GNUNET_OK == delete_by_rowid (plugin, rowid)))
673 plugin->env->duc (plugin->env->cls,
674 -(size + GNUNET_DATASTORE_ENTRY_OVERHEAD));
677 /* database must be empty */
678 if (SQLITE_OK != sqlite3_reset (stmt))
679 LOG_SQLITE (plugin, NULL,
680 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
687 LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
689 if (SQLITE_OK != sqlite3_reset (stmt))
690 LOG_SQLITE (plugin, NULL,
691 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
694 database_shutdown (plugin);
695 database_setup (plugin->env->cfg, plugin);
698 if (SQLITE_OK != sqlite3_reset (stmt))
699 LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
701 proc (proc_cls, NULL, 0, NULL, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0);
707 * Select a subset of the items in the datastore and call
708 * the given processor for the item.
710 * @param cls our plugin context
711 * @param offset offset of the result (modulo num-results);
712 * specific ordering does not matter for the offset
713 * @param type entries of which type should be considered?
714 * Use 0 for any type.
715 * @param proc function to call on each matching value;
716 * will be called once with a NULL value at the end
717 * @param proc_cls closure for proc
720 sqlite_plugin_get_zero_anonymity (void *cls, uint64_t offset,
721 enum GNUNET_BLOCK_Type type,
722 PluginDatumProcessor proc, void *proc_cls)
724 struct Plugin *plugin = cls;
727 GNUNET_assert (type != GNUNET_BLOCK_TYPE_ANY);
728 stmt = plugin->selZeroAnon;
729 if ((SQLITE_OK != sqlite3_bind_int (stmt, 1, type)) ||
730 (SQLITE_OK != sqlite3_bind_int64 (stmt, 2, offset)))
732 LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
733 "sqlite3_bind_XXXX");
734 if (SQLITE_OK != sqlite3_reset (stmt))
735 LOG_SQLITE (plugin, NULL,
736 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
738 proc (proc_cls, NULL, 0, NULL, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0);
741 execute_get (plugin, stmt, proc, proc_cls);
747 * Get results for a particular key in the datastore.
750 * @param offset offset (mod count).
751 * @param key key to match, never NULL
752 * @param vhash hash of the value, maybe NULL (to
753 * match all values that have the right key).
754 * Note that for DBlocks there is no difference
755 * betwen key and vhash, but for other blocks
757 * @param type entries of which type are relevant?
758 * Use 0 for any type.
759 * @param proc function to call on each matching value;
760 * will be called once with a NULL value at the end
761 * @param proc_cls closure for proc
764 sqlite_plugin_get_key (void *cls, uint64_t offset, const struct GNUNET_HashCode * key,
765 const struct GNUNET_HashCode * vhash,
766 enum GNUNET_BLOCK_Type type, PluginDatumProcessor proc,
769 struct Plugin *plugin = cls;
777 GNUNET_assert (proc != NULL);
778 GNUNET_assert (key != NULL);
779 GNUNET_snprintf (scratch, sizeof (scratch),
780 "SELECT count(*) FROM gn090 WHERE hash=?%s%s",
781 vhash == NULL ? "" : " AND vhash=?",
782 type == 0 ? "" : " AND type=?");
783 if (sq_prepare (plugin->dbh, scratch, &stmt) != SQLITE_OK)
785 LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
787 proc (proc_cls, NULL, 0, NULL, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0);
792 sqlite3_bind_blob (stmt, sqoff++, key, sizeof (struct GNUNET_HashCode),
794 if ((vhash != NULL) && (ret == SQLITE_OK))
796 sqlite3_bind_blob (stmt, sqoff++, vhash, sizeof (struct GNUNET_HashCode),
798 if ((type != 0) && (ret == SQLITE_OK))
799 ret = sqlite3_bind_int (stmt, sqoff++, type);
800 if (SQLITE_OK != ret)
802 LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR, "sqlite_bind");
803 sqlite3_finalize (stmt);
804 proc (proc_cls, NULL, 0, NULL, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0);
807 ret = sqlite3_step (stmt);
808 if (ret != SQLITE_ROW)
810 LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
812 sqlite3_finalize (stmt);
813 proc (proc_cls, NULL, 0, NULL, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0);
816 total = sqlite3_column_int (stmt, 0);
817 sqlite3_finalize (stmt);
820 proc (proc_cls, NULL, 0, NULL, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0);
823 limit_off = (int) (offset % total);
826 GNUNET_snprintf (scratch, sizeof (scratch),
827 "SELECT type, prio, anonLevel, expire, hash, value, _ROWID_ "
828 "FROM gn090 WHERE hash=?%s%s "
829 "ORDER BY _ROWID_ ASC LIMIT 1 OFFSET ?",
830 vhash == NULL ? "" : " AND vhash=?",
831 type == 0 ? "" : " AND type=?");
832 if (sq_prepare (plugin->dbh, scratch, &stmt) != SQLITE_OK)
834 LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
836 proc (proc_cls, NULL, 0, NULL, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0);
841 sqlite3_bind_blob (stmt, sqoff++, key, sizeof (struct GNUNET_HashCode),
843 if ((vhash != NULL) && (ret == SQLITE_OK))
845 sqlite3_bind_blob (stmt, sqoff++, vhash, sizeof (struct GNUNET_HashCode),
847 if ((type != 0) && (ret == SQLITE_OK))
848 ret = sqlite3_bind_int (stmt, sqoff++, type);
849 if (ret == SQLITE_OK)
850 ret = sqlite3_bind_int64 (stmt, sqoff++, limit_off);
851 if (ret != SQLITE_OK)
853 LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
855 proc (proc_cls, NULL, 0, NULL, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0);
858 execute_get (plugin, stmt, proc, proc_cls);
859 sqlite3_finalize (stmt);
865 * Context for 'repl_proc' function.
871 * Function to call for the result (or the NULL).
873 PluginDatumProcessor proc;
886 * Yes if UID was set.
893 * Wrapper for the processor for 'sqlite_plugin_replication_get'.
894 * Decrements the replication counter and calls the original
898 * @param key key for the content
899 * @param size number of bytes in data
900 * @param data content stored
901 * @param type type of the content
902 * @param priority priority of the content
903 * @param anonymity anonymity-level for the content
904 * @param expiration expiration time for the content
905 * @param uid unique identifier for the datum;
906 * maybe 0 if no unique identifier is available
908 * @return GNUNET_OK for normal return,
909 * GNUNET_NO to delete the item
912 repl_proc (void *cls, const struct GNUNET_HashCode * key, uint32_t size,
913 const void *data, enum GNUNET_BLOCK_Type type, uint32_t priority,
914 uint32_t anonymity, struct GNUNET_TIME_Absolute expiration,
917 struct ReplCtx *rc = cls;
921 rc->proc (rc->proc_cls, key, size, data, type, priority, anonymity,
926 rc->have_uid = GNUNET_YES;
933 * Get a random item for replication. Returns a single random item
934 * from those with the highest replication counters. The item's
935 * replication counter is decremented by one IF it was positive before.
936 * Call 'proc' with all values ZERO or NULL if the datastore is empty.
939 * @param proc function to call the value (once only).
940 * @param proc_cls closure for proc
943 sqlite_plugin_get_replication (void *cls, PluginDatumProcessor proc,
946 struct Plugin *plugin = cls;
952 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "sqlite",
953 "Getting random block based on replication order.\n");
954 rc.have_uid = GNUNET_NO;
956 rc.proc_cls = proc_cls;
957 stmt = plugin->maxRepl;
958 if (SQLITE_ROW != sqlite3_step (stmt))
960 if (SQLITE_OK != sqlite3_reset (stmt))
961 LOG_SQLITE (plugin, NULL,
962 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
965 proc (proc_cls, NULL, 0, NULL, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0);
968 repl = sqlite3_column_int (stmt, 0);
969 if (SQLITE_OK != sqlite3_reset (stmt))
970 LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
972 stmt = plugin->selRepl;
973 rvalue = GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK, UINT64_MAX);
974 if (SQLITE_OK != sqlite3_bind_int64 (stmt, 1, rvalue))
976 LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
977 "sqlite3_bind_XXXX");
978 if (SQLITE_OK != sqlite3_reset (stmt))
979 LOG_SQLITE (plugin, NULL,
980 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
982 proc (proc_cls, NULL, 0, NULL, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0);
985 if (SQLITE_OK != sqlite3_bind_int (stmt, 2, repl))
987 LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
988 "sqlite3_bind_XXXX");
989 if (SQLITE_OK != sqlite3_reset (stmt))
990 LOG_SQLITE (plugin, NULL,
991 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
993 proc (proc_cls, NULL, 0, NULL, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0);
996 execute_get (plugin, stmt, &repl_proc, &rc);
997 if (GNUNET_YES == rc.have_uid)
999 if (SQLITE_OK != sqlite3_bind_int64 (plugin->updRepl, 1, rc.uid))
1001 LOG_SQLITE (plugin, NULL,
1002 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
1003 "sqlite3_bind_XXXX");
1004 if (SQLITE_OK != sqlite3_reset (plugin->updRepl))
1005 LOG_SQLITE (plugin, NULL,
1006 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
1010 if (SQLITE_DONE != sqlite3_step (plugin->updRepl))
1011 LOG_SQLITE (plugin, NULL,
1012 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
1014 if (SQLITE_OK != sqlite3_reset (plugin->updRepl))
1015 LOG_SQLITE (plugin, NULL,
1016 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
1024 * Get a random item that has expired or has low priority.
1025 * Call 'proc' with all values ZERO or NULL if the datastore is empty.
1027 * @param cls closure
1028 * @param proc function to call the value (once only).
1029 * @param proc_cls closure for proc
1032 sqlite_plugin_get_expiration (void *cls, PluginDatumProcessor proc,
1035 struct Plugin *plugin = cls;
1037 struct GNUNET_TIME_Absolute now;
1039 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "sqlite",
1040 "Getting random block based on expiration and priority order.\n");
1041 now = GNUNET_TIME_absolute_get ();
1042 stmt = plugin->selExpi;
1043 if (SQLITE_OK != sqlite3_bind_int64 (stmt, 1, now.abs_value))
1045 LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
1046 "sqlite3_bind_XXXX");
1047 if (SQLITE_OK != sqlite3_reset (stmt))
1048 LOG_SQLITE (plugin, NULL,
1049 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
1051 proc (proc_cls, NULL, 0, NULL, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0);
1054 execute_get (plugin, stmt, proc, proc_cls);
1060 * Get all of the keys in the datastore.
1062 * @param cls closure
1063 * @param proc function to call on each key
1064 * @param proc_cls closure for proc
1067 sqlite_plugin_get_keys (void *cls,
1068 PluginKeyProcessor proc,
1071 struct Plugin *plugin = cls;
1072 const struct GNUNET_HashCode *key;
1076 GNUNET_assert (proc != NULL);
1077 if (sq_prepare (plugin->dbh, "SELECT hash FROM gn090", &stmt) != SQLITE_OK)
1079 LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
1083 while (SQLITE_ROW == (ret = sqlite3_step (stmt)))
1085 key = sqlite3_column_blob (stmt, 0);
1086 if (sizeof (struct GNUNET_HashCode) == sqlite3_column_bytes (stmt, 0))
1087 proc (proc_cls, key, 1);
1091 if (SQLITE_DONE != ret)
1092 LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR, "sqlite_step");
1093 sqlite3_finalize (stmt);
1100 * @param cls our plugin context
1103 sqlite_plugin_drop (void *cls)
1105 struct Plugin *plugin = cls;
1107 plugin->drop_on_shutdown = GNUNET_YES;
1112 * Get an estimate of how much space the database is
1115 * @param cls the 'struct Plugin'
1116 * @return the size of the database on disk (estimate)
1118 static unsigned long long
1119 sqlite_plugin_estimate_size (void *cls)
1121 struct Plugin *plugin = cls;
1130 if (SQLITE_VERSION_NUMBER < 3006000)
1132 GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING, "datastore-sqlite",
1134 ("sqlite version to old to determine size, assuming zero\n"));
1137 CHECK (SQLITE_OK == sqlite3_exec (plugin->dbh, "VACUUM", NULL, NULL, ENULL));
1139 sqlite3_exec (plugin->dbh, "PRAGMA auto_vacuum=INCREMENTAL", NULL,
1141 CHECK (SQLITE_OK == sq_prepare (plugin->dbh, "PRAGMA page_count", &stmt));
1142 if (SQLITE_ROW == sqlite3_step (stmt))
1143 pages = sqlite3_column_int64 (stmt, 0);
1146 sqlite3_finalize (stmt);
1147 CHECK (SQLITE_OK == sq_prepare (plugin->dbh, "PRAGMA page_size", &stmt));
1148 CHECK (SQLITE_ROW == sqlite3_step (stmt));
1149 page_size = sqlite3_column_int64 (stmt, 0);
1150 sqlite3_finalize (stmt);
1151 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1153 ("Using sqlite page utilization to estimate payload (%llu pages of size %llu bytes)\n"),
1154 (unsigned long long) pages, (unsigned long long) page_size);
1155 return pages * page_size;
1160 * Entry point for the plugin.
1162 * @param cls the "struct GNUNET_DATASTORE_PluginEnvironment*"
1163 * @return NULL on error, othrewise the plugin context
1166 libgnunet_plugin_datastore_sqlite_init (void *cls)
1168 static struct Plugin plugin;
1169 struct GNUNET_DATASTORE_PluginEnvironment *env = cls;
1170 struct GNUNET_DATASTORE_PluginFunctions *api;
1172 if (plugin.env != NULL)
1173 return NULL; /* can only initialize once! */
1174 memset (&plugin, 0, sizeof (struct Plugin));
1176 if (GNUNET_OK != database_setup (env->cfg, &plugin))
1178 database_shutdown (&plugin);
1181 api = GNUNET_malloc (sizeof (struct GNUNET_DATASTORE_PluginFunctions));
1183 api->estimate_size = &sqlite_plugin_estimate_size;
1184 api->put = &sqlite_plugin_put;
1185 api->update = &sqlite_plugin_update;
1186 api->get_key = &sqlite_plugin_get_key;
1187 api->get_replication = &sqlite_plugin_get_replication;
1188 api->get_expiration = &sqlite_plugin_get_expiration;
1189 api->get_zero_anonymity = &sqlite_plugin_get_zero_anonymity;
1190 api->get_keys = &sqlite_plugin_get_keys;
1191 api->drop = &sqlite_plugin_drop;
1192 GNUNET_log_from (GNUNET_ERROR_TYPE_INFO, "sqlite",
1193 _("Sqlite database running\n"));
1199 * Exit point from the plugin.
1201 * @param cls the plugin context (as returned by "init")
1202 * @return always NULL
1205 libgnunet_plugin_datastore_sqlite_done (void *cls)
1208 struct GNUNET_DATASTORE_PluginFunctions *api = cls;
1209 struct Plugin *plugin = api->cls;
1211 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "sqlite",
1212 "sqlite plugin is done\n");
1214 if (plugin->drop_on_shutdown)
1215 fn = GNUNET_strdup (plugin->fn);
1216 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "sqlite",
1217 "Shutting down database\n");
1218 database_shutdown (plugin);
1223 if (0 != UNLINK (fn))
1224 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "unlink", fn);
1227 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "sqlite",
1228 "sqlite plugin is finished\n");
1232 /* end of plugin_datastore_sqlite.c */