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)
171 "CREATE INDEX idx_hash ON gn090 (hash)", NULL, NULL, NULL);
173 "CREATE INDEX idx_hash_vhash ON gn090 (hash,vhash)", NULL,
175 sqlite3_exec (dbh, "CREATE INDEX idx_expire_repl ON gn090 (expire ASC,repl DESC)", NULL, NULL,
177 sqlite3_exec (dbh, "CREATE INDEX idx_comb ON gn090 (anonLevel ASC,expire ASC,prio,type,hash)",
179 sqlite3_exec (dbh, "CREATE INDEX idx_expire ON gn090 (expire)",
181 sqlite3_exec (dbh, "CREATE INDEX idx_repl_rvalue ON gn090 (repl,rvalue)",
187 #define CHECK(a) GNUNET_break(a)
191 #define ENULL_DEFINED 1
192 #define CHECK(a) if (! a) { GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "%s\n", e); sqlite3_free(e); }
197 * Initialize the database connections and associated
198 * data structures (create tables and indices
199 * as needed as well).
201 * @param cfg our configuration
202 * @param plugin the plugin context (state for this module)
203 * @return GNUNET_OK on success
206 database_setup (const struct GNUNET_CONFIGURATION_Handle *cfg,
207 struct Plugin *plugin)
216 GNUNET_CONFIGURATION_get_value_filename (cfg,
221 GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR,
223 _("Option `%s' in section `%s' missing in configuration!\n"),
226 return GNUNET_SYSERR;
228 if (GNUNET_OK != GNUNET_DISK_file_test (afsdir))
230 if (GNUNET_OK != GNUNET_DISK_directory_create_for_file (afsdir))
233 GNUNET_free (afsdir);
234 return GNUNET_SYSERR;
236 /* database is new or got deleted, reset payload to zero! */
237 plugin->env->duc (plugin->env->cls, 0);
240 plugin->fn = GNUNET_STRINGS_to_utf8 (afsdir, strlen (afsdir),
241 nl_langinfo (CODESET));
243 plugin->fn = GNUNET_STRINGS_to_utf8 (afsdir, strlen (afsdir),
244 "UTF-8"); /* good luck */
246 GNUNET_free (afsdir);
248 /* Open database and precompile statements */
249 if (sqlite3_open (plugin->fn, &plugin->dbh) != SQLITE_OK)
251 GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR,
253 _("Unable to initialize SQLite: %s.\n"),
254 sqlite3_errmsg (plugin->dbh));
255 return GNUNET_SYSERR;
258 sqlite3_exec (plugin->dbh,
259 "PRAGMA temp_store=MEMORY", NULL, NULL, ENULL));
261 sqlite3_exec (plugin->dbh,
262 "PRAGMA synchronous=OFF", NULL, NULL, ENULL));
264 sqlite3_exec (plugin->dbh,
265 "PRAGMA legacy_file_format=OFF", NULL, NULL, ENULL));
267 sqlite3_exec (plugin->dbh,
268 "PRAGMA auto_vacuum=INCREMENTAL", NULL, NULL, ENULL));
270 sqlite3_exec (plugin->dbh,
271 "PRAGMA locking_mode=EXCLUSIVE", NULL, NULL, ENULL));
273 sqlite3_exec (plugin->dbh,
274 "PRAGMA count_changes=OFF", NULL, NULL, ENULL));
276 sqlite3_exec (plugin->dbh,
277 "PRAGMA page_size=4092", NULL, NULL, ENULL));
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) &&
288 (sqlite3_exec (plugin->dbh,
289 "CREATE TABLE gn090 ("
290 " repl INT4 NOT NULL DEFAULT 0,"
291 " type INT4 NOT NULL DEFAULT 0,"
292 " prio INT4 NOT NULL DEFAULT 0,"
293 " anonLevel INT4 NOT NULL DEFAULT 0,"
294 " expire INT8 NOT NULL DEFAULT 0,"
295 " rvalue INT8 NOT NULL,"
296 " hash TEXT NOT NULL DEFAULT '',"
297 " vhash TEXT NOT NULL DEFAULT '',"
298 " value BLOB NOT NULL DEFAULT '')", NULL, NULL,
299 NULL) != SQLITE_OK) )
301 LOG_SQLITE (plugin, NULL,
302 GNUNET_ERROR_TYPE_ERROR,
304 sqlite3_finalize (stmt);
305 return GNUNET_SYSERR;
307 sqlite3_finalize (stmt);
308 create_indices (plugin->dbh);
310 if ((sq_prepare (plugin->dbh,
311 "UPDATE gn090 SET prio = prio + ?, expire = MAX(expire,?) WHERE _ROWID_ = ?",
312 &plugin->updPrio) != SQLITE_OK) ||
313 (sq_prepare (plugin->dbh,
314 "UPDATE gn090 SET repl = MAX (0, repl - 1) WHERE _ROWID_ = ?",
315 &plugin->updRepl) != SQLITE_OK) ||
316 (sq_prepare (plugin->dbh,
317 "SELECT type,prio,anonLevel,expire,hash,value,_ROWID_ FROM gn090"
318 " ORDER BY repl DESC, Random() LIMIT 1",
319 &plugin->selRepl) != SQLITE_OK) ||
320 (sq_prepare (plugin->dbh,
321 "SELECT type,prio,anonLevel,expire,hash,value,_ROWID_ FROM gn090 "
322 " WHERE NOT EXISTS (SELECT 1 FROM gn090 WHERE expire < ?1 LIMIT 1) OR expire < ?1 "
323 " ORDER BY prio ASC LIMIT 1",
324 &plugin->selExpi) != SQLITE_OK) ||
325 (sq_prepare (plugin->dbh,
326 "SELECT type,prio,anonLevel,expire,hash,value,_ROWID_ FROM gn090 "
327 "WHERE (anonLevel = 0 AND type=?1) "
328 "ORDER BY hash DESC LIMIT 1 OFFSET ?2",
329 &plugin->selZeroAnon) != SQLITE_OK) ||
330 (sq_prepare (plugin->dbh,
331 "INSERT INTO gn090 (repl, type, prio, "
332 "anonLevel, expire, rvalue, hash, vhash, value) "
333 "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)",
334 &plugin->insertContent) != SQLITE_OK) ||
335 (sq_prepare (plugin->dbh,
336 "DELETE FROM gn090 WHERE _ROWID_ = ?",
337 &plugin->delRow) != SQLITE_OK))
339 LOG_SQLITE (plugin, NULL,
340 GNUNET_ERROR_TYPE_ERROR, "precompiling");
341 return GNUNET_SYSERR;
349 * Shutdown database connection and associate data
351 * @param plugin the plugin context (state for this module)
354 database_shutdown (struct Plugin *plugin)
357 #if SQLITE_VERSION_NUMBER >= 3007000
361 if (plugin->delRow != NULL)
362 sqlite3_finalize (plugin->delRow);
363 if (plugin->updPrio != NULL)
364 sqlite3_finalize (plugin->updPrio);
365 if (plugin->updRepl != NULL)
366 sqlite3_finalize (plugin->updRepl);
367 if (plugin->selRepl != NULL)
368 sqlite3_finalize (plugin->selRepl);
369 if (plugin->selExpi != NULL)
370 sqlite3_finalize (plugin->selExpi);
371 if (plugin->selZeroAnon != NULL)
372 sqlite3_finalize (plugin->selZeroAnon);
373 if (plugin->insertContent != NULL)
374 sqlite3_finalize (plugin->insertContent);
375 result = sqlite3_close(plugin->dbh);
376 #if SQLITE_VERSION_NUMBER >= 3007000
377 if (result == SQLITE_BUSY)
379 GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING,
381 _("Tried to close sqlite without finalizing all prepared statements.\n"));
382 stmt = sqlite3_next_stmt(plugin->dbh, NULL);
386 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
387 "sqlite", "Closing statement %p\n", stmt);
389 result = sqlite3_finalize(stmt);
391 if (result != SQLITE_OK)
392 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
394 "Failed to close statement %p: %d\n", stmt, result);
396 stmt = sqlite3_next_stmt(plugin->dbh, NULL);
398 result = sqlite3_close(plugin->dbh);
401 if (SQLITE_OK != result)
402 LOG_SQLITE (plugin, NULL,
403 GNUNET_ERROR_TYPE_ERROR,
406 GNUNET_free_non_null (plugin->fn);
411 * Delete the database entry with the given
414 * @param plugin the plugin context (state for this module)
415 * @param rid the ID of the row to delete
418 delete_by_rowid (struct Plugin* plugin,
419 unsigned long long rid)
421 sqlite3_bind_int64 (plugin->delRow, 1, rid);
422 if (SQLITE_DONE != sqlite3_step (plugin->delRow))
424 LOG_SQLITE (plugin, NULL,
425 GNUNET_ERROR_TYPE_ERROR |
426 GNUNET_ERROR_TYPE_BULK, "sqlite3_step");
427 if (SQLITE_OK != sqlite3_reset (plugin->delRow))
428 LOG_SQLITE (plugin, NULL,
429 GNUNET_ERROR_TYPE_ERROR |
430 GNUNET_ERROR_TYPE_BULK, "sqlite3_reset");
431 return GNUNET_SYSERR;
433 if (SQLITE_OK != sqlite3_reset (plugin->delRow))
434 LOG_SQLITE (plugin, NULL,
435 GNUNET_ERROR_TYPE_ERROR |
436 GNUNET_ERROR_TYPE_BULK, "sqlite3_reset");
442 * Store an item in the datastore.
445 * @param key key for the item
446 * @param size number of bytes in data
447 * @param data content stored
448 * @param type type of the content
449 * @param priority priority of the content
450 * @param anonymity anonymity-level for the content
451 * @param replication replication-level for the content
452 * @param expiration expiration time for the content
453 * @param msg set to an error message
454 * @return GNUNET_OK on success
457 sqlite_plugin_put (void *cls,
458 const GNUNET_HashCode *key,
461 enum GNUNET_BLOCK_Type type,
464 uint32_t replication,
465 struct GNUNET_TIME_Absolute expiration,
468 struct Plugin *plugin = cls;
472 GNUNET_HashCode vhash;
475 if (size > MAX_ITEM_SIZE)
476 return GNUNET_SYSERR;
478 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
480 "Storing in database block with type %u/key `%s'/priority %u/expiration in %llu ms (%lld).\n",
484 (unsigned long long) GNUNET_TIME_absolute_get_remaining (expiration).rel_value,
485 (long long) expiration.abs_value);
487 GNUNET_CRYPTO_hash (data, size, &vhash);
488 stmt = plugin->insertContent;
489 rvalue = GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK, UINT64_MAX);
490 if ((SQLITE_OK != sqlite3_bind_int (stmt, 1, replication)) ||
491 (SQLITE_OK != sqlite3_bind_int (stmt, 2, type)) ||
492 (SQLITE_OK != sqlite3_bind_int (stmt, 3, priority)) ||
493 (SQLITE_OK != sqlite3_bind_int (stmt, 4, anonymity)) ||
494 (SQLITE_OK != sqlite3_bind_int64 (stmt, 5, expiration.abs_value)) ||
495 (SQLITE_OK != sqlite3_bind_int64 (stmt, 6, rvalue)) ||
497 sqlite3_bind_blob (stmt, 7, key, sizeof (GNUNET_HashCode),
498 SQLITE_TRANSIENT)) ||
500 sqlite3_bind_blob (stmt, 8, &vhash, sizeof (GNUNET_HashCode),
503 sqlite3_bind_blob (stmt, 9, data, size,
508 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, "sqlite3_bind_XXXX");
509 if (SQLITE_OK != sqlite3_reset (stmt))
510 LOG_SQLITE (plugin, NULL,
511 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, "sqlite3_reset");
512 return GNUNET_SYSERR;
514 n = sqlite3_step (stmt);
518 plugin->env->duc (plugin->env->cls,
519 size + GNUNET_DATASTORE_ENTRY_OVERHEAD);
521 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
523 "Stored new entry (%u bytes)\n",
524 size + GNUNET_DATASTORE_ENTRY_OVERHEAD);
530 LOG_SQLITE (plugin, msg,
531 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
536 LOG_SQLITE (plugin, msg,
537 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
539 if (SQLITE_OK != sqlite3_reset (stmt))
540 LOG_SQLITE (plugin, NULL,
541 GNUNET_ERROR_TYPE_ERROR |
542 GNUNET_ERROR_TYPE_BULK, "sqlite3_reset");
543 database_shutdown (plugin);
544 database_setup (plugin->env->cfg,
546 return GNUNET_SYSERR;
548 if (SQLITE_OK != sqlite3_reset (stmt))
549 LOG_SQLITE (plugin, NULL,
550 GNUNET_ERROR_TYPE_ERROR |
551 GNUNET_ERROR_TYPE_BULK, "sqlite3_reset");
557 * Update the priority for a particular key in the datastore. If
558 * the expiration time in value is different than the time found in
559 * the datastore, the higher value should be kept. For the
560 * anonymity level, the lower value is to be used. The specified
561 * priority should be added to the existing priority, ignoring the
564 * Note that it is possible for multiple values to match this put.
565 * In that case, all of the respective values are updated.
567 * @param cls the plugin context (state for this module)
568 * @param uid unique identifier of the datum
569 * @param delta by how much should the priority
570 * change? If priority + delta < 0 the
571 * priority should be set to 0 (never go
573 * @param expire new expiration time should be the
574 * MAX of any existing expiration time and
576 * @param msg set to an error message
577 * @return GNUNET_OK on success
580 sqlite_plugin_update (void *cls,
582 int delta, struct GNUNET_TIME_Absolute expire,
585 struct Plugin *plugin = cls;
588 sqlite3_bind_int (plugin->updPrio, 1, delta);
589 sqlite3_bind_int64 (plugin->updPrio, 2, expire.abs_value);
590 sqlite3_bind_int64 (plugin->updPrio, 3, uid);
591 n = sqlite3_step (plugin->updPrio);
592 sqlite3_reset (plugin->updPrio);
597 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
603 LOG_SQLITE (plugin, msg,
604 GNUNET_ERROR_TYPE_WARNING | GNUNET_ERROR_TYPE_BULK,
608 LOG_SQLITE (plugin, msg,
609 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
611 return GNUNET_SYSERR;
617 * Execute statement that gets a row and call the callback
618 * with the result. Resets the statement afterwards.
620 * @param plugin the plugin
621 * @param stmt the statement
622 * @param proc processor to call
623 * @param proc_cls closure for 'proc'
626 execute_get (struct Plugin *plugin,
628 PluginDatumProcessor proc, void *proc_cls)
631 struct GNUNET_TIME_Absolute expiration;
632 unsigned long long rowid;
636 n = sqlite3_step (stmt);
640 size = sqlite3_column_bytes (stmt, 5);
641 rowid = sqlite3_column_int64 (stmt, 6);
642 if (sqlite3_column_bytes (stmt, 4) != sizeof (GNUNET_HashCode))
644 GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING,
646 _("Invalid data in database. Trying to fix (by deletion).\n"));
647 if (SQLITE_OK != sqlite3_reset (stmt))
648 LOG_SQLITE (plugin, NULL,
649 GNUNET_ERROR_TYPE_ERROR |
650 GNUNET_ERROR_TYPE_BULK, "sqlite3_reset");
651 if (GNUNET_OK == delete_by_rowid (plugin, rowid))
652 plugin->env->duc (plugin->env->cls,
653 - (size + GNUNET_DATASTORE_ENTRY_OVERHEAD));
656 expiration.abs_value = sqlite3_column_int64 (stmt, 3);
658 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
660 "Found reply in database with expiration %llu\n",
661 (unsigned long long) expiration.abs_value);
663 ret = proc (proc_cls,
664 sqlite3_column_blob (stmt, 4) /* key */,
666 sqlite3_column_blob (stmt, 5) /* data */,
667 sqlite3_column_int (stmt, 0) /* type */,
668 sqlite3_column_int (stmt, 1) /* priority */,
669 sqlite3_column_int (stmt, 2) /* anonymity */,
672 if (SQLITE_OK != sqlite3_reset (stmt))
673 LOG_SQLITE (plugin, NULL,
674 GNUNET_ERROR_TYPE_ERROR |
675 GNUNET_ERROR_TYPE_BULK, "sqlite3_reset");
676 if ( (GNUNET_NO == ret) &&
677 (GNUNET_OK == delete_by_rowid (plugin, rowid)) )
678 plugin->env->duc (plugin->env->cls,
679 - (size + GNUNET_DATASTORE_ENTRY_OVERHEAD));
682 /* database must be empty */
683 if (SQLITE_OK != sqlite3_reset (stmt))
684 LOG_SQLITE (plugin, NULL,
685 GNUNET_ERROR_TYPE_ERROR |
686 GNUNET_ERROR_TYPE_BULK, "sqlite3_reset");
692 LOG_SQLITE (plugin, NULL,
693 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
695 if (SQLITE_OK != sqlite3_reset (stmt))
696 LOG_SQLITE (plugin, NULL,
697 GNUNET_ERROR_TYPE_ERROR |
698 GNUNET_ERROR_TYPE_BULK,
701 database_shutdown (plugin);
702 database_setup (plugin->env->cfg,
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 proc (proc_cls, NULL, 0, NULL, 0, 0, 0,
711 GNUNET_TIME_UNIT_ZERO_ABS, 0);
717 * Select a subset of the items in the datastore and call
718 * the given processor for the item.
720 * @param cls our plugin context
721 * @param type entries of which type should be considered?
722 * Use 0 for any type.
723 * @param proc function to call on each matching value;
724 * will be called once with a NULL value at the end
725 * @param proc_cls closure for proc
728 sqlite_plugin_get_zero_anonymity (void *cls,
730 enum GNUNET_BLOCK_Type type,
731 PluginDatumProcessor proc,
734 struct Plugin *plugin = cls;
737 GNUNET_assert (type != GNUNET_BLOCK_TYPE_ANY);
738 stmt = plugin->selZeroAnon;
739 if ( (SQLITE_OK != sqlite3_bind_int (stmt, 1, type)) ||
740 (SQLITE_OK != sqlite3_bind_int64 (stmt, 2, offset)) )
742 LOG_SQLITE (plugin, NULL,
743 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
744 "sqlite3_bind_XXXX");
745 if (SQLITE_OK != sqlite3_reset (stmt))
746 LOG_SQLITE (plugin, NULL,
747 GNUNET_ERROR_TYPE_ERROR |
748 GNUNET_ERROR_TYPE_BULK,
750 proc (proc_cls, NULL, 0, NULL, 0, 0, 0,
751 GNUNET_TIME_UNIT_ZERO_ABS, 0);
754 execute_get (plugin, stmt, proc, proc_cls);
760 * Get results for a particular key in the datastore.
763 * @param offset offset (mod count).
764 * @param key key to match, never NULL
765 * @param vhash hash of the value, maybe NULL (to
766 * match all values that have the right key).
767 * Note that for DBlocks there is no difference
768 * betwen key and vhash, but for other blocks
770 * @param type entries of which type are relevant?
771 * Use 0 for any type.
772 * @param proc function to call on each matching value;
773 * will be called once with a NULL value at the end
774 * @param proc_cls closure for proc
777 sqlite_plugin_get_key (void *cls,
779 const GNUNET_HashCode *key,
780 const GNUNET_HashCode *vhash,
781 enum GNUNET_BLOCK_Type type,
782 PluginDatumProcessor proc, void *proc_cls)
784 struct Plugin *plugin = cls;
792 GNUNET_assert (proc != NULL);
793 GNUNET_assert (key != NULL);
794 GNUNET_snprintf (scratch, sizeof (scratch),
795 "SELECT count(*) FROM gn090 WHERE hash=?%s%s",
796 vhash == NULL ? "" : " AND vhash=?",
797 type == 0 ? "" : " AND type=?");
798 if (sq_prepare (plugin->dbh, scratch, &stmt) != SQLITE_OK)
800 LOG_SQLITE (plugin, NULL,
801 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, "sqlite_prepare");
802 proc (proc_cls, NULL, 0, NULL, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0);
806 ret = sqlite3_bind_blob (stmt, sqoff++,
807 key, sizeof (GNUNET_HashCode), SQLITE_TRANSIENT);
808 if ((vhash != NULL) && (ret == SQLITE_OK))
809 ret = sqlite3_bind_blob (stmt, sqoff++,
811 sizeof (GNUNET_HashCode), SQLITE_TRANSIENT);
812 if ((type != 0) && (ret == SQLITE_OK))
813 ret = sqlite3_bind_int (stmt, sqoff++, type);
814 if (SQLITE_OK != ret)
816 LOG_SQLITE (plugin, NULL,
817 GNUNET_ERROR_TYPE_ERROR, "sqlite_bind");
818 sqlite3_finalize (stmt);
819 proc (proc_cls, NULL, 0, NULL, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0);
822 ret = sqlite3_step (stmt);
823 if (ret != SQLITE_ROW)
825 LOG_SQLITE (plugin, NULL,
826 GNUNET_ERROR_TYPE_ERROR| GNUNET_ERROR_TYPE_BULK,
828 sqlite3_finalize (stmt);
829 proc (proc_cls, NULL, 0, NULL, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0);
832 total = sqlite3_column_int (stmt, 0);
833 sqlite3_finalize (stmt);
836 proc (proc_cls, NULL, 0, NULL, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0);
839 limit_off = (int) (offset % total);
842 GNUNET_snprintf (scratch, sizeof (scratch),
843 "SELECT type, prio, anonLevel, expire, hash, value, _ROWID_ "
844 "FROM gn090 WHERE hash=?%s%s "
845 "ORDER BY _ROWID_ ASC LIMIT 1 OFFSET ?",
846 vhash == NULL ? "" : " AND vhash=?",
847 type == 0 ? "" : " AND type=?");
848 if (sq_prepare (plugin->dbh, scratch, &stmt) != SQLITE_OK)
850 LOG_SQLITE (plugin, NULL,
851 GNUNET_ERROR_TYPE_ERROR |
852 GNUNET_ERROR_TYPE_BULK, "sqlite_prepare");
853 proc (proc_cls, NULL, 0, NULL, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0);
857 ret = sqlite3_bind_blob (stmt,
860 sizeof (GNUNET_HashCode),
862 if ((vhash != NULL) && (ret == SQLITE_OK))
863 ret = sqlite3_bind_blob (stmt,
866 sizeof (GNUNET_HashCode), SQLITE_TRANSIENT);
867 if ((type != 0) && (ret == SQLITE_OK))
868 ret = sqlite3_bind_int (stmt, sqoff++, type);
869 if (ret == SQLITE_OK)
870 ret = sqlite3_bind_int64 (stmt, sqoff++, limit_off);
871 if (ret != SQLITE_OK)
873 LOG_SQLITE (plugin, NULL,
874 GNUNET_ERROR_TYPE_ERROR |
875 GNUNET_ERROR_TYPE_BULK, "sqlite_bind");
876 proc (proc_cls, NULL, 0, NULL, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0);
879 execute_get (plugin, stmt, proc, proc_cls);
880 sqlite3_finalize (stmt);
886 * Context for 'repl_proc' function.
892 * Function to call for the result (or the NULL).
894 PluginDatumProcessor proc;
907 * Yes if UID was set.
914 * Wrapper for the processor for 'sqlite_plugin_replication_get'.
915 * Decrements the replication counter and calls the original
919 * @param key key for the content
920 * @param size number of bytes in data
921 * @param data content stored
922 * @param type type of the content
923 * @param priority priority of the content
924 * @param anonymity anonymity-level for the content
925 * @param expiration expiration time for the content
926 * @param uid unique identifier for the datum;
927 * maybe 0 if no unique identifier is available
929 * @return GNUNET_OK for normal return,
930 * GNUNET_NO to delete the item
933 repl_proc (void *cls,
934 const GNUNET_HashCode *key,
937 enum GNUNET_BLOCK_Type type,
940 struct GNUNET_TIME_Absolute expiration,
943 struct ReplCtx *rc = cls;
946 ret = rc->proc (rc->proc_cls,
949 type, priority, anonymity, expiration,
954 rc->have_uid = GNUNET_YES;
961 * Get a random item for replication. Returns a single random item
962 * from those with the highest replication counters. The item's
963 * replication counter is decremented by one IF it was positive before.
964 * Call 'proc' with all values ZERO or NULL if the datastore is empty.
967 * @param proc function to call the value (once only).
968 * @param proc_cls closure for proc
971 sqlite_plugin_get_replication (void *cls,
972 PluginDatumProcessor proc, void *proc_cls)
974 struct Plugin *plugin = cls;
978 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
980 "Getting random block based on replication order.\n");
982 rc.have_uid = GNUNET_NO;
984 rc.proc_cls = proc_cls;
985 execute_get (plugin, plugin->selRepl, &repl_proc, &rc);
986 if (GNUNET_YES == rc.have_uid)
988 sqlite3_bind_int64 (plugin->updRepl, 1, rc.uid);
989 if (SQLITE_DONE != sqlite3_step (plugin->updRepl))
990 LOG_SQLITE (plugin, NULL,
991 GNUNET_ERROR_TYPE_ERROR |
992 GNUNET_ERROR_TYPE_BULK, "sqlite3_step");
993 if (SQLITE_OK != sqlite3_reset (plugin->updRepl))
994 LOG_SQLITE (plugin, NULL,
995 GNUNET_ERROR_TYPE_ERROR |
996 GNUNET_ERROR_TYPE_BULK, "sqlite3_reset");
1003 * Get a random item that has expired or has low priority.
1004 * Call 'proc' with all values ZERO or NULL if the datastore is empty.
1006 * @param cls closure
1007 * @param proc function to call the value (once only).
1008 * @param proc_cls closure for proc
1011 sqlite_plugin_get_expiration (void *cls,
1012 PluginDatumProcessor proc, void *proc_cls)
1014 struct Plugin *plugin = cls;
1016 struct GNUNET_TIME_Absolute now;
1019 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1021 "Getting random block based on expiration and priority order.\n");
1023 now = GNUNET_TIME_absolute_get ();
1024 stmt = plugin->selExpi;
1025 if (SQLITE_OK != sqlite3_bind_int64 (stmt, 1, now.abs_value))
1027 LOG_SQLITE (plugin, NULL,
1028 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, "sqlite3_bind_XXXX");
1029 if (SQLITE_OK != sqlite3_reset (stmt))
1030 LOG_SQLITE (plugin, NULL,
1031 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, "sqlite3_reset");
1032 proc (proc_cls, NULL, 0, NULL, 0, 0, 0,
1033 GNUNET_TIME_UNIT_ZERO_ABS, 0);
1036 execute_get (plugin, stmt, proc, proc_cls);
1043 * @param cls our plugin context
1046 sqlite_plugin_drop (void *cls)
1048 struct Plugin *plugin = cls;
1049 plugin->drop_on_shutdown = GNUNET_YES;
1054 * Get an estimate of how much space the database is
1057 * @param cls the 'struct Plugin'
1058 * @return the size of the database on disk (estimate)
1060 static unsigned long long
1061 sqlite_plugin_estimate_size (void *cls)
1063 struct Plugin *plugin = cls;
1071 if (SQLITE_VERSION_NUMBER < 3006000)
1073 GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING,
1075 _("sqlite version to old to determine size, assuming zero\n"));
1079 sqlite3_exec (plugin->dbh,
1080 "VACUUM", NULL, NULL, ENULL));
1082 sqlite3_exec (plugin->dbh,
1083 "PRAGMA auto_vacuum=INCREMENTAL", NULL, NULL, ENULL));
1085 sq_prepare (plugin->dbh,
1086 "PRAGMA page_count",
1089 sqlite3_step (stmt))
1090 pages = sqlite3_column_int64 (stmt, 0);
1093 sqlite3_finalize (stmt);
1095 sq_prepare (plugin->dbh,
1098 CHECK (SQLITE_ROW ==
1099 sqlite3_step (stmt));
1100 page_size = sqlite3_column_int64 (stmt, 0);
1101 sqlite3_finalize (stmt);
1102 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1103 _("Using sqlite page utilization to estimate payload (%llu pages of size %llu bytes)\n"),
1104 (unsigned long long) pages,
1105 (unsigned long long) page_size);
1106 return pages * page_size;
1111 * Entry point for the plugin.
1113 * @param cls the "struct GNUNET_DATASTORE_PluginEnvironment*"
1114 * @return NULL on error, othrewise the plugin context
1117 libgnunet_plugin_datastore_sqlite_init (void *cls)
1119 static struct Plugin plugin;
1120 struct GNUNET_DATASTORE_PluginEnvironment *env = cls;
1121 struct GNUNET_DATASTORE_PluginFunctions *api;
1123 if (plugin.env != NULL)
1124 return NULL; /* can only initialize once! */
1125 memset (&plugin, 0, sizeof(struct Plugin));
1128 database_setup (env->cfg, &plugin))
1130 database_shutdown (&plugin);
1133 api = GNUNET_malloc (sizeof (struct GNUNET_DATASTORE_PluginFunctions));
1135 api->estimate_size = &sqlite_plugin_estimate_size;
1136 api->put = &sqlite_plugin_put;
1137 api->update = &sqlite_plugin_update;
1138 api->get_key = &sqlite_plugin_get_key;
1139 api->get_replication = &sqlite_plugin_get_replication;
1140 api->get_expiration = &sqlite_plugin_get_expiration;
1141 api->get_zero_anonymity = &sqlite_plugin_get_zero_anonymity;
1142 api->drop = &sqlite_plugin_drop;
1143 GNUNET_log_from (GNUNET_ERROR_TYPE_INFO,
1144 "sqlite", _("Sqlite database running\n"));
1150 * Exit point from the plugin.
1152 * @param cls the plugin context (as returned by "init")
1153 * @return always NULL
1156 libgnunet_plugin_datastore_sqlite_done (void *cls)
1159 struct GNUNET_DATASTORE_PluginFunctions *api = cls;
1160 struct Plugin *plugin = api->cls;
1163 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1165 "sqlite plugin is done\n");
1169 if (plugin->drop_on_shutdown)
1170 fn = GNUNET_strdup (plugin->fn);
1172 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1174 "Shutting down database\n");
1176 database_shutdown (plugin);
1181 if (0 != UNLINK(fn))
1182 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING,
1188 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1190 "sqlite plugin is finished\n");
1195 /* end of plugin_datastore_sqlite.c */