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)
422 sqlite3_bind_int64 (plugin->delRow, 1, rid))
424 LOG_SQLITE (plugin, NULL,
425 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, "sqlite3_bind_XXXX");
426 if (SQLITE_OK != sqlite3_reset (plugin->delRow))
427 LOG_SQLITE (plugin, NULL,
428 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, "sqlite3_reset");
429 return GNUNET_SYSERR;
431 if (SQLITE_DONE != sqlite3_step (plugin->delRow))
433 LOG_SQLITE (plugin, NULL,
434 GNUNET_ERROR_TYPE_ERROR |
435 GNUNET_ERROR_TYPE_BULK, "sqlite3_step");
436 if (SQLITE_OK != sqlite3_reset (plugin->delRow))
437 LOG_SQLITE (plugin, NULL,
438 GNUNET_ERROR_TYPE_ERROR |
439 GNUNET_ERROR_TYPE_BULK, "sqlite3_reset");
440 return GNUNET_SYSERR;
442 if (SQLITE_OK != sqlite3_reset (plugin->delRow))
443 LOG_SQLITE (plugin, NULL,
444 GNUNET_ERROR_TYPE_ERROR |
445 GNUNET_ERROR_TYPE_BULK, "sqlite3_reset");
451 * Store an item in the datastore.
454 * @param key key for the item
455 * @param size number of bytes in data
456 * @param data content stored
457 * @param type type of the content
458 * @param priority priority of the content
459 * @param anonymity anonymity-level for the content
460 * @param replication replication-level for the content
461 * @param expiration expiration time for the content
462 * @param msg set to an error message
463 * @return GNUNET_OK on success
466 sqlite_plugin_put (void *cls,
467 const GNUNET_HashCode *key,
470 enum GNUNET_BLOCK_Type type,
473 uint32_t replication,
474 struct GNUNET_TIME_Absolute expiration,
477 struct Plugin *plugin = cls;
481 GNUNET_HashCode vhash;
484 if (size > MAX_ITEM_SIZE)
485 return GNUNET_SYSERR;
487 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
489 "Storing in database block with type %u/key `%s'/priority %u/expiration in %llu ms (%lld).\n",
493 (unsigned long long) GNUNET_TIME_absolute_get_remaining (expiration).rel_value,
494 (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 (GNUNET_HashCode),
507 SQLITE_TRANSIENT)) ||
509 sqlite3_bind_blob (stmt, 8, &vhash, sizeof (GNUNET_HashCode),
512 sqlite3_bind_blob (stmt, 9, data, size,
517 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, "sqlite3_bind_XXXX");
518 if (SQLITE_OK != sqlite3_reset (stmt))
519 LOG_SQLITE (plugin, NULL,
520 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, "sqlite3_reset");
521 return GNUNET_SYSERR;
523 n = sqlite3_step (stmt);
527 plugin->env->duc (plugin->env->cls,
528 size + GNUNET_DATASTORE_ENTRY_OVERHEAD);
530 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
532 "Stored new entry (%u bytes)\n",
533 size + GNUNET_DATASTORE_ENTRY_OVERHEAD);
539 LOG_SQLITE (plugin, msg,
540 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
545 LOG_SQLITE (plugin, msg,
546 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
548 if (SQLITE_OK != sqlite3_reset (stmt))
549 LOG_SQLITE (plugin, NULL,
550 GNUNET_ERROR_TYPE_ERROR |
551 GNUNET_ERROR_TYPE_BULK, "sqlite3_reset");
552 database_shutdown (plugin);
553 database_setup (plugin->env->cfg,
555 return GNUNET_SYSERR;
557 if (SQLITE_OK != sqlite3_reset (stmt))
558 LOG_SQLITE (plugin, NULL,
559 GNUNET_ERROR_TYPE_ERROR |
560 GNUNET_ERROR_TYPE_BULK, "sqlite3_reset");
566 * Update the priority for a particular key in the datastore. If
567 * the expiration time in value is different than the time found in
568 * the datastore, the higher value should be kept. For the
569 * anonymity level, the lower value is to be used. The specified
570 * priority should be added to the existing priority, ignoring the
573 * Note that it is possible for multiple values to match this put.
574 * In that case, all of the respective values are updated.
576 * @param cls the plugin context (state for this module)
577 * @param uid unique identifier of the datum
578 * @param delta by how much should the priority
579 * change? If priority + delta < 0 the
580 * priority should be set to 0 (never go
582 * @param expire new expiration time should be the
583 * MAX of any existing expiration time and
585 * @param msg set to an error message
586 * @return GNUNET_OK on success
589 sqlite_plugin_update (void *cls,
591 int delta, struct GNUNET_TIME_Absolute expire,
594 struct Plugin *plugin = cls;
598 sqlite3_bind_int (plugin->updPrio, 1, delta)) ||
600 sqlite3_bind_int64 (plugin->updPrio, 2, expire.abs_value)) ||
602 sqlite3_bind_int64 (plugin->updPrio, 3, uid)) )
604 LOG_SQLITE (plugin, msg,
605 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, "sqlite3_bind_XXXX");
606 if (SQLITE_OK != sqlite3_reset (plugin->updPrio))
607 LOG_SQLITE (plugin, NULL,
608 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, "sqlite3_reset");
609 return GNUNET_SYSERR;
612 n = sqlite3_step (plugin->updPrio);
613 if (SQLITE_OK != sqlite3_reset (plugin->updPrio))
614 LOG_SQLITE (plugin, NULL,
615 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, "sqlite3_reset");
620 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
626 LOG_SQLITE (plugin, msg,
627 GNUNET_ERROR_TYPE_WARNING | GNUNET_ERROR_TYPE_BULK,
631 LOG_SQLITE (plugin, msg,
632 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
634 return GNUNET_SYSERR;
640 * Execute statement that gets a row and call the callback
641 * with the result. Resets the statement afterwards.
643 * @param plugin the plugin
644 * @param stmt the statement
645 * @param proc processor to call
646 * @param proc_cls closure for 'proc'
649 execute_get (struct Plugin *plugin,
651 PluginDatumProcessor proc, void *proc_cls)
654 struct GNUNET_TIME_Absolute expiration;
655 unsigned long long rowid;
659 n = sqlite3_step (stmt);
663 size = sqlite3_column_bytes (stmt, 5);
664 rowid = sqlite3_column_int64 (stmt, 6);
665 if (sqlite3_column_bytes (stmt, 4) != sizeof (GNUNET_HashCode))
667 GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING,
669 _("Invalid data in database. Trying to fix (by deletion).\n"));
670 if (SQLITE_OK != sqlite3_reset (stmt))
671 LOG_SQLITE (plugin, NULL,
672 GNUNET_ERROR_TYPE_ERROR |
673 GNUNET_ERROR_TYPE_BULK, "sqlite3_reset");
674 if (GNUNET_OK == delete_by_rowid (plugin, rowid))
675 plugin->env->duc (plugin->env->cls,
676 - (size + GNUNET_DATASTORE_ENTRY_OVERHEAD));
679 expiration.abs_value = sqlite3_column_int64 (stmt, 3);
681 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
683 "Found reply in database with expiration %llu\n",
684 (unsigned long long) expiration.abs_value);
686 ret = proc (proc_cls,
687 sqlite3_column_blob (stmt, 4) /* key */,
689 sqlite3_column_blob (stmt, 5) /* data */,
690 sqlite3_column_int (stmt, 0) /* type */,
691 sqlite3_column_int (stmt, 1) /* priority */,
692 sqlite3_column_int (stmt, 2) /* anonymity */,
695 if (SQLITE_OK != sqlite3_reset (stmt))
696 LOG_SQLITE (plugin, NULL,
697 GNUNET_ERROR_TYPE_ERROR |
698 GNUNET_ERROR_TYPE_BULK, "sqlite3_reset");
699 if ( (GNUNET_NO == ret) &&
700 (GNUNET_OK == delete_by_rowid (plugin, rowid)) )
701 plugin->env->duc (plugin->env->cls,
702 - (size + GNUNET_DATASTORE_ENTRY_OVERHEAD));
705 /* database must be empty */
706 if (SQLITE_OK != sqlite3_reset (stmt))
707 LOG_SQLITE (plugin, NULL,
708 GNUNET_ERROR_TYPE_ERROR |
709 GNUNET_ERROR_TYPE_BULK, "sqlite3_reset");
715 LOG_SQLITE (plugin, NULL,
716 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
718 if (SQLITE_OK != sqlite3_reset (stmt))
719 LOG_SQLITE (plugin, NULL,
720 GNUNET_ERROR_TYPE_ERROR |
721 GNUNET_ERROR_TYPE_BULK,
724 database_shutdown (plugin);
725 database_setup (plugin->env->cfg,
729 if (SQLITE_OK != sqlite3_reset (stmt))
730 LOG_SQLITE (plugin, NULL,
731 GNUNET_ERROR_TYPE_ERROR |
732 GNUNET_ERROR_TYPE_BULK, "sqlite3_reset");
733 proc (proc_cls, NULL, 0, NULL, 0, 0, 0,
734 GNUNET_TIME_UNIT_ZERO_ABS, 0);
740 * Select a subset of the items in the datastore and call
741 * the given processor for the item.
743 * @param cls our plugin context
744 * @param offset offset of the result (modulo num-results);
745 * specific ordering does not matter for the offset
746 * @param type entries of which type should be considered?
747 * Use 0 for any type.
748 * @param proc function to call on each matching value;
749 * will be called once with a NULL value at the end
750 * @param proc_cls closure for proc
753 sqlite_plugin_get_zero_anonymity (void *cls,
755 enum GNUNET_BLOCK_Type type,
756 PluginDatumProcessor proc,
759 struct Plugin *plugin = cls;
762 GNUNET_assert (type != GNUNET_BLOCK_TYPE_ANY);
763 stmt = plugin->selZeroAnon;
764 if ( (SQLITE_OK != sqlite3_bind_int (stmt, 1, type)) ||
765 (SQLITE_OK != sqlite3_bind_int64 (stmt, 2, offset)) )
767 LOG_SQLITE (plugin, NULL,
768 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
769 "sqlite3_bind_XXXX");
770 if (SQLITE_OK != sqlite3_reset (stmt))
771 LOG_SQLITE (plugin, NULL,
772 GNUNET_ERROR_TYPE_ERROR |
773 GNUNET_ERROR_TYPE_BULK,
775 proc (proc_cls, NULL, 0, NULL, 0, 0, 0,
776 GNUNET_TIME_UNIT_ZERO_ABS, 0);
779 execute_get (plugin, stmt, proc, proc_cls);
785 * Get results for a particular key in the datastore.
788 * @param offset offset (mod count).
789 * @param key key to match, never NULL
790 * @param vhash hash of the value, maybe NULL (to
791 * match all values that have the right key).
792 * Note that for DBlocks there is no difference
793 * betwen key and vhash, but for other blocks
795 * @param type entries of which type are relevant?
796 * Use 0 for any type.
797 * @param proc function to call on each matching value;
798 * will be called once with a NULL value at the end
799 * @param proc_cls closure for proc
802 sqlite_plugin_get_key (void *cls,
804 const GNUNET_HashCode *key,
805 const GNUNET_HashCode *vhash,
806 enum GNUNET_BLOCK_Type type,
807 PluginDatumProcessor proc, void *proc_cls)
809 struct Plugin *plugin = cls;
817 GNUNET_assert (proc != NULL);
818 GNUNET_assert (key != NULL);
819 GNUNET_snprintf (scratch, sizeof (scratch),
820 "SELECT count(*) FROM gn090 WHERE hash=?%s%s",
821 vhash == NULL ? "" : " AND vhash=?",
822 type == 0 ? "" : " AND type=?");
823 if (sq_prepare (plugin->dbh, scratch, &stmt) != SQLITE_OK)
825 LOG_SQLITE (plugin, NULL,
826 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, "sqlite_prepare");
827 proc (proc_cls, NULL, 0, NULL, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0);
831 ret = sqlite3_bind_blob (stmt, sqoff++,
832 key, sizeof (GNUNET_HashCode), SQLITE_TRANSIENT);
833 if ((vhash != NULL) && (ret == SQLITE_OK))
834 ret = sqlite3_bind_blob (stmt, sqoff++,
836 sizeof (GNUNET_HashCode), SQLITE_TRANSIENT);
837 if ((type != 0) && (ret == SQLITE_OK))
838 ret = sqlite3_bind_int (stmt, sqoff++, type);
839 if (SQLITE_OK != ret)
841 LOG_SQLITE (plugin, NULL,
842 GNUNET_ERROR_TYPE_ERROR, "sqlite_bind");
843 sqlite3_finalize (stmt);
844 proc (proc_cls, NULL, 0, NULL, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0);
847 ret = sqlite3_step (stmt);
848 if (ret != SQLITE_ROW)
850 LOG_SQLITE (plugin, NULL,
851 GNUNET_ERROR_TYPE_ERROR| GNUNET_ERROR_TYPE_BULK,
853 sqlite3_finalize (stmt);
854 proc (proc_cls, NULL, 0, NULL, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0);
857 total = sqlite3_column_int (stmt, 0);
858 sqlite3_finalize (stmt);
861 proc (proc_cls, NULL, 0, NULL, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0);
864 limit_off = (int) (offset % total);
867 GNUNET_snprintf (scratch, sizeof (scratch),
868 "SELECT type, prio, anonLevel, expire, hash, value, _ROWID_ "
869 "FROM gn090 WHERE hash=?%s%s "
870 "ORDER BY _ROWID_ ASC LIMIT 1 OFFSET ?",
871 vhash == NULL ? "" : " AND vhash=?",
872 type == 0 ? "" : " AND type=?");
873 if (sq_prepare (plugin->dbh, scratch, &stmt) != SQLITE_OK)
875 LOG_SQLITE (plugin, NULL,
876 GNUNET_ERROR_TYPE_ERROR |
877 GNUNET_ERROR_TYPE_BULK, "sqlite_prepare");
878 proc (proc_cls, NULL, 0, NULL, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0);
882 ret = sqlite3_bind_blob (stmt,
885 sizeof (GNUNET_HashCode),
887 if ((vhash != NULL) && (ret == SQLITE_OK))
888 ret = sqlite3_bind_blob (stmt,
891 sizeof (GNUNET_HashCode), SQLITE_TRANSIENT);
892 if ((type != 0) && (ret == SQLITE_OK))
893 ret = sqlite3_bind_int (stmt, sqoff++, type);
894 if (ret == SQLITE_OK)
895 ret = sqlite3_bind_int64 (stmt, sqoff++, limit_off);
896 if (ret != SQLITE_OK)
898 LOG_SQLITE (plugin, NULL,
899 GNUNET_ERROR_TYPE_ERROR |
900 GNUNET_ERROR_TYPE_BULK, "sqlite_bind");
901 proc (proc_cls, NULL, 0, NULL, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0);
904 execute_get (plugin, stmt, proc, proc_cls);
905 sqlite3_finalize (stmt);
911 * Context for 'repl_proc' function.
917 * Function to call for the result (or the NULL).
919 PluginDatumProcessor proc;
932 * Yes if UID was set.
939 * Wrapper for the processor for 'sqlite_plugin_replication_get'.
940 * Decrements the replication counter and calls the original
944 * @param key key for the content
945 * @param size number of bytes in data
946 * @param data content stored
947 * @param type type of the content
948 * @param priority priority of the content
949 * @param anonymity anonymity-level for the content
950 * @param expiration expiration time for the content
951 * @param uid unique identifier for the datum;
952 * maybe 0 if no unique identifier is available
954 * @return GNUNET_OK for normal return,
955 * GNUNET_NO to delete the item
958 repl_proc (void *cls,
959 const GNUNET_HashCode *key,
962 enum GNUNET_BLOCK_Type type,
965 struct GNUNET_TIME_Absolute expiration,
968 struct ReplCtx *rc = cls;
971 ret = rc->proc (rc->proc_cls,
974 type, priority, anonymity, expiration,
979 rc->have_uid = GNUNET_YES;
986 * Get a random item for replication. Returns a single random item
987 * from those with the highest replication counters. The item's
988 * replication counter is decremented by one IF it was positive before.
989 * Call 'proc' with all values ZERO or NULL if the datastore is empty.
992 * @param proc function to call the value (once only).
993 * @param proc_cls closure for proc
996 sqlite_plugin_get_replication (void *cls,
997 PluginDatumProcessor proc, void *proc_cls)
999 struct Plugin *plugin = cls;
1003 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1005 "Getting random block based on replication order.\n");
1007 rc.have_uid = GNUNET_NO;
1009 rc.proc_cls = proc_cls;
1010 execute_get (plugin, plugin->selRepl, &repl_proc, &rc);
1011 if (GNUNET_YES == rc.have_uid)
1014 sqlite3_bind_int64 (plugin->updRepl, 1, rc.uid))
1016 LOG_SQLITE (plugin, NULL,
1017 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, "sqlite3_bind_XXXX");
1018 if (SQLITE_OK != sqlite3_reset (plugin->updRepl))
1019 LOG_SQLITE (plugin, NULL,
1020 GNUNET_ERROR_TYPE_ERROR |
1021 GNUNET_ERROR_TYPE_BULK, "sqlite3_reset");
1024 if (SQLITE_DONE != sqlite3_step (plugin->updRepl))
1025 LOG_SQLITE (plugin, NULL,
1026 GNUNET_ERROR_TYPE_ERROR |
1027 GNUNET_ERROR_TYPE_BULK, "sqlite3_step");
1028 if (SQLITE_OK != sqlite3_reset (plugin->updRepl))
1029 LOG_SQLITE (plugin, NULL,
1030 GNUNET_ERROR_TYPE_ERROR |
1031 GNUNET_ERROR_TYPE_BULK, "sqlite3_reset");
1038 * Get a random item that has expired or has low priority.
1039 * Call 'proc' with all values ZERO or NULL if the datastore is empty.
1041 * @param cls closure
1042 * @param proc function to call the value (once only).
1043 * @param proc_cls closure for proc
1046 sqlite_plugin_get_expiration (void *cls,
1047 PluginDatumProcessor proc, void *proc_cls)
1049 struct Plugin *plugin = cls;
1051 struct GNUNET_TIME_Absolute now;
1054 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1056 "Getting random block based on expiration and priority order.\n");
1058 now = GNUNET_TIME_absolute_get ();
1059 stmt = plugin->selExpi;
1060 if (SQLITE_OK != sqlite3_bind_int64 (stmt, 1, now.abs_value))
1062 LOG_SQLITE (plugin, NULL,
1063 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, "sqlite3_bind_XXXX");
1064 if (SQLITE_OK != sqlite3_reset (stmt))
1065 LOG_SQLITE (plugin, NULL,
1066 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, "sqlite3_reset");
1067 proc (proc_cls, NULL, 0, NULL, 0, 0, 0,
1068 GNUNET_TIME_UNIT_ZERO_ABS, 0);
1071 execute_get (plugin, stmt, proc, proc_cls);
1078 * @param cls our plugin context
1081 sqlite_plugin_drop (void *cls)
1083 struct Plugin *plugin = cls;
1084 plugin->drop_on_shutdown = GNUNET_YES;
1089 * Get an estimate of how much space the database is
1092 * @param cls the 'struct Plugin'
1093 * @return the size of the database on disk (estimate)
1095 static unsigned long long
1096 sqlite_plugin_estimate_size (void *cls)
1098 struct Plugin *plugin = cls;
1106 if (SQLITE_VERSION_NUMBER < 3006000)
1108 GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING,
1110 _("sqlite version to old to determine size, assuming zero\n"));
1114 sqlite3_exec (plugin->dbh,
1115 "VACUUM", NULL, NULL, ENULL));
1117 sqlite3_exec (plugin->dbh,
1118 "PRAGMA auto_vacuum=INCREMENTAL", NULL, NULL, ENULL));
1120 sq_prepare (plugin->dbh,
1121 "PRAGMA page_count",
1124 sqlite3_step (stmt))
1125 pages = sqlite3_column_int64 (stmt, 0);
1128 sqlite3_finalize (stmt);
1130 sq_prepare (plugin->dbh,
1133 CHECK (SQLITE_ROW ==
1134 sqlite3_step (stmt));
1135 page_size = sqlite3_column_int64 (stmt, 0);
1136 sqlite3_finalize (stmt);
1137 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1138 _("Using sqlite page utilization to estimate payload (%llu pages of size %llu bytes)\n"),
1139 (unsigned long long) pages,
1140 (unsigned long long) page_size);
1141 return pages * page_size;
1146 * Entry point for the plugin.
1148 * @param cls the "struct GNUNET_DATASTORE_PluginEnvironment*"
1149 * @return NULL on error, othrewise the plugin context
1152 libgnunet_plugin_datastore_sqlite_init (void *cls)
1154 static struct Plugin plugin;
1155 struct GNUNET_DATASTORE_PluginEnvironment *env = cls;
1156 struct GNUNET_DATASTORE_PluginFunctions *api;
1158 if (plugin.env != NULL)
1159 return NULL; /* can only initialize once! */
1160 memset (&plugin, 0, sizeof(struct Plugin));
1163 database_setup (env->cfg, &plugin))
1165 database_shutdown (&plugin);
1168 api = GNUNET_malloc (sizeof (struct GNUNET_DATASTORE_PluginFunctions));
1170 api->estimate_size = &sqlite_plugin_estimate_size;
1171 api->put = &sqlite_plugin_put;
1172 api->update = &sqlite_plugin_update;
1173 api->get_key = &sqlite_plugin_get_key;
1174 api->get_replication = &sqlite_plugin_get_replication;
1175 api->get_expiration = &sqlite_plugin_get_expiration;
1176 api->get_zero_anonymity = &sqlite_plugin_get_zero_anonymity;
1177 api->drop = &sqlite_plugin_drop;
1178 GNUNET_log_from (GNUNET_ERROR_TYPE_INFO,
1179 "sqlite", _("Sqlite database running\n"));
1185 * Exit point from the plugin.
1187 * @param cls the plugin context (as returned by "init")
1188 * @return always NULL
1191 libgnunet_plugin_datastore_sqlite_done (void *cls)
1194 struct GNUNET_DATASTORE_PluginFunctions *api = cls;
1195 struct Plugin *plugin = api->cls;
1198 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1200 "sqlite plugin is done\n");
1204 if (plugin->drop_on_shutdown)
1205 fn = GNUNET_strdup (plugin->fn);
1207 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1209 "Shutting down database\n");
1211 database_shutdown (plugin);
1216 if (0 != UNLINK(fn))
1217 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING,
1223 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1225 "sqlite plugin is finished\n");
1230 /* end of plugin_datastore_sqlite.c */