2 This file is part of GNUnet
3 (C) 2009, 2011 Christian Grothoff (and other contributing authors)
5 GNUnet is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published
7 by the Free Software Foundation; either version 3, or (at your
8 option) any later version.
10 GNUnet is distributed in the hope that it will be useful, but
11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with GNUnet; see the file COPYING. If not, write to the
17 Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18 Boston, MA 02111-1307, USA.
22 * @file datastore/plugin_datastore_sqlite.c
23 * @brief sqlite-based datastore backend
24 * @author Christian Grothoff
28 #include "gnunet_datastore_plugin.h"
32 * Enable or disable logging debug messages.
34 #define DEBUG_SQLITE GNUNET_NO
37 * We allocate items on the stack at times. To prevent a stack
38 * overflow, we impose a limit on the maximum size for the data per
39 * item. 64k should be enough.
41 #define MAX_ITEM_SIZE 65536
44 * After how many ms "busy" should a DB operation fail for good?
45 * A low value makes sure that we are more responsive to requests
46 * (especially PUTs). A high value guarantees a higher success
47 * rate (SELECTs in iterate can take several seconds despite LIMIT=1).
49 * The default value of 250ms should ensure that users do not experience
50 * huge latencies while at the same time allowing operations to succeed
51 * with reasonable probability.
53 #define BUSY_TIMEOUT_MS 250
57 * Log an error message at log-level 'level' that indicates
58 * a failure of the command 'cmd' on file 'filename'
59 * with the message given by strerror(errno).
61 #define LOG_SQLITE(db, msg, level, cmd) do { GNUNET_log_from (level, "sqlite", _("`%s' failed at %s:%d with error: %s\n"), cmd, __FILE__, __LINE__, sqlite3_errmsg(db->dbh)); if (msg != NULL) GNUNET_asprintf(msg, _("`%s' failed at %s:%u with error: %s"), cmd, __FILE__, __LINE__, sqlite3_errmsg(db->dbh)); } while(0)
66 * Context for all functions in this plugin.
71 * Our execution environment.
73 struct GNUNET_DATASTORE_PluginEnvironment *env;
81 * Native SQLite database handle.
86 * Precompiled SQL for deletion.
91 * Precompiled SQL for update.
93 sqlite3_stmt *updPrio;
96 * Get maximum repl value in database.
98 sqlite3_stmt *maxRepl;
101 * Precompiled SQL for replication decrement.
103 sqlite3_stmt *updRepl;
106 * Precompiled SQL for replication selection.
108 sqlite3_stmt *selRepl;
111 * Precompiled SQL for expiration selection.
113 sqlite3_stmt *selExpi;
116 * Precompiled SQL for expiration selection.
118 sqlite3_stmt *selZeroAnon;
121 * Precompiled SQL for insertion.
123 sqlite3_stmt *insertContent;
126 * Should the database be dropped on shutdown?
128 int drop_on_shutdown;
134 * @brief Prepare a SQL statement
136 * @param dbh handle to the database
137 * @param zSql SQL statement, UTF-8 encoded
138 * @param ppStmt set to the prepared statement
139 * @return 0 on success
142 sq_prepare (sqlite3 * dbh,
144 sqlite3_stmt ** ppStmt)
149 result = sqlite3_prepare_v2 (dbh,
153 (const char **) &dummy);
154 #if DEBUG_SQLITE && 0
155 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
157 "Prepared `%s' / %p: %d\n",
167 * Create our database indices.
169 * @param dbh handle to the database
172 create_indices (sqlite3 * dbh)
177 "CREATE INDEX IF NOT EXISTS idx_hash ON gn090 (hash)", NULL, NULL, NULL)) ||
180 "CREATE INDEX IF NOT EXISTS idx_hash_vhash ON gn090 (hash,vhash)", NULL,
183 sqlite3_exec (dbh, "CREATE INDEX IF NOT EXISTS idx_expire_repl ON gn090 (expire ASC,repl DESC)", NULL, NULL,
186 sqlite3_exec (dbh, "CREATE INDEX IF NOT EXISTS idx_comb ON gn090 (anonLevel ASC,expire ASC,prio,type,hash)",
187 NULL, NULL, NULL)) ||
189 sqlite3_exec (dbh, "CREATE INDEX IF NOT EXISTS idx_anon_type_hash ON gn090 (anonLevel ASC,type,hash)",
190 NULL, NULL, NULL)) ||
192 sqlite3_exec (dbh, "CREATE INDEX IF NOT EXISTS idx_expire ON gn090 (expire ASC)",
193 NULL, NULL, NULL)) ||
195 sqlite3_exec (dbh, "CREATE INDEX IF NOT EXISTS idx_repl_rvalue ON gn090 (repl,rvalue)",
196 NULL, NULL, NULL)) ||
198 sqlite3_exec (dbh, "CREATE INDEX IF NOT EXISTS idx_repl ON gn090 (repl DESC)",
200 GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR,
202 "Failed to create indices: %s\n",
203 sqlite3_errmsg (dbh));
208 #define CHECK(a) GNUNET_break(a)
212 #define ENULL_DEFINED 1
213 #define CHECK(a) if (! a) { GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "%s\n", e); sqlite3_free(e); }
218 * Initialize the database connections and associated
219 * data structures (create tables and indices
220 * as needed as well).
222 * @param cfg our configuration
223 * @param plugin the plugin context (state for this module)
224 * @return GNUNET_OK on success
227 database_setup (const struct GNUNET_CONFIGURATION_Handle *cfg,
228 struct Plugin *plugin)
237 GNUNET_CONFIGURATION_get_value_filename (cfg,
242 GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR,
244 _("Option `%s' in section `%s' missing in configuration!\n"),
247 return GNUNET_SYSERR;
249 if (GNUNET_OK != GNUNET_DISK_file_test (afsdir))
251 if (GNUNET_OK != GNUNET_DISK_directory_create_for_file (afsdir))
254 GNUNET_free (afsdir);
255 return GNUNET_SYSERR;
257 /* database is new or got deleted, reset payload to zero! */
258 plugin->env->duc (plugin->env->cls, 0);
261 plugin->fn = GNUNET_STRINGS_to_utf8 (afsdir, strlen (afsdir),
262 nl_langinfo (CODESET));
264 plugin->fn = GNUNET_STRINGS_to_utf8 (afsdir, strlen (afsdir),
265 "UTF-8"); /* good luck */
267 GNUNET_free (afsdir);
269 /* Open database and precompile statements */
270 if (sqlite3_open (plugin->fn, &plugin->dbh) != SQLITE_OK)
272 GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR,
274 _("Unable to initialize SQLite: %s.\n"),
275 sqlite3_errmsg (plugin->dbh));
276 return GNUNET_SYSERR;
279 sqlite3_exec (plugin->dbh,
280 "PRAGMA temp_store=MEMORY", NULL, NULL, ENULL));
282 sqlite3_exec (plugin->dbh,
283 "PRAGMA synchronous=OFF", NULL, NULL, ENULL));
285 sqlite3_exec (plugin->dbh,
286 "PRAGMA legacy_file_format=OFF", NULL, NULL, ENULL));
288 sqlite3_exec (plugin->dbh,
289 "PRAGMA auto_vacuum=INCREMENTAL", NULL, NULL, ENULL));
291 sqlite3_exec (plugin->dbh,
292 "PRAGMA locking_mode=EXCLUSIVE", NULL, NULL, ENULL));
294 sqlite3_exec (plugin->dbh,
295 "PRAGMA count_changes=OFF", NULL, NULL, ENULL));
297 sqlite3_exec (plugin->dbh,
298 "PRAGMA page_size=4092", NULL, NULL, ENULL));
300 CHECK (SQLITE_OK == sqlite3_busy_timeout (plugin->dbh, BUSY_TIMEOUT_MS));
303 /* We have to do it here, because otherwise precompiling SQL might fail */
305 sq_prepare (plugin->dbh,
306 "SELECT 1 FROM sqlite_master WHERE tbl_name = 'gn090'",
308 if ( (sqlite3_step (stmt) == SQLITE_DONE) &&
309 (sqlite3_exec (plugin->dbh,
310 "CREATE TABLE gn090 ("
311 " repl INT4 NOT NULL DEFAULT 0,"
312 " type INT4 NOT NULL DEFAULT 0,"
313 " prio INT4 NOT NULL DEFAULT 0,"
314 " anonLevel INT4 NOT NULL DEFAULT 0,"
315 " expire INT8 NOT NULL DEFAULT 0,"
316 " rvalue INT8 NOT NULL,"
317 " hash TEXT NOT NULL DEFAULT '',"
318 " vhash TEXT NOT NULL DEFAULT '',"
319 " value BLOB NOT NULL DEFAULT '')", NULL, NULL,
320 NULL) != SQLITE_OK) )
322 LOG_SQLITE (plugin, NULL,
323 GNUNET_ERROR_TYPE_ERROR,
325 sqlite3_finalize (stmt);
326 return GNUNET_SYSERR;
328 sqlite3_finalize (stmt);
329 create_indices (plugin->dbh);
331 if ((sq_prepare (plugin->dbh,
333 "SET prio = prio + ?, expire = MAX(expire,?) WHERE _ROWID_ = ?",
334 &plugin->updPrio) != SQLITE_OK) ||
335 (sq_prepare (plugin->dbh,
337 "SET repl = MAX (0, repl - 1) WHERE _ROWID_ = ?",
338 &plugin->updRepl) != SQLITE_OK) ||
339 (sq_prepare (plugin->dbh,
340 "SELECT type,prio,anonLevel,expire,hash,value,_ROWID_ "
341 "FROM gn090 INDEXED BY idx_repl_rvalue "
344 " NOT EXISTS (SELECT 1 FROM gn090 INDEXED BY idx_repl_rvalue WHERE repl=?2 AND rvalue>=?1 LIMIT 1))"
345 " ORDER BY rvalue ASC"
347 &plugin->selRepl) != SQLITE_OK) ||
348 (sq_prepare (plugin->dbh,
350 "FROM gn090 INDEXED BY idx_repl_rvalue",
351 &plugin->maxRepl) != SQLITE_OK) ||
352 (sq_prepare (plugin->dbh,
353 "SELECT type,prio,anonLevel,expire,hash,value,_ROWID_ "
354 "FROM gn090 INDEXED BY idx_expire"
355 " WHERE NOT EXISTS (SELECT 1 FROM gn090 WHERE expire < ?1 LIMIT 1) OR (expire < ?1) "
356 " ORDER BY expire ASC LIMIT 1",
357 &plugin->selExpi) != SQLITE_OK) ||
358 (sq_prepare (plugin->dbh,
359 "SELECT type,prio,anonLevel,expire,hash,value,_ROWID_ "
360 "FROM gn090 INDEXED BY idx_anon_type_hash "
361 "WHERE (anonLevel = 0 AND type=?1) "
362 "ORDER BY hash DESC LIMIT 1 OFFSET ?2",
363 &plugin->selZeroAnon) != SQLITE_OK) ||
364 (sq_prepare (plugin->dbh,
365 "INSERT INTO gn090 (repl, type, prio, "
366 "anonLevel, expire, rvalue, hash, vhash, value) "
367 "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)",
368 &plugin->insertContent) != SQLITE_OK) ||
369 (sq_prepare (plugin->dbh,
370 "DELETE FROM gn090 WHERE _ROWID_ = ?",
371 &plugin->delRow) != SQLITE_OK))
373 LOG_SQLITE (plugin, NULL,
374 GNUNET_ERROR_TYPE_ERROR, "precompiling");
375 return GNUNET_SYSERR;
383 * Shutdown database connection and associate data
385 * @param plugin the plugin context (state for this module)
388 database_shutdown (struct Plugin *plugin)
391 #if SQLITE_VERSION_NUMBER >= 3007000
395 if (plugin->delRow != NULL)
396 sqlite3_finalize (plugin->delRow);
397 if (plugin->updPrio != NULL)
398 sqlite3_finalize (plugin->updPrio);
399 if (plugin->updRepl != NULL)
400 sqlite3_finalize (plugin->updRepl);
401 if (plugin->selRepl != NULL)
402 sqlite3_finalize (plugin->selRepl);
403 if (plugin->maxRepl != NULL)
404 sqlite3_finalize (plugin->maxRepl);
405 if (plugin->selExpi != NULL)
406 sqlite3_finalize (plugin->selExpi);
407 if (plugin->selZeroAnon != NULL)
408 sqlite3_finalize (plugin->selZeroAnon);
409 if (plugin->insertContent != NULL)
410 sqlite3_finalize (plugin->insertContent);
411 result = sqlite3_close(plugin->dbh);
412 #if SQLITE_VERSION_NUMBER >= 3007000
413 if (result == SQLITE_BUSY)
415 GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING,
417 _("Tried to close sqlite without finalizing all prepared statements.\n"));
418 stmt = sqlite3_next_stmt(plugin->dbh, NULL);
422 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
423 "sqlite", "Closing statement %p\n", stmt);
425 result = sqlite3_finalize(stmt);
427 if (result != SQLITE_OK)
428 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
430 "Failed to close statement %p: %d\n", stmt, result);
432 stmt = sqlite3_next_stmt(plugin->dbh, NULL);
434 result = sqlite3_close(plugin->dbh);
437 if (SQLITE_OK != result)
438 LOG_SQLITE (plugin, NULL,
439 GNUNET_ERROR_TYPE_ERROR,
442 GNUNET_free_non_null (plugin->fn);
447 * Delete the database entry with the given
450 * @param plugin the plugin context (state for this module)
451 * @param rid the ID of the row to delete
454 delete_by_rowid (struct Plugin* plugin,
455 unsigned long long rid)
458 sqlite3_bind_int64 (plugin->delRow, 1, rid))
460 LOG_SQLITE (plugin, NULL,
461 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, "sqlite3_bind_XXXX");
462 if (SQLITE_OK != sqlite3_reset (plugin->delRow))
463 LOG_SQLITE (plugin, NULL,
464 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, "sqlite3_reset");
465 return GNUNET_SYSERR;
467 if (SQLITE_DONE != sqlite3_step (plugin->delRow))
469 LOG_SQLITE (plugin, NULL,
470 GNUNET_ERROR_TYPE_ERROR |
471 GNUNET_ERROR_TYPE_BULK, "sqlite3_step");
472 if (SQLITE_OK != sqlite3_reset (plugin->delRow))
473 LOG_SQLITE (plugin, NULL,
474 GNUNET_ERROR_TYPE_ERROR |
475 GNUNET_ERROR_TYPE_BULK, "sqlite3_reset");
476 return GNUNET_SYSERR;
478 if (SQLITE_OK != sqlite3_reset (plugin->delRow))
479 LOG_SQLITE (plugin, NULL,
480 GNUNET_ERROR_TYPE_ERROR |
481 GNUNET_ERROR_TYPE_BULK, "sqlite3_reset");
487 * Store an item in the datastore.
490 * @param key key for the item
491 * @param size number of bytes in data
492 * @param data content stored
493 * @param type type of the content
494 * @param priority priority of the content
495 * @param anonymity anonymity-level for the content
496 * @param replication replication-level for the content
497 * @param expiration expiration time for the content
498 * @param msg set to an error message
499 * @return GNUNET_OK on success
502 sqlite_plugin_put (void *cls,
503 const GNUNET_HashCode *key,
506 enum GNUNET_BLOCK_Type type,
509 uint32_t replication,
510 struct GNUNET_TIME_Absolute expiration,
513 struct Plugin *plugin = cls;
517 GNUNET_HashCode vhash;
520 if (size > MAX_ITEM_SIZE)
521 return GNUNET_SYSERR;
523 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
525 "Storing in database block with type %u/key `%s'/priority %u/expiration in %llu ms (%lld).\n",
529 (unsigned long long) GNUNET_TIME_absolute_get_remaining (expiration).rel_value,
530 (long long) expiration.abs_value);
532 GNUNET_CRYPTO_hash (data, size, &vhash);
533 stmt = plugin->insertContent;
534 rvalue = GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK, UINT64_MAX);
535 if ((SQLITE_OK != sqlite3_bind_int (stmt, 1, replication)) ||
536 (SQLITE_OK != sqlite3_bind_int (stmt, 2, type)) ||
537 (SQLITE_OK != sqlite3_bind_int (stmt, 3, priority)) ||
538 (SQLITE_OK != sqlite3_bind_int (stmt, 4, anonymity)) ||
539 (SQLITE_OK != sqlite3_bind_int64 (stmt, 5, expiration.abs_value)) ||
540 (SQLITE_OK != sqlite3_bind_int64 (stmt, 6, rvalue)) ||
542 sqlite3_bind_blob (stmt, 7, key, sizeof (GNUNET_HashCode),
543 SQLITE_TRANSIENT)) ||
545 sqlite3_bind_blob (stmt, 8, &vhash, sizeof (GNUNET_HashCode),
548 sqlite3_bind_blob (stmt, 9, data, size,
553 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, "sqlite3_bind_XXXX");
554 if (SQLITE_OK != sqlite3_reset (stmt))
555 LOG_SQLITE (plugin, NULL,
556 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, "sqlite3_reset");
557 return GNUNET_SYSERR;
559 n = sqlite3_step (stmt);
563 plugin->env->duc (plugin->env->cls,
564 size + GNUNET_DATASTORE_ENTRY_OVERHEAD);
566 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
568 "Stored new entry (%u bytes)\n",
569 size + GNUNET_DATASTORE_ENTRY_OVERHEAD);
575 LOG_SQLITE (plugin, msg,
576 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
581 LOG_SQLITE (plugin, msg,
582 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
584 if (SQLITE_OK != sqlite3_reset (stmt))
585 LOG_SQLITE (plugin, NULL,
586 GNUNET_ERROR_TYPE_ERROR |
587 GNUNET_ERROR_TYPE_BULK, "sqlite3_reset");
588 database_shutdown (plugin);
589 database_setup (plugin->env->cfg,
591 return GNUNET_SYSERR;
593 if (SQLITE_OK != sqlite3_reset (stmt))
594 LOG_SQLITE (plugin, NULL,
595 GNUNET_ERROR_TYPE_ERROR |
596 GNUNET_ERROR_TYPE_BULK, "sqlite3_reset");
602 * Update the priority for a particular key in the datastore. If
603 * the expiration time in value is different than the time found in
604 * the datastore, the higher value should be kept. For the
605 * anonymity level, the lower value is to be used. The specified
606 * priority should be added to the existing priority, ignoring the
609 * Note that it is possible for multiple values to match this put.
610 * In that case, all of the respective values are updated.
612 * @param cls the plugin context (state for this module)
613 * @param uid unique identifier of the datum
614 * @param delta by how much should the priority
615 * change? If priority + delta < 0 the
616 * priority should be set to 0 (never go
618 * @param expire new expiration time should be the
619 * MAX of any existing expiration time and
621 * @param msg set to an error message
622 * @return GNUNET_OK on success
625 sqlite_plugin_update (void *cls,
627 int delta, struct GNUNET_TIME_Absolute expire,
630 struct Plugin *plugin = cls;
634 sqlite3_bind_int (plugin->updPrio, 1, delta)) ||
636 sqlite3_bind_int64 (plugin->updPrio, 2, expire.abs_value)) ||
638 sqlite3_bind_int64 (plugin->updPrio, 3, uid)) )
640 LOG_SQLITE (plugin, msg,
641 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, "sqlite3_bind_XXXX");
642 if (SQLITE_OK != sqlite3_reset (plugin->updPrio))
643 LOG_SQLITE (plugin, NULL,
644 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, "sqlite3_reset");
645 return GNUNET_SYSERR;
648 n = sqlite3_step (plugin->updPrio);
649 if (SQLITE_OK != sqlite3_reset (plugin->updPrio))
650 LOG_SQLITE (plugin, NULL,
651 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, "sqlite3_reset");
656 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
662 LOG_SQLITE (plugin, msg,
663 GNUNET_ERROR_TYPE_WARNING | GNUNET_ERROR_TYPE_BULK,
667 LOG_SQLITE (plugin, msg,
668 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
670 return GNUNET_SYSERR;
676 * Execute statement that gets a row and call the callback
677 * with the result. Resets the statement afterwards.
679 * @param plugin the plugin
680 * @param stmt the statement
681 * @param proc processor to call
682 * @param proc_cls closure for 'proc'
685 execute_get (struct Plugin *plugin,
687 PluginDatumProcessor proc, void *proc_cls)
690 struct GNUNET_TIME_Absolute expiration;
691 unsigned long long rowid;
695 n = sqlite3_step (stmt);
699 size = sqlite3_column_bytes (stmt, 5);
700 rowid = sqlite3_column_int64 (stmt, 6);
701 if (sqlite3_column_bytes (stmt, 4) != sizeof (GNUNET_HashCode))
703 GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING,
705 _("Invalid data in database. Trying to fix (by deletion).\n"));
706 if (SQLITE_OK != sqlite3_reset (stmt))
707 LOG_SQLITE (plugin, NULL,
708 GNUNET_ERROR_TYPE_ERROR |
709 GNUNET_ERROR_TYPE_BULK, "sqlite3_reset");
710 if (GNUNET_OK == delete_by_rowid (plugin, rowid))
711 plugin->env->duc (plugin->env->cls,
712 - (size + GNUNET_DATASTORE_ENTRY_OVERHEAD));
715 expiration.abs_value = sqlite3_column_int64 (stmt, 3);
717 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
719 "Found reply in database with expiration %llu\n",
720 (unsigned long long) expiration.abs_value);
722 ret = proc (proc_cls,
723 sqlite3_column_blob (stmt, 4) /* key */,
725 sqlite3_column_blob (stmt, 5) /* data */,
726 sqlite3_column_int (stmt, 0) /* type */,
727 sqlite3_column_int (stmt, 1) /* priority */,
728 sqlite3_column_int (stmt, 2) /* anonymity */,
731 if (SQLITE_OK != sqlite3_reset (stmt))
732 LOG_SQLITE (plugin, NULL,
733 GNUNET_ERROR_TYPE_ERROR |
734 GNUNET_ERROR_TYPE_BULK, "sqlite3_reset");
735 if ( (GNUNET_NO == ret) &&
736 (GNUNET_OK == delete_by_rowid (plugin, rowid)) )
737 plugin->env->duc (plugin->env->cls,
738 - (size + GNUNET_DATASTORE_ENTRY_OVERHEAD));
741 /* database must be empty */
742 if (SQLITE_OK != sqlite3_reset (stmt))
743 LOG_SQLITE (plugin, NULL,
744 GNUNET_ERROR_TYPE_ERROR |
745 GNUNET_ERROR_TYPE_BULK, "sqlite3_reset");
751 LOG_SQLITE (plugin, NULL,
752 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
754 if (SQLITE_OK != sqlite3_reset (stmt))
755 LOG_SQLITE (plugin, NULL,
756 GNUNET_ERROR_TYPE_ERROR |
757 GNUNET_ERROR_TYPE_BULK,
760 database_shutdown (plugin);
761 database_setup (plugin->env->cfg,
765 if (SQLITE_OK != sqlite3_reset (stmt))
766 LOG_SQLITE (plugin, NULL,
767 GNUNET_ERROR_TYPE_ERROR |
768 GNUNET_ERROR_TYPE_BULK, "sqlite3_reset");
769 proc (proc_cls, NULL, 0, NULL, 0, 0, 0,
770 GNUNET_TIME_UNIT_ZERO_ABS, 0);
776 * Select a subset of the items in the datastore and call
777 * the given processor for the item.
779 * @param cls our plugin context
780 * @param offset offset of the result (modulo num-results);
781 * specific ordering does not matter for the offset
782 * @param type entries of which type should be considered?
783 * Use 0 for any type.
784 * @param proc function to call on each matching value;
785 * will be called once with a NULL value at the end
786 * @param proc_cls closure for proc
789 sqlite_plugin_get_zero_anonymity (void *cls,
791 enum GNUNET_BLOCK_Type type,
792 PluginDatumProcessor proc,
795 struct Plugin *plugin = cls;
798 GNUNET_assert (type != GNUNET_BLOCK_TYPE_ANY);
799 stmt = plugin->selZeroAnon;
800 if ( (SQLITE_OK != sqlite3_bind_int (stmt, 1, type)) ||
801 (SQLITE_OK != sqlite3_bind_int64 (stmt, 2, offset)) )
803 LOG_SQLITE (plugin, NULL,
804 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
805 "sqlite3_bind_XXXX");
806 if (SQLITE_OK != sqlite3_reset (stmt))
807 LOG_SQLITE (plugin, NULL,
808 GNUNET_ERROR_TYPE_ERROR |
809 GNUNET_ERROR_TYPE_BULK,
811 proc (proc_cls, NULL, 0, NULL, 0, 0, 0,
812 GNUNET_TIME_UNIT_ZERO_ABS, 0);
815 execute_get (plugin, stmt, proc, proc_cls);
821 * Get results for a particular key in the datastore.
824 * @param offset offset (mod count).
825 * @param key key to match, never NULL
826 * @param vhash hash of the value, maybe NULL (to
827 * match all values that have the right key).
828 * Note that for DBlocks there is no difference
829 * betwen key and vhash, but for other blocks
831 * @param type entries of which type are relevant?
832 * Use 0 for any type.
833 * @param proc function to call on each matching value;
834 * will be called once with a NULL value at the end
835 * @param proc_cls closure for proc
838 sqlite_plugin_get_key (void *cls,
840 const GNUNET_HashCode *key,
841 const GNUNET_HashCode *vhash,
842 enum GNUNET_BLOCK_Type type,
843 PluginDatumProcessor proc, void *proc_cls)
845 struct Plugin *plugin = cls;
853 GNUNET_assert (proc != NULL);
854 GNUNET_assert (key != NULL);
855 GNUNET_snprintf (scratch, sizeof (scratch),
856 "SELECT count(*) FROM gn090 WHERE hash=?%s%s",
857 vhash == NULL ? "" : " AND vhash=?",
858 type == 0 ? "" : " AND type=?");
859 if (sq_prepare (plugin->dbh, scratch, &stmt) != SQLITE_OK)
861 LOG_SQLITE (plugin, NULL,
862 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, "sqlite_prepare");
863 proc (proc_cls, NULL, 0, NULL, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0);
867 ret = sqlite3_bind_blob (stmt, sqoff++,
868 key, sizeof (GNUNET_HashCode), SQLITE_TRANSIENT);
869 if ((vhash != NULL) && (ret == SQLITE_OK))
870 ret = sqlite3_bind_blob (stmt, sqoff++,
872 sizeof (GNUNET_HashCode), SQLITE_TRANSIENT);
873 if ((type != 0) && (ret == SQLITE_OK))
874 ret = sqlite3_bind_int (stmt, sqoff++, type);
875 if (SQLITE_OK != ret)
877 LOG_SQLITE (plugin, NULL,
878 GNUNET_ERROR_TYPE_ERROR, "sqlite_bind");
879 sqlite3_finalize (stmt);
880 proc (proc_cls, NULL, 0, NULL, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0);
883 ret = sqlite3_step (stmt);
884 if (ret != SQLITE_ROW)
886 LOG_SQLITE (plugin, NULL,
887 GNUNET_ERROR_TYPE_ERROR| GNUNET_ERROR_TYPE_BULK,
889 sqlite3_finalize (stmt);
890 proc (proc_cls, NULL, 0, NULL, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0);
893 total = sqlite3_column_int (stmt, 0);
894 sqlite3_finalize (stmt);
897 proc (proc_cls, NULL, 0, NULL, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0);
900 limit_off = (int) (offset % total);
903 GNUNET_snprintf (scratch, sizeof (scratch),
904 "SELECT type, prio, anonLevel, expire, hash, value, _ROWID_ "
905 "FROM gn090 WHERE hash=?%s%s "
906 "ORDER BY _ROWID_ ASC LIMIT 1 OFFSET ?",
907 vhash == NULL ? "" : " AND vhash=?",
908 type == 0 ? "" : " AND type=?");
909 if (sq_prepare (plugin->dbh, scratch, &stmt) != SQLITE_OK)
911 LOG_SQLITE (plugin, NULL,
912 GNUNET_ERROR_TYPE_ERROR |
913 GNUNET_ERROR_TYPE_BULK, "sqlite_prepare");
914 proc (proc_cls, NULL, 0, NULL, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0);
918 ret = sqlite3_bind_blob (stmt,
921 sizeof (GNUNET_HashCode),
923 if ((vhash != NULL) && (ret == SQLITE_OK))
924 ret = sqlite3_bind_blob (stmt,
927 sizeof (GNUNET_HashCode), SQLITE_TRANSIENT);
928 if ((type != 0) && (ret == SQLITE_OK))
929 ret = sqlite3_bind_int (stmt, sqoff++, type);
930 if (ret == SQLITE_OK)
931 ret = sqlite3_bind_int64 (stmt, sqoff++, limit_off);
932 if (ret != SQLITE_OK)
934 LOG_SQLITE (plugin, NULL,
935 GNUNET_ERROR_TYPE_ERROR |
936 GNUNET_ERROR_TYPE_BULK, "sqlite_bind");
937 proc (proc_cls, NULL, 0, NULL, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0);
940 execute_get (plugin, stmt, proc, proc_cls);
941 sqlite3_finalize (stmt);
947 * Context for 'repl_proc' function.
953 * Function to call for the result (or the NULL).
955 PluginDatumProcessor proc;
968 * Yes if UID was set.
975 * Wrapper for the processor for 'sqlite_plugin_replication_get'.
976 * Decrements the replication counter and calls the original
980 * @param key key for the content
981 * @param size number of bytes in data
982 * @param data content stored
983 * @param type type of the content
984 * @param priority priority of the content
985 * @param anonymity anonymity-level for the content
986 * @param expiration expiration time for the content
987 * @param uid unique identifier for the datum;
988 * maybe 0 if no unique identifier is available
990 * @return GNUNET_OK for normal return,
991 * GNUNET_NO to delete the item
994 repl_proc (void *cls,
995 const GNUNET_HashCode *key,
998 enum GNUNET_BLOCK_Type type,
1001 struct GNUNET_TIME_Absolute expiration,
1004 struct ReplCtx *rc = cls;
1007 ret = rc->proc (rc->proc_cls,
1010 type, priority, anonymity, expiration,
1015 rc->have_uid = GNUNET_YES;
1022 * Get a random item for replication. Returns a single random item
1023 * from those with the highest replication counters. The item's
1024 * replication counter is decremented by one IF it was positive before.
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_replication (void *cls,
1033 PluginDatumProcessor proc, void *proc_cls)
1035 struct Plugin *plugin = cls;
1042 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1044 "Getting random block based on replication order.\n");
1046 rc.have_uid = GNUNET_NO;
1048 rc.proc_cls = proc_cls;
1049 stmt = plugin->maxRepl;
1050 if (SQLITE_ROW != sqlite3_step (stmt))
1052 if (SQLITE_OK != sqlite3_reset (stmt))
1053 LOG_SQLITE (plugin, NULL,
1054 GNUNET_ERROR_TYPE_ERROR |
1055 GNUNET_ERROR_TYPE_BULK, "sqlite3_reset");
1057 proc (proc_cls, NULL, 0, NULL, 0, 0, 0,
1058 GNUNET_TIME_UNIT_ZERO_ABS, 0);
1061 repl = sqlite3_column_int (stmt, 0);
1062 if (SQLITE_OK != sqlite3_reset (stmt))
1063 LOG_SQLITE (plugin, NULL,
1064 GNUNET_ERROR_TYPE_ERROR |
1065 GNUNET_ERROR_TYPE_BULK, "sqlite3_reset");
1066 stmt = plugin->selRepl;
1067 rvalue = GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK, UINT64_MAX);
1068 if (SQLITE_OK != sqlite3_bind_int64 (stmt, 1, rvalue))
1070 LOG_SQLITE (plugin, NULL,
1071 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, "sqlite3_bind_XXXX");
1072 if (SQLITE_OK != sqlite3_reset (stmt))
1073 LOG_SQLITE (plugin, NULL,
1074 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, "sqlite3_reset");
1075 proc (proc_cls, NULL, 0, NULL, 0, 0, 0,
1076 GNUNET_TIME_UNIT_ZERO_ABS, 0);
1079 if (SQLITE_OK != sqlite3_bind_int (stmt, 2, repl))
1081 LOG_SQLITE (plugin, NULL,
1082 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, "sqlite3_bind_XXXX");
1083 if (SQLITE_OK != sqlite3_reset (stmt))
1084 LOG_SQLITE (plugin, NULL,
1085 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, "sqlite3_reset");
1086 proc (proc_cls, NULL, 0, NULL, 0, 0, 0,
1087 GNUNET_TIME_UNIT_ZERO_ABS, 0);
1090 execute_get (plugin, stmt, &repl_proc, &rc);
1091 if (GNUNET_YES == rc.have_uid)
1094 sqlite3_bind_int64 (plugin->updRepl, 1, rc.uid))
1096 LOG_SQLITE (plugin, NULL,
1097 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, "sqlite3_bind_XXXX");
1098 if (SQLITE_OK != sqlite3_reset (plugin->updRepl))
1099 LOG_SQLITE (plugin, NULL,
1100 GNUNET_ERROR_TYPE_ERROR |
1101 GNUNET_ERROR_TYPE_BULK, "sqlite3_reset");
1104 if (SQLITE_DONE != sqlite3_step (plugin->updRepl))
1105 LOG_SQLITE (plugin, NULL,
1106 GNUNET_ERROR_TYPE_ERROR |
1107 GNUNET_ERROR_TYPE_BULK, "sqlite3_step");
1108 if (SQLITE_OK != sqlite3_reset (plugin->updRepl))
1109 LOG_SQLITE (plugin, NULL,
1110 GNUNET_ERROR_TYPE_ERROR |
1111 GNUNET_ERROR_TYPE_BULK, "sqlite3_reset");
1118 * Get a random item that has expired or has low priority.
1119 * Call 'proc' with all values ZERO or NULL if the datastore is empty.
1121 * @param cls closure
1122 * @param proc function to call the value (once only).
1123 * @param proc_cls closure for proc
1126 sqlite_plugin_get_expiration (void *cls,
1127 PluginDatumProcessor proc, void *proc_cls)
1129 struct Plugin *plugin = cls;
1131 struct GNUNET_TIME_Absolute now;
1134 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1136 "Getting random block based on expiration and priority order.\n");
1138 now = GNUNET_TIME_absolute_get ();
1139 stmt = plugin->selExpi;
1140 if (SQLITE_OK != sqlite3_bind_int64 (stmt, 1, now.abs_value))
1142 LOG_SQLITE (plugin, NULL,
1143 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, "sqlite3_bind_XXXX");
1144 if (SQLITE_OK != sqlite3_reset (stmt))
1145 LOG_SQLITE (plugin, NULL,
1146 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, "sqlite3_reset");
1147 proc (proc_cls, NULL, 0, NULL, 0, 0, 0,
1148 GNUNET_TIME_UNIT_ZERO_ABS, 0);
1151 execute_get (plugin, stmt, proc, proc_cls);
1158 * @param cls our plugin context
1161 sqlite_plugin_drop (void *cls)
1163 struct Plugin *plugin = cls;
1164 plugin->drop_on_shutdown = GNUNET_YES;
1169 * Get an estimate of how much space the database is
1172 * @param cls the 'struct Plugin'
1173 * @return the size of the database on disk (estimate)
1175 static unsigned long long
1176 sqlite_plugin_estimate_size (void *cls)
1178 struct Plugin *plugin = cls;
1186 if (SQLITE_VERSION_NUMBER < 3006000)
1188 GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING,
1190 _("sqlite version to old to determine size, assuming zero\n"));
1194 sqlite3_exec (plugin->dbh,
1195 "VACUUM", NULL, NULL, ENULL));
1197 sqlite3_exec (plugin->dbh,
1198 "PRAGMA auto_vacuum=INCREMENTAL", NULL, NULL, ENULL));
1200 sq_prepare (plugin->dbh,
1201 "PRAGMA page_count",
1204 sqlite3_step (stmt))
1205 pages = sqlite3_column_int64 (stmt, 0);
1208 sqlite3_finalize (stmt);
1210 sq_prepare (plugin->dbh,
1213 CHECK (SQLITE_ROW ==
1214 sqlite3_step (stmt));
1215 page_size = sqlite3_column_int64 (stmt, 0);
1216 sqlite3_finalize (stmt);
1217 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1218 _("Using sqlite page utilization to estimate payload (%llu pages of size %llu bytes)\n"),
1219 (unsigned long long) pages,
1220 (unsigned long long) page_size);
1221 return pages * page_size;
1226 * Entry point for the plugin.
1228 * @param cls the "struct GNUNET_DATASTORE_PluginEnvironment*"
1229 * @return NULL on error, othrewise the plugin context
1232 libgnunet_plugin_datastore_sqlite_init (void *cls)
1234 static struct Plugin plugin;
1235 struct GNUNET_DATASTORE_PluginEnvironment *env = cls;
1236 struct GNUNET_DATASTORE_PluginFunctions *api;
1238 if (plugin.env != NULL)
1239 return NULL; /* can only initialize once! */
1240 memset (&plugin, 0, sizeof(struct Plugin));
1243 database_setup (env->cfg, &plugin))
1245 database_shutdown (&plugin);
1248 api = GNUNET_malloc (sizeof (struct GNUNET_DATASTORE_PluginFunctions));
1250 api->estimate_size = &sqlite_plugin_estimate_size;
1251 api->put = &sqlite_plugin_put;
1252 api->update = &sqlite_plugin_update;
1253 api->get_key = &sqlite_plugin_get_key;
1254 api->get_replication = &sqlite_plugin_get_replication;
1255 api->get_expiration = &sqlite_plugin_get_expiration;
1256 api->get_zero_anonymity = &sqlite_plugin_get_zero_anonymity;
1257 api->drop = &sqlite_plugin_drop;
1258 GNUNET_log_from (GNUNET_ERROR_TYPE_INFO,
1259 "sqlite", _("Sqlite database running\n"));
1265 * Exit point from the plugin.
1267 * @param cls the plugin context (as returned by "init")
1268 * @return always NULL
1271 libgnunet_plugin_datastore_sqlite_done (void *cls)
1274 struct GNUNET_DATASTORE_PluginFunctions *api = cls;
1275 struct Plugin *plugin = api->cls;
1278 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1280 "sqlite plugin is done\n");
1284 if (plugin->drop_on_shutdown)
1285 fn = GNUNET_strdup (plugin->fn);
1287 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1289 "Shutting down database\n");
1291 database_shutdown (plugin);
1296 if (0 != UNLINK(fn))
1297 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING,
1303 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1305 "sqlite plugin is finished\n");
1310 /* end of plugin_datastore_sqlite.c */