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 * Precompiled SQL for replication decrement.
98 sqlite3_stmt *updRepl;
101 * Precompiled SQL for replication selection.
103 sqlite3_stmt *selRepl;
106 * Precompiled SQL for expiration selection.
108 sqlite3_stmt *selExpi;
111 * Precompiled SQL for expiration selection.
113 sqlite3_stmt *selZeroAnon;
116 * Precompiled SQL for insertion.
118 sqlite3_stmt *insertContent;
121 * Should the database be dropped on shutdown?
123 int drop_on_shutdown;
129 * @brief Prepare a SQL statement
131 * @param dbh handle to the database
132 * @param zSql SQL statement, UTF-8 encoded
133 * @param ppStmt set to the prepared statement
134 * @return 0 on success
137 sq_prepare (sqlite3 * dbh,
139 sqlite3_stmt ** ppStmt)
144 result = sqlite3_prepare_v2 (dbh,
148 (const char **) &dummy);
149 #if DEBUG_SQLITE && 0
150 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
152 "Prepared `%s' / %p: %d\n",
162 * Create our database indices.
164 * @param dbh handle to the database
167 create_indices (sqlite3 * dbh)
172 "CREATE INDEX IF NOT EXISTS idx_hash ON gn090 (hash)", NULL, NULL, NULL)) ||
175 "CREATE INDEX IF NOT EXISTS idx_hash_vhash ON gn090 (hash,vhash)", NULL,
178 sqlite3_exec (dbh, "CREATE INDEX IF NOT EXISTS idx_expire_repl ON gn090 (expire ASC,repl DESC)", NULL, NULL,
181 sqlite3_exec (dbh, "CREATE INDEX IF NOT EXISTS idx_comb ON gn090 (anonLevel ASC,expire ASC,prio,type,hash)",
182 NULL, NULL, NULL)) ||
184 sqlite3_exec (dbh, "CREATE INDEX IF NOT EXISTS idx_expire ON gn090 (expire)",
185 NULL, NULL, NULL)) ||
187 sqlite3_exec (dbh, "CREATE INDEX IF NOT EXISTS idx_repl_rvalue ON gn090 (repl,rvalue)",
188 NULL, NULL, NULL)) ||
190 sqlite3_exec (dbh, "CREATE INDEX IF NOT EXISTS idx_repl ON gn090 (repl DESC)",
192 GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR,
194 "Failed to create indices: %s\n",
195 sqlite3_errmsg (dbh));
200 #define CHECK(a) GNUNET_break(a)
204 #define ENULL_DEFINED 1
205 #define CHECK(a) if (! a) { GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "%s\n", e); sqlite3_free(e); }
210 * Initialize the database connections and associated
211 * data structures (create tables and indices
212 * as needed as well).
214 * @param cfg our configuration
215 * @param plugin the plugin context (state for this module)
216 * @return GNUNET_OK on success
219 database_setup (const struct GNUNET_CONFIGURATION_Handle *cfg,
220 struct Plugin *plugin)
229 GNUNET_CONFIGURATION_get_value_filename (cfg,
234 GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR,
236 _("Option `%s' in section `%s' missing in configuration!\n"),
239 return GNUNET_SYSERR;
241 if (GNUNET_OK != GNUNET_DISK_file_test (afsdir))
243 if (GNUNET_OK != GNUNET_DISK_directory_create_for_file (afsdir))
246 GNUNET_free (afsdir);
247 return GNUNET_SYSERR;
249 /* database is new or got deleted, reset payload to zero! */
250 plugin->env->duc (plugin->env->cls, 0);
253 plugin->fn = GNUNET_STRINGS_to_utf8 (afsdir, strlen (afsdir),
254 nl_langinfo (CODESET));
256 plugin->fn = GNUNET_STRINGS_to_utf8 (afsdir, strlen (afsdir),
257 "UTF-8"); /* good luck */
259 GNUNET_free (afsdir);
261 /* Open database and precompile statements */
262 if (sqlite3_open (plugin->fn, &plugin->dbh) != SQLITE_OK)
264 GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR,
266 _("Unable to initialize SQLite: %s.\n"),
267 sqlite3_errmsg (plugin->dbh));
268 return GNUNET_SYSERR;
271 sqlite3_exec (plugin->dbh,
272 "PRAGMA temp_store=MEMORY", NULL, NULL, ENULL));
274 sqlite3_exec (plugin->dbh,
275 "PRAGMA synchronous=OFF", NULL, NULL, ENULL));
277 sqlite3_exec (plugin->dbh,
278 "PRAGMA legacy_file_format=OFF", NULL, NULL, ENULL));
280 sqlite3_exec (plugin->dbh,
281 "PRAGMA auto_vacuum=INCREMENTAL", NULL, NULL, ENULL));
283 sqlite3_exec (plugin->dbh,
284 "PRAGMA locking_mode=EXCLUSIVE", NULL, NULL, ENULL));
286 sqlite3_exec (plugin->dbh,
287 "PRAGMA count_changes=OFF", NULL, NULL, ENULL));
289 sqlite3_exec (plugin->dbh,
290 "PRAGMA page_size=4092", NULL, NULL, ENULL));
292 CHECK (SQLITE_OK == sqlite3_busy_timeout (plugin->dbh, BUSY_TIMEOUT_MS));
295 /* We have to do it here, because otherwise precompiling SQL might fail */
297 sq_prepare (plugin->dbh,
298 "SELECT 1 FROM sqlite_master WHERE tbl_name = 'gn090'",
300 if ( (sqlite3_step (stmt) == SQLITE_DONE) &&
301 (sqlite3_exec (plugin->dbh,
302 "CREATE TABLE gn090 ("
303 " repl INT4 NOT NULL DEFAULT 0,"
304 " type INT4 NOT NULL DEFAULT 0,"
305 " prio INT4 NOT NULL DEFAULT 0,"
306 " anonLevel INT4 NOT NULL DEFAULT 0,"
307 " expire INT8 NOT NULL DEFAULT 0,"
308 " rvalue INT8 NOT NULL,"
309 " hash TEXT NOT NULL DEFAULT '',"
310 " vhash TEXT NOT NULL DEFAULT '',"
311 " value BLOB NOT NULL DEFAULT '')", NULL, NULL,
312 NULL) != SQLITE_OK) )
314 LOG_SQLITE (plugin, NULL,
315 GNUNET_ERROR_TYPE_ERROR,
317 sqlite3_finalize (stmt);
318 return GNUNET_SYSERR;
320 sqlite3_finalize (stmt);
321 create_indices (plugin->dbh);
323 if ((sq_prepare (plugin->dbh,
324 "UPDATE gn090 SET prio = prio + ?, expire = MAX(expire,?) WHERE _ROWID_ = ?",
325 &plugin->updPrio) != SQLITE_OK) ||
326 (sq_prepare (plugin->dbh,
327 "UPDATE gn090 SET repl = MAX (0, repl - 1) WHERE _ROWID_ = ?",
328 &plugin->updRepl) != SQLITE_OK) ||
330 /* FIXME: this is the O(n) version */
331 (sq_prepare (plugin->dbh,
332 "SELECT type,prio,anonLevel,expire,hash,value,_ROWID_ FROM gn090"
333 " ORDER BY repl DESC, Random() LIMIT 1",
334 &plugin->selRepl) != SQLITE_OK) ||
336 /* FIXME: this gives O(n) queries, presumably because the LEFT JOIN generates
337 a temporary table with all matching expressions before the ORDER BY and LIMIT
338 clauses are applied */
339 (sq_prepare (plugin->dbh,
340 "SELECT type,prio,anonLevel,expire,hash,value,gn090._ROWID_ "
341 "FROM (SELECT random() AS v) AS t1,"
342 " (SELECT MAX(repl) AS m FROM gn090 INDEXED BY idx_repl) AS t2 "
343 " LEFT JOIN gn090 INDEXED BY idx_repl_rvalue"
346 " NOT EXISTS (SELECT 1 FROM gn090 INDEXED BY idx_repl_rvalue WHERE repl=t2.m AND rvalue>=t1.v))"
347 " ORDER BY rvalue ASC"
349 &plugin->selRepl) != SQLITE_OK) ||
351 /* NOTE: this fails, because sqlite doesn't link the t2.m (or the t1.v) to the temporary result from before
352 (parse error during preparation) */
353 (sq_prepare (plugin->dbh,
354 "SELECT type,prio,anonLevel,expire,hash,value,_ROWID_ "
355 "FROM (SELECT random() AS v) AS t1,"
356 " (SELECT MAX(repl) AS m FROM gn090 INDEXED BY idx_repl) AS t2, "
357 " (SELECT type,prio,anonLevel,expire,hash,value,_ROWID_ FROM gn090 INDEXED BY idx_repl_rvalue"
358 " WHERE repl=t2.m AND" /* "no such column: t2.m" */
360 " NOT EXISTS (SELECT 1 FROM gn090 INDEXED BY idx_repl_rvalue WHERE repl=t2.m AND rvalue>=t1.v))"
361 " ORDER BY rvalue ASC"
363 &plugin->selRepl) != SQLITE_OK) ||
365 (sq_prepare (plugin->dbh,
366 "SELECT type,prio,anonLevel,expire,hash,value,_ROWID_ FROM gn090 "
367 " WHERE NOT EXISTS (SELECT 1 FROM gn090 WHERE expire < ?1 LIMIT 1) OR expire < ?1 "
368 " ORDER BY prio ASC LIMIT 1",
369 &plugin->selExpi) != SQLITE_OK) ||
370 (sq_prepare (plugin->dbh,
371 "SELECT type,prio,anonLevel,expire,hash,value,_ROWID_ FROM gn090 "
372 "WHERE (anonLevel = 0 AND type=?1) "
373 "ORDER BY hash DESC LIMIT 1 OFFSET ?2",
374 &plugin->selZeroAnon) != SQLITE_OK) ||
375 (sq_prepare (plugin->dbh,
376 "INSERT INTO gn090 (repl, type, prio, "
377 "anonLevel, expire, rvalue, hash, vhash, value) "
378 "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)",
379 &plugin->insertContent) != SQLITE_OK) ||
380 (sq_prepare (plugin->dbh,
381 "DELETE FROM gn090 WHERE _ROWID_ = ?",
382 &plugin->delRow) != SQLITE_OK))
384 LOG_SQLITE (plugin, NULL,
385 GNUNET_ERROR_TYPE_ERROR, "precompiling");
386 return GNUNET_SYSERR;
394 * Shutdown database connection and associate data
396 * @param plugin the plugin context (state for this module)
399 database_shutdown (struct Plugin *plugin)
402 #if SQLITE_VERSION_NUMBER >= 3007000
406 if (plugin->delRow != NULL)
407 sqlite3_finalize (plugin->delRow);
408 if (plugin->updPrio != NULL)
409 sqlite3_finalize (plugin->updPrio);
410 if (plugin->updRepl != NULL)
411 sqlite3_finalize (plugin->updRepl);
412 if (plugin->selRepl != NULL)
413 sqlite3_finalize (plugin->selRepl);
414 if (plugin->selExpi != NULL)
415 sqlite3_finalize (plugin->selExpi);
416 if (plugin->selZeroAnon != NULL)
417 sqlite3_finalize (plugin->selZeroAnon);
418 if (plugin->insertContent != NULL)
419 sqlite3_finalize (plugin->insertContent);
420 result = sqlite3_close(plugin->dbh);
421 #if SQLITE_VERSION_NUMBER >= 3007000
422 if (result == SQLITE_BUSY)
424 GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING,
426 _("Tried to close sqlite without finalizing all prepared statements.\n"));
427 stmt = sqlite3_next_stmt(plugin->dbh, NULL);
431 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
432 "sqlite", "Closing statement %p\n", stmt);
434 result = sqlite3_finalize(stmt);
436 if (result != SQLITE_OK)
437 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
439 "Failed to close statement %p: %d\n", stmt, result);
441 stmt = sqlite3_next_stmt(plugin->dbh, NULL);
443 result = sqlite3_close(plugin->dbh);
446 if (SQLITE_OK != result)
447 LOG_SQLITE (plugin, NULL,
448 GNUNET_ERROR_TYPE_ERROR,
451 GNUNET_free_non_null (plugin->fn);
456 * Delete the database entry with the given
459 * @param plugin the plugin context (state for this module)
460 * @param rid the ID of the row to delete
463 delete_by_rowid (struct Plugin* plugin,
464 unsigned long long rid)
467 sqlite3_bind_int64 (plugin->delRow, 1, rid))
469 LOG_SQLITE (plugin, NULL,
470 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, "sqlite3_bind_XXXX");
471 if (SQLITE_OK != sqlite3_reset (plugin->delRow))
472 LOG_SQLITE (plugin, NULL,
473 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, "sqlite3_reset");
474 return GNUNET_SYSERR;
476 if (SQLITE_DONE != sqlite3_step (plugin->delRow))
478 LOG_SQLITE (plugin, NULL,
479 GNUNET_ERROR_TYPE_ERROR |
480 GNUNET_ERROR_TYPE_BULK, "sqlite3_step");
481 if (SQLITE_OK != sqlite3_reset (plugin->delRow))
482 LOG_SQLITE (plugin, NULL,
483 GNUNET_ERROR_TYPE_ERROR |
484 GNUNET_ERROR_TYPE_BULK, "sqlite3_reset");
485 return GNUNET_SYSERR;
487 if (SQLITE_OK != sqlite3_reset (plugin->delRow))
488 LOG_SQLITE (plugin, NULL,
489 GNUNET_ERROR_TYPE_ERROR |
490 GNUNET_ERROR_TYPE_BULK, "sqlite3_reset");
496 * Store an item in the datastore.
499 * @param key key for the item
500 * @param size number of bytes in data
501 * @param data content stored
502 * @param type type of the content
503 * @param priority priority of the content
504 * @param anonymity anonymity-level for the content
505 * @param replication replication-level for the content
506 * @param expiration expiration time for the content
507 * @param msg set to an error message
508 * @return GNUNET_OK on success
511 sqlite_plugin_put (void *cls,
512 const GNUNET_HashCode *key,
515 enum GNUNET_BLOCK_Type type,
518 uint32_t replication,
519 struct GNUNET_TIME_Absolute expiration,
522 struct Plugin *plugin = cls;
526 GNUNET_HashCode vhash;
529 if (size > MAX_ITEM_SIZE)
530 return GNUNET_SYSERR;
532 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
534 "Storing in database block with type %u/key `%s'/priority %u/expiration in %llu ms (%lld).\n",
538 (unsigned long long) GNUNET_TIME_absolute_get_remaining (expiration).rel_value,
539 (long long) expiration.abs_value);
541 GNUNET_CRYPTO_hash (data, size, &vhash);
542 stmt = plugin->insertContent;
543 rvalue = GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK, UINT64_MAX);
544 if ((SQLITE_OK != sqlite3_bind_int (stmt, 1, replication)) ||
545 (SQLITE_OK != sqlite3_bind_int (stmt, 2, type)) ||
546 (SQLITE_OK != sqlite3_bind_int (stmt, 3, priority)) ||
547 (SQLITE_OK != sqlite3_bind_int (stmt, 4, anonymity)) ||
548 (SQLITE_OK != sqlite3_bind_int64 (stmt, 5, expiration.abs_value)) ||
549 (SQLITE_OK != sqlite3_bind_int64 (stmt, 6, rvalue)) ||
551 sqlite3_bind_blob (stmt, 7, key, sizeof (GNUNET_HashCode),
552 SQLITE_TRANSIENT)) ||
554 sqlite3_bind_blob (stmt, 8, &vhash, sizeof (GNUNET_HashCode),
557 sqlite3_bind_blob (stmt, 9, data, size,
562 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, "sqlite3_bind_XXXX");
563 if (SQLITE_OK != sqlite3_reset (stmt))
564 LOG_SQLITE (plugin, NULL,
565 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, "sqlite3_reset");
566 return GNUNET_SYSERR;
568 n = sqlite3_step (stmt);
572 plugin->env->duc (plugin->env->cls,
573 size + GNUNET_DATASTORE_ENTRY_OVERHEAD);
575 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
577 "Stored new entry (%u bytes)\n",
578 size + GNUNET_DATASTORE_ENTRY_OVERHEAD);
584 LOG_SQLITE (plugin, msg,
585 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
590 LOG_SQLITE (plugin, msg,
591 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
593 if (SQLITE_OK != sqlite3_reset (stmt))
594 LOG_SQLITE (plugin, NULL,
595 GNUNET_ERROR_TYPE_ERROR |
596 GNUNET_ERROR_TYPE_BULK, "sqlite3_reset");
597 database_shutdown (plugin);
598 database_setup (plugin->env->cfg,
600 return GNUNET_SYSERR;
602 if (SQLITE_OK != sqlite3_reset (stmt))
603 LOG_SQLITE (plugin, NULL,
604 GNUNET_ERROR_TYPE_ERROR |
605 GNUNET_ERROR_TYPE_BULK, "sqlite3_reset");
611 * Update the priority for a particular key in the datastore. If
612 * the expiration time in value is different than the time found in
613 * the datastore, the higher value should be kept. For the
614 * anonymity level, the lower value is to be used. The specified
615 * priority should be added to the existing priority, ignoring the
618 * Note that it is possible for multiple values to match this put.
619 * In that case, all of the respective values are updated.
621 * @param cls the plugin context (state for this module)
622 * @param uid unique identifier of the datum
623 * @param delta by how much should the priority
624 * change? If priority + delta < 0 the
625 * priority should be set to 0 (never go
627 * @param expire new expiration time should be the
628 * MAX of any existing expiration time and
630 * @param msg set to an error message
631 * @return GNUNET_OK on success
634 sqlite_plugin_update (void *cls,
636 int delta, struct GNUNET_TIME_Absolute expire,
639 struct Plugin *plugin = cls;
643 sqlite3_bind_int (plugin->updPrio, 1, delta)) ||
645 sqlite3_bind_int64 (plugin->updPrio, 2, expire.abs_value)) ||
647 sqlite3_bind_int64 (plugin->updPrio, 3, uid)) )
649 LOG_SQLITE (plugin, msg,
650 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, "sqlite3_bind_XXXX");
651 if (SQLITE_OK != sqlite3_reset (plugin->updPrio))
652 LOG_SQLITE (plugin, NULL,
653 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, "sqlite3_reset");
654 return GNUNET_SYSERR;
657 n = sqlite3_step (plugin->updPrio);
658 if (SQLITE_OK != sqlite3_reset (plugin->updPrio))
659 LOG_SQLITE (plugin, NULL,
660 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, "sqlite3_reset");
665 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
671 LOG_SQLITE (plugin, msg,
672 GNUNET_ERROR_TYPE_WARNING | GNUNET_ERROR_TYPE_BULK,
676 LOG_SQLITE (plugin, msg,
677 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
679 return GNUNET_SYSERR;
685 * Execute statement that gets a row and call the callback
686 * with the result. Resets the statement afterwards.
688 * @param plugin the plugin
689 * @param stmt the statement
690 * @param proc processor to call
691 * @param proc_cls closure for 'proc'
694 execute_get (struct Plugin *plugin,
696 PluginDatumProcessor proc, void *proc_cls)
699 struct GNUNET_TIME_Absolute expiration;
700 unsigned long long rowid;
704 n = sqlite3_step (stmt);
708 size = sqlite3_column_bytes (stmt, 5);
709 rowid = sqlite3_column_int64 (stmt, 6);
710 if (sqlite3_column_bytes (stmt, 4) != sizeof (GNUNET_HashCode))
712 GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING,
714 _("Invalid data in database. Trying to fix (by deletion).\n"));
715 if (SQLITE_OK != sqlite3_reset (stmt))
716 LOG_SQLITE (plugin, NULL,
717 GNUNET_ERROR_TYPE_ERROR |
718 GNUNET_ERROR_TYPE_BULK, "sqlite3_reset");
719 if (GNUNET_OK == delete_by_rowid (plugin, rowid))
720 plugin->env->duc (plugin->env->cls,
721 - (size + GNUNET_DATASTORE_ENTRY_OVERHEAD));
724 expiration.abs_value = sqlite3_column_int64 (stmt, 3);
726 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
728 "Found reply in database with expiration %llu\n",
729 (unsigned long long) expiration.abs_value);
731 ret = proc (proc_cls,
732 sqlite3_column_blob (stmt, 4) /* key */,
734 sqlite3_column_blob (stmt, 5) /* data */,
735 sqlite3_column_int (stmt, 0) /* type */,
736 sqlite3_column_int (stmt, 1) /* priority */,
737 sqlite3_column_int (stmt, 2) /* anonymity */,
740 if (SQLITE_OK != sqlite3_reset (stmt))
741 LOG_SQLITE (plugin, NULL,
742 GNUNET_ERROR_TYPE_ERROR |
743 GNUNET_ERROR_TYPE_BULK, "sqlite3_reset");
744 if ( (GNUNET_NO == ret) &&
745 (GNUNET_OK == delete_by_rowid (plugin, rowid)) )
746 plugin->env->duc (plugin->env->cls,
747 - (size + GNUNET_DATASTORE_ENTRY_OVERHEAD));
750 /* database must be empty */
751 if (SQLITE_OK != sqlite3_reset (stmt))
752 LOG_SQLITE (plugin, NULL,
753 GNUNET_ERROR_TYPE_ERROR |
754 GNUNET_ERROR_TYPE_BULK, "sqlite3_reset");
760 LOG_SQLITE (plugin, NULL,
761 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
763 if (SQLITE_OK != sqlite3_reset (stmt))
764 LOG_SQLITE (plugin, NULL,
765 GNUNET_ERROR_TYPE_ERROR |
766 GNUNET_ERROR_TYPE_BULK,
769 database_shutdown (plugin);
770 database_setup (plugin->env->cfg,
774 if (SQLITE_OK != sqlite3_reset (stmt))
775 LOG_SQLITE (plugin, NULL,
776 GNUNET_ERROR_TYPE_ERROR |
777 GNUNET_ERROR_TYPE_BULK, "sqlite3_reset");
778 proc (proc_cls, NULL, 0, NULL, 0, 0, 0,
779 GNUNET_TIME_UNIT_ZERO_ABS, 0);
785 * Select a subset of the items in the datastore and call
786 * the given processor for the item.
788 * @param cls our plugin context
789 * @param offset offset of the result (modulo num-results);
790 * specific ordering does not matter for the offset
791 * @param type entries of which type should be considered?
792 * Use 0 for any type.
793 * @param proc function to call on each matching value;
794 * will be called once with a NULL value at the end
795 * @param proc_cls closure for proc
798 sqlite_plugin_get_zero_anonymity (void *cls,
800 enum GNUNET_BLOCK_Type type,
801 PluginDatumProcessor proc,
804 struct Plugin *plugin = cls;
807 GNUNET_assert (type != GNUNET_BLOCK_TYPE_ANY);
808 stmt = plugin->selZeroAnon;
809 if ( (SQLITE_OK != sqlite3_bind_int (stmt, 1, type)) ||
810 (SQLITE_OK != sqlite3_bind_int64 (stmt, 2, offset)) )
812 LOG_SQLITE (plugin, NULL,
813 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
814 "sqlite3_bind_XXXX");
815 if (SQLITE_OK != sqlite3_reset (stmt))
816 LOG_SQLITE (plugin, NULL,
817 GNUNET_ERROR_TYPE_ERROR |
818 GNUNET_ERROR_TYPE_BULK,
820 proc (proc_cls, NULL, 0, NULL, 0, 0, 0,
821 GNUNET_TIME_UNIT_ZERO_ABS, 0);
824 execute_get (plugin, stmt, proc, proc_cls);
830 * Get results for a particular key in the datastore.
833 * @param offset offset (mod count).
834 * @param key key to match, never NULL
835 * @param vhash hash of the value, maybe NULL (to
836 * match all values that have the right key).
837 * Note that for DBlocks there is no difference
838 * betwen key and vhash, but for other blocks
840 * @param type entries of which type are relevant?
841 * Use 0 for any type.
842 * @param proc function to call on each matching value;
843 * will be called once with a NULL value at the end
844 * @param proc_cls closure for proc
847 sqlite_plugin_get_key (void *cls,
849 const GNUNET_HashCode *key,
850 const GNUNET_HashCode *vhash,
851 enum GNUNET_BLOCK_Type type,
852 PluginDatumProcessor proc, void *proc_cls)
854 struct Plugin *plugin = cls;
862 GNUNET_assert (proc != NULL);
863 GNUNET_assert (key != NULL);
864 GNUNET_snprintf (scratch, sizeof (scratch),
865 "SELECT count(*) FROM gn090 WHERE hash=?%s%s",
866 vhash == NULL ? "" : " AND vhash=?",
867 type == 0 ? "" : " AND type=?");
868 if (sq_prepare (plugin->dbh, scratch, &stmt) != SQLITE_OK)
870 LOG_SQLITE (plugin, NULL,
871 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, "sqlite_prepare");
872 proc (proc_cls, NULL, 0, NULL, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0);
876 ret = sqlite3_bind_blob (stmt, sqoff++,
877 key, sizeof (GNUNET_HashCode), SQLITE_TRANSIENT);
878 if ((vhash != NULL) && (ret == SQLITE_OK))
879 ret = sqlite3_bind_blob (stmt, sqoff++,
881 sizeof (GNUNET_HashCode), SQLITE_TRANSIENT);
882 if ((type != 0) && (ret == SQLITE_OK))
883 ret = sqlite3_bind_int (stmt, sqoff++, type);
884 if (SQLITE_OK != ret)
886 LOG_SQLITE (plugin, NULL,
887 GNUNET_ERROR_TYPE_ERROR, "sqlite_bind");
888 sqlite3_finalize (stmt);
889 proc (proc_cls, NULL, 0, NULL, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0);
892 ret = sqlite3_step (stmt);
893 if (ret != SQLITE_ROW)
895 LOG_SQLITE (plugin, NULL,
896 GNUNET_ERROR_TYPE_ERROR| GNUNET_ERROR_TYPE_BULK,
898 sqlite3_finalize (stmt);
899 proc (proc_cls, NULL, 0, NULL, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0);
902 total = sqlite3_column_int (stmt, 0);
903 sqlite3_finalize (stmt);
906 proc (proc_cls, NULL, 0, NULL, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0);
909 limit_off = (int) (offset % total);
912 GNUNET_snprintf (scratch, sizeof (scratch),
913 "SELECT type, prio, anonLevel, expire, hash, value, _ROWID_ "
914 "FROM gn090 WHERE hash=?%s%s "
915 "ORDER BY _ROWID_ ASC LIMIT 1 OFFSET ?",
916 vhash == NULL ? "" : " AND vhash=?",
917 type == 0 ? "" : " AND type=?");
918 if (sq_prepare (plugin->dbh, scratch, &stmt) != SQLITE_OK)
920 LOG_SQLITE (plugin, NULL,
921 GNUNET_ERROR_TYPE_ERROR |
922 GNUNET_ERROR_TYPE_BULK, "sqlite_prepare");
923 proc (proc_cls, NULL, 0, NULL, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0);
927 ret = sqlite3_bind_blob (stmt,
930 sizeof (GNUNET_HashCode),
932 if ((vhash != NULL) && (ret == SQLITE_OK))
933 ret = sqlite3_bind_blob (stmt,
936 sizeof (GNUNET_HashCode), SQLITE_TRANSIENT);
937 if ((type != 0) && (ret == SQLITE_OK))
938 ret = sqlite3_bind_int (stmt, sqoff++, type);
939 if (ret == SQLITE_OK)
940 ret = sqlite3_bind_int64 (stmt, sqoff++, limit_off);
941 if (ret != SQLITE_OK)
943 LOG_SQLITE (plugin, NULL,
944 GNUNET_ERROR_TYPE_ERROR |
945 GNUNET_ERROR_TYPE_BULK, "sqlite_bind");
946 proc (proc_cls, NULL, 0, NULL, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0);
949 execute_get (plugin, stmt, proc, proc_cls);
950 sqlite3_finalize (stmt);
956 * Context for 'repl_proc' function.
962 * Function to call for the result (or the NULL).
964 PluginDatumProcessor proc;
977 * Yes if UID was set.
984 * Wrapper for the processor for 'sqlite_plugin_replication_get'.
985 * Decrements the replication counter and calls the original
989 * @param key key for the content
990 * @param size number of bytes in data
991 * @param data content stored
992 * @param type type of the content
993 * @param priority priority of the content
994 * @param anonymity anonymity-level for the content
995 * @param expiration expiration time for the content
996 * @param uid unique identifier for the datum;
997 * maybe 0 if no unique identifier is available
999 * @return GNUNET_OK for normal return,
1000 * GNUNET_NO to delete the item
1003 repl_proc (void *cls,
1004 const GNUNET_HashCode *key,
1007 enum GNUNET_BLOCK_Type type,
1010 struct GNUNET_TIME_Absolute expiration,
1013 struct ReplCtx *rc = cls;
1016 ret = rc->proc (rc->proc_cls,
1019 type, priority, anonymity, expiration,
1024 rc->have_uid = GNUNET_YES;
1031 * Get a random item for replication. Returns a single random item
1032 * from those with the highest replication counters. The item's
1033 * replication counter is decremented by one IF it was positive before.
1034 * Call 'proc' with all values ZERO or NULL if the datastore is empty.
1036 * @param cls closure
1037 * @param proc function to call the value (once only).
1038 * @param proc_cls closure for proc
1041 sqlite_plugin_get_replication (void *cls,
1042 PluginDatumProcessor proc, void *proc_cls)
1044 struct Plugin *plugin = cls;
1048 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1050 "Getting random block based on replication order.\n");
1052 rc.have_uid = GNUNET_NO;
1054 rc.proc_cls = proc_cls;
1055 execute_get (plugin, plugin->selRepl, &repl_proc, &rc);
1056 if (GNUNET_YES == rc.have_uid)
1059 sqlite3_bind_int64 (plugin->updRepl, 1, rc.uid))
1061 LOG_SQLITE (plugin, NULL,
1062 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, "sqlite3_bind_XXXX");
1063 if (SQLITE_OK != sqlite3_reset (plugin->updRepl))
1064 LOG_SQLITE (plugin, NULL,
1065 GNUNET_ERROR_TYPE_ERROR |
1066 GNUNET_ERROR_TYPE_BULK, "sqlite3_reset");
1069 if (SQLITE_DONE != sqlite3_step (plugin->updRepl))
1070 LOG_SQLITE (plugin, NULL,
1071 GNUNET_ERROR_TYPE_ERROR |
1072 GNUNET_ERROR_TYPE_BULK, "sqlite3_step");
1073 if (SQLITE_OK != sqlite3_reset (plugin->updRepl))
1074 LOG_SQLITE (plugin, NULL,
1075 GNUNET_ERROR_TYPE_ERROR |
1076 GNUNET_ERROR_TYPE_BULK, "sqlite3_reset");
1083 * Get a random item that has expired or has low priority.
1084 * Call 'proc' with all values ZERO or NULL if the datastore is empty.
1086 * @param cls closure
1087 * @param proc function to call the value (once only).
1088 * @param proc_cls closure for proc
1091 sqlite_plugin_get_expiration (void *cls,
1092 PluginDatumProcessor proc, void *proc_cls)
1094 struct Plugin *plugin = cls;
1096 struct GNUNET_TIME_Absolute now;
1099 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1101 "Getting random block based on expiration and priority order.\n");
1103 now = GNUNET_TIME_absolute_get ();
1104 stmt = plugin->selExpi;
1105 if (SQLITE_OK != sqlite3_bind_int64 (stmt, 1, now.abs_value))
1107 LOG_SQLITE (plugin, NULL,
1108 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, "sqlite3_bind_XXXX");
1109 if (SQLITE_OK != sqlite3_reset (stmt))
1110 LOG_SQLITE (plugin, NULL,
1111 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, "sqlite3_reset");
1112 proc (proc_cls, NULL, 0, NULL, 0, 0, 0,
1113 GNUNET_TIME_UNIT_ZERO_ABS, 0);
1116 execute_get (plugin, stmt, proc, proc_cls);
1123 * @param cls our plugin context
1126 sqlite_plugin_drop (void *cls)
1128 struct Plugin *plugin = cls;
1129 plugin->drop_on_shutdown = GNUNET_YES;
1134 * Get an estimate of how much space the database is
1137 * @param cls the 'struct Plugin'
1138 * @return the size of the database on disk (estimate)
1140 static unsigned long long
1141 sqlite_plugin_estimate_size (void *cls)
1143 struct Plugin *plugin = cls;
1151 if (SQLITE_VERSION_NUMBER < 3006000)
1153 GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING,
1155 _("sqlite version to old to determine size, assuming zero\n"));
1159 sqlite3_exec (plugin->dbh,
1160 "VACUUM", NULL, NULL, ENULL));
1162 sqlite3_exec (plugin->dbh,
1163 "PRAGMA auto_vacuum=INCREMENTAL", NULL, NULL, ENULL));
1165 sq_prepare (plugin->dbh,
1166 "PRAGMA page_count",
1169 sqlite3_step (stmt))
1170 pages = sqlite3_column_int64 (stmt, 0);
1173 sqlite3_finalize (stmt);
1175 sq_prepare (plugin->dbh,
1178 CHECK (SQLITE_ROW ==
1179 sqlite3_step (stmt));
1180 page_size = sqlite3_column_int64 (stmt, 0);
1181 sqlite3_finalize (stmt);
1182 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1183 _("Using sqlite page utilization to estimate payload (%llu pages of size %llu bytes)\n"),
1184 (unsigned long long) pages,
1185 (unsigned long long) page_size);
1186 return pages * page_size;
1191 * Entry point for the plugin.
1193 * @param cls the "struct GNUNET_DATASTORE_PluginEnvironment*"
1194 * @return NULL on error, othrewise the plugin context
1197 libgnunet_plugin_datastore_sqlite_init (void *cls)
1199 static struct Plugin plugin;
1200 struct GNUNET_DATASTORE_PluginEnvironment *env = cls;
1201 struct GNUNET_DATASTORE_PluginFunctions *api;
1203 if (plugin.env != NULL)
1204 return NULL; /* can only initialize once! */
1205 memset (&plugin, 0, sizeof(struct Plugin));
1208 database_setup (env->cfg, &plugin))
1210 database_shutdown (&plugin);
1213 api = GNUNET_malloc (sizeof (struct GNUNET_DATASTORE_PluginFunctions));
1215 api->estimate_size = &sqlite_plugin_estimate_size;
1216 api->put = &sqlite_plugin_put;
1217 api->update = &sqlite_plugin_update;
1218 api->get_key = &sqlite_plugin_get_key;
1219 api->get_replication = &sqlite_plugin_get_replication;
1220 api->get_expiration = &sqlite_plugin_get_expiration;
1221 api->get_zero_anonymity = &sqlite_plugin_get_zero_anonymity;
1222 api->drop = &sqlite_plugin_drop;
1223 GNUNET_log_from (GNUNET_ERROR_TYPE_INFO,
1224 "sqlite", _("Sqlite database running\n"));
1230 * Exit point from the plugin.
1232 * @param cls the plugin context (as returned by "init")
1233 * @return always NULL
1236 libgnunet_plugin_datastore_sqlite_done (void *cls)
1239 struct GNUNET_DATASTORE_PluginFunctions *api = cls;
1240 struct Plugin *plugin = api->cls;
1243 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1245 "sqlite plugin is done\n");
1249 if (plugin->drop_on_shutdown)
1250 fn = GNUNET_strdup (plugin->fn);
1252 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1254 "Shutting down database\n");
1256 database_shutdown (plugin);
1261 if (0 != UNLINK(fn))
1262 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING,
1268 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1270 "sqlite plugin is finished\n");
1275 /* end of plugin_datastore_sqlite.c */