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, const char *zSql, sqlite3_stmt ** ppStmt)
147 result = sqlite3_prepare_v2 (dbh,
149 strlen (zSql), ppStmt, (const char **) &dummy);
150 #if DEBUG_SQLITE && 0
151 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
152 "sqlite", "Prepared `%s' / %p: %d\n", zSql, *ppStmt, result);
159 * Create our database indices.
161 * @param dbh handle to the database
164 create_indices (sqlite3 * dbh)
169 "CREATE INDEX IF NOT EXISTS idx_hash ON gn090 (hash)",
170 NULL, NULL, NULL)) ||
173 "CREATE INDEX IF NOT EXISTS idx_hash_vhash ON gn090 (hash,vhash)",
174 NULL, NULL, NULL)) ||
177 "CREATE INDEX IF NOT EXISTS idx_expire_repl ON gn090 (expire ASC,repl DESC)",
178 NULL, NULL, NULL)) ||
181 "CREATE INDEX IF NOT EXISTS idx_comb ON gn090 (anonLevel ASC,expire ASC,prio,type,hash)",
182 NULL, NULL, NULL)) ||
185 "CREATE INDEX IF NOT EXISTS idx_anon_type_hash ON gn090 (anonLevel ASC,type,hash)",
186 NULL, NULL, NULL)) ||
189 "CREATE INDEX IF NOT EXISTS idx_expire ON gn090 (expire ASC)",
190 NULL, NULL, NULL)) ||
193 "CREATE INDEX IF NOT EXISTS idx_repl_rvalue ON gn090 (repl,rvalue)",
194 NULL, NULL, NULL)) ||
197 "CREATE INDEX IF NOT EXISTS idx_repl ON gn090 (repl DESC)",
199 GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, "sqlite",
200 "Failed to create indices: %s\n", sqlite3_errmsg (dbh));
205 #define CHECK(a) GNUNET_break(a)
209 #define ENULL_DEFINED 1
210 #define CHECK(a) if (! a) { GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "%s\n", e); sqlite3_free(e); }
215 * Initialize the database connections and associated
216 * data structures (create tables and indices
217 * as needed as well).
219 * @param cfg our configuration
220 * @param plugin the plugin context (state for this module)
221 * @return GNUNET_OK on success
224 database_setup (const struct GNUNET_CONFIGURATION_Handle *cfg,
225 struct Plugin *plugin)
235 GNUNET_CONFIGURATION_get_value_filename (cfg,
237 "FILENAME", &afsdir))
239 GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR,
242 ("Option `%s' in section `%s' missing in configuration!\n"),
243 "FILENAME", "datastore-sqlite");
244 return GNUNET_SYSERR;
246 if (GNUNET_OK != GNUNET_DISK_file_test (afsdir))
248 if (GNUNET_OK != GNUNET_DISK_directory_create_for_file (afsdir))
251 GNUNET_free (afsdir);
252 return GNUNET_SYSERR;
254 /* database is new or got deleted, reset payload to zero! */
255 plugin->env->duc (plugin->env->cls, 0);
258 plugin->fn = GNUNET_STRINGS_to_utf8 (afsdir, strlen (afsdir),
259 nl_langinfo (CODESET));
261 plugin->fn = GNUNET_STRINGS_to_utf8 (afsdir, strlen (afsdir), "UTF-8"); /* good luck */
263 GNUNET_free (afsdir);
265 /* Open database and precompile statements */
266 if (sqlite3_open (plugin->fn, &plugin->dbh) != SQLITE_OK)
268 GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR,
270 _("Unable to initialize SQLite: %s.\n"),
271 sqlite3_errmsg (plugin->dbh));
272 return GNUNET_SYSERR;
275 sqlite3_exec (plugin->dbh,
276 "PRAGMA temp_store=MEMORY", NULL, NULL, ENULL));
278 sqlite3_exec (plugin->dbh,
279 "PRAGMA synchronous=OFF", NULL, NULL, ENULL));
281 sqlite3_exec (plugin->dbh,
282 "PRAGMA legacy_file_format=OFF", NULL, NULL, ENULL));
284 sqlite3_exec (plugin->dbh,
285 "PRAGMA auto_vacuum=INCREMENTAL", NULL, NULL, ENULL));
287 sqlite3_exec (plugin->dbh,
288 "PRAGMA locking_mode=EXCLUSIVE", NULL, NULL, ENULL));
290 sqlite3_exec (plugin->dbh,
291 "PRAGMA count_changes=OFF", NULL, NULL, ENULL));
293 sqlite3_exec (plugin->dbh,
294 "PRAGMA page_size=4092", NULL, NULL, ENULL));
296 CHECK (SQLITE_OK == sqlite3_busy_timeout (plugin->dbh, BUSY_TIMEOUT_MS));
299 /* We have to do it here, because otherwise precompiling SQL might fail */
301 sq_prepare (plugin->dbh,
302 "SELECT 1 FROM sqlite_master WHERE tbl_name = 'gn090'",
304 if ((sqlite3_step (stmt) == SQLITE_DONE) &&
305 (sqlite3_exec (plugin->dbh,
306 "CREATE TABLE gn090 ("
307 " repl INT4 NOT NULL DEFAULT 0,"
308 " type INT4 NOT NULL DEFAULT 0,"
309 " prio INT4 NOT NULL DEFAULT 0,"
310 " anonLevel INT4 NOT NULL DEFAULT 0,"
311 " expire INT8 NOT NULL DEFAULT 0,"
312 " rvalue INT8 NOT NULL,"
313 " hash TEXT NOT NULL DEFAULT '',"
314 " vhash TEXT NOT NULL DEFAULT '',"
315 " value BLOB NOT NULL DEFAULT '')", NULL, NULL,
318 LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR, "sqlite3_exec");
319 sqlite3_finalize (stmt);
320 return GNUNET_SYSERR;
322 sqlite3_finalize (stmt);
323 create_indices (plugin->dbh);
325 if ((sq_prepare (plugin->dbh,
327 "SET prio = prio + ?, expire = MAX(expire,?) WHERE _ROWID_ = ?",
328 &plugin->updPrio) != SQLITE_OK) ||
329 (sq_prepare (plugin->dbh,
331 "SET repl = MAX (0, repl - 1) WHERE _ROWID_ = ?",
332 &plugin->updRepl) != SQLITE_OK) ||
333 (sq_prepare (plugin->dbh,
334 "SELECT type,prio,anonLevel,expire,hash,value,_ROWID_ "
335 "FROM gn090 INDEXED BY idx_repl_rvalue "
338 " NOT EXISTS (SELECT 1 FROM gn090 INDEXED BY idx_repl_rvalue WHERE repl=?2 AND rvalue>=?1 LIMIT 1))"
339 " ORDER BY rvalue ASC"
341 &plugin->selRepl) != SQLITE_OK) ||
342 (sq_prepare (plugin->dbh,
344 "FROM gn090 INDEXED BY idx_repl_rvalue",
345 &plugin->maxRepl) != SQLITE_OK) ||
346 (sq_prepare (plugin->dbh,
347 "SELECT type,prio,anonLevel,expire,hash,value,_ROWID_ "
348 "FROM gn090 INDEXED BY idx_expire"
349 " WHERE NOT EXISTS (SELECT 1 FROM gn090 WHERE expire < ?1 LIMIT 1) OR (expire < ?1) "
350 " ORDER BY expire ASC LIMIT 1",
351 &plugin->selExpi) != SQLITE_OK) ||
352 (sq_prepare (plugin->dbh,
353 "SELECT type,prio,anonLevel,expire,hash,value,_ROWID_ "
354 "FROM gn090 INDEXED BY idx_anon_type_hash "
355 "WHERE (anonLevel = 0 AND type=?1) "
356 "ORDER BY hash DESC LIMIT 1 OFFSET ?2",
357 &plugin->selZeroAnon) != SQLITE_OK) ||
358 (sq_prepare (plugin->dbh,
359 "INSERT INTO gn090 (repl, type, prio, "
360 "anonLevel, expire, rvalue, hash, vhash, value) "
361 "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)",
362 &plugin->insertContent) != SQLITE_OK) ||
363 (sq_prepare (plugin->dbh,
364 "DELETE FROM gn090 WHERE _ROWID_ = ?",
365 &plugin->delRow) != SQLITE_OK))
367 LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR, "precompiling");
368 return GNUNET_SYSERR;
376 * Shutdown database connection and associate data
378 * @param plugin the plugin context (state for this module)
381 database_shutdown (struct Plugin *plugin)
385 #if SQLITE_VERSION_NUMBER >= 3007000
389 if (plugin->delRow != NULL)
390 sqlite3_finalize (plugin->delRow);
391 if (plugin->updPrio != NULL)
392 sqlite3_finalize (plugin->updPrio);
393 if (plugin->updRepl != NULL)
394 sqlite3_finalize (plugin->updRepl);
395 if (plugin->selRepl != NULL)
396 sqlite3_finalize (plugin->selRepl);
397 if (plugin->maxRepl != NULL)
398 sqlite3_finalize (plugin->maxRepl);
399 if (plugin->selExpi != NULL)
400 sqlite3_finalize (plugin->selExpi);
401 if (plugin->selZeroAnon != NULL)
402 sqlite3_finalize (plugin->selZeroAnon);
403 if (plugin->insertContent != NULL)
404 sqlite3_finalize (plugin->insertContent);
405 result = sqlite3_close (plugin->dbh);
406 #if SQLITE_VERSION_NUMBER >= 3007000
407 if (result == SQLITE_BUSY)
409 GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING,
412 ("Tried to close sqlite without finalizing all prepared statements.\n"));
413 stmt = sqlite3_next_stmt (plugin->dbh, NULL);
417 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
418 "sqlite", "Closing statement %p\n", stmt);
420 result = sqlite3_finalize (stmt);
422 if (result != SQLITE_OK)
423 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
425 "Failed to close statement %p: %d\n", stmt, result);
427 stmt = sqlite3_next_stmt (plugin->dbh, NULL);
429 result = sqlite3_close (plugin->dbh);
432 if (SQLITE_OK != result)
433 LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR, "sqlite3_close");
435 GNUNET_free_non_null (plugin->fn);
440 * Delete the database entry with the given
443 * @param plugin the plugin context (state for this module)
444 * @param rid the ID of the row to delete
447 delete_by_rowid (struct Plugin *plugin, unsigned long long rid)
449 if (SQLITE_OK != sqlite3_bind_int64 (plugin->delRow, 1, rid))
451 LOG_SQLITE (plugin, NULL,
452 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
453 "sqlite3_bind_XXXX");
454 if (SQLITE_OK != sqlite3_reset (plugin->delRow))
455 LOG_SQLITE (plugin, NULL,
456 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
458 return GNUNET_SYSERR;
460 if (SQLITE_DONE != sqlite3_step (plugin->delRow))
462 LOG_SQLITE (plugin, NULL,
463 GNUNET_ERROR_TYPE_ERROR |
464 GNUNET_ERROR_TYPE_BULK, "sqlite3_step");
465 if (SQLITE_OK != sqlite3_reset (plugin->delRow))
466 LOG_SQLITE (plugin, NULL,
467 GNUNET_ERROR_TYPE_ERROR |
468 GNUNET_ERROR_TYPE_BULK, "sqlite3_reset");
469 return GNUNET_SYSERR;
471 if (SQLITE_OK != sqlite3_reset (plugin->delRow))
472 LOG_SQLITE (plugin, NULL,
473 GNUNET_ERROR_TYPE_ERROR |
474 GNUNET_ERROR_TYPE_BULK, "sqlite3_reset");
480 * Store an item in the datastore.
483 * @param key key for the item
484 * @param size number of bytes in data
485 * @param data content stored
486 * @param type type of the content
487 * @param priority priority of the content
488 * @param anonymity anonymity-level for the content
489 * @param replication replication-level for the content
490 * @param expiration expiration time for the content
491 * @param msg set to an error message
492 * @return GNUNET_OK on success
495 sqlite_plugin_put (void *cls,
496 const GNUNET_HashCode * key,
499 enum GNUNET_BLOCK_Type type,
502 uint32_t replication,
503 struct GNUNET_TIME_Absolute expiration, char **msg)
505 struct Plugin *plugin = cls;
509 GNUNET_HashCode vhash;
512 if (size > MAX_ITEM_SIZE)
513 return GNUNET_SYSERR;
515 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
517 "Storing in database block with type %u/key `%s'/priority %u/expiration in %llu ms (%lld).\n",
522 GNUNET_TIME_absolute_get_remaining (expiration).rel_value,
523 (long long) expiration.abs_value);
525 GNUNET_CRYPTO_hash (data, size, &vhash);
526 stmt = plugin->insertContent;
527 rvalue = GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK, UINT64_MAX);
528 if ((SQLITE_OK != sqlite3_bind_int (stmt, 1, replication)) ||
529 (SQLITE_OK != sqlite3_bind_int (stmt, 2, type)) ||
530 (SQLITE_OK != sqlite3_bind_int (stmt, 3, priority)) ||
531 (SQLITE_OK != sqlite3_bind_int (stmt, 4, anonymity)) ||
532 (SQLITE_OK != sqlite3_bind_int64 (stmt, 5, expiration.abs_value)) ||
533 (SQLITE_OK != sqlite3_bind_int64 (stmt, 6, rvalue)) ||
535 sqlite3_bind_blob (stmt, 7, key, sizeof (GNUNET_HashCode),
536 SQLITE_TRANSIENT)) ||
538 sqlite3_bind_blob (stmt, 8, &vhash, sizeof (GNUNET_HashCode),
541 sqlite3_bind_blob (stmt, 9, data, size, SQLITE_TRANSIENT)))
545 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
546 "sqlite3_bind_XXXX");
547 if (SQLITE_OK != sqlite3_reset (stmt))
548 LOG_SQLITE (plugin, NULL,
549 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
551 return GNUNET_SYSERR;
553 n = sqlite3_step (stmt);
557 plugin->env->duc (plugin->env->cls, size + GNUNET_DATASTORE_ENTRY_OVERHEAD);
559 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
561 "Stored new entry (%u bytes)\n",
562 size + GNUNET_DATASTORE_ENTRY_OVERHEAD);
568 LOG_SQLITE (plugin, msg,
569 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
574 LOG_SQLITE (plugin, msg,
575 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
577 if (SQLITE_OK != sqlite3_reset (stmt))
578 LOG_SQLITE (plugin, NULL,
579 GNUNET_ERROR_TYPE_ERROR |
580 GNUNET_ERROR_TYPE_BULK, "sqlite3_reset");
581 database_shutdown (plugin);
582 database_setup (plugin->env->cfg, plugin);
583 return GNUNET_SYSERR;
585 if (SQLITE_OK != sqlite3_reset (stmt))
586 LOG_SQLITE (plugin, NULL,
587 GNUNET_ERROR_TYPE_ERROR |
588 GNUNET_ERROR_TYPE_BULK, "sqlite3_reset");
594 * Update the priority for a particular key in the datastore. If
595 * the expiration time in value is different than the time found in
596 * the datastore, the higher value should be kept. For the
597 * anonymity level, the lower value is to be used. The specified
598 * priority should be added to the existing priority, ignoring the
601 * Note that it is possible for multiple values to match this put.
602 * In that case, all of the respective values are updated.
604 * @param cls the plugin context (state for this module)
605 * @param uid unique identifier of the datum
606 * @param delta by how much should the priority
607 * change? If priority + delta < 0 the
608 * priority should be set to 0 (never go
610 * @param expire new expiration time should be the
611 * MAX of any existing expiration time and
613 * @param msg set to an error message
614 * @return GNUNET_OK on success
617 sqlite_plugin_update (void *cls,
619 int delta, struct GNUNET_TIME_Absolute expire, char **msg)
621 struct Plugin *plugin = cls;
625 sqlite3_bind_int (plugin->updPrio, 1, delta)) ||
627 sqlite3_bind_int64 (plugin->updPrio, 2, expire.abs_value)) ||
628 (SQLITE_OK != sqlite3_bind_int64 (plugin->updPrio, 3, uid)))
630 LOG_SQLITE (plugin, msg,
631 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
632 "sqlite3_bind_XXXX");
633 if (SQLITE_OK != sqlite3_reset (plugin->updPrio))
634 LOG_SQLITE (plugin, NULL,
635 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
637 return GNUNET_SYSERR;
640 n = sqlite3_step (plugin->updPrio);
641 if (SQLITE_OK != sqlite3_reset (plugin->updPrio))
642 LOG_SQLITE (plugin, NULL,
643 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
649 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "sqlite", "Block updated\n");
653 LOG_SQLITE (plugin, msg,
654 GNUNET_ERROR_TYPE_WARNING | GNUNET_ERROR_TYPE_BULK,
658 LOG_SQLITE (plugin, msg,
659 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
661 return GNUNET_SYSERR;
667 * Execute statement that gets a row and call the callback
668 * with the result. Resets the statement afterwards.
670 * @param plugin the plugin
671 * @param stmt the statement
672 * @param proc processor to call
673 * @param proc_cls closure for 'proc'
676 execute_get (struct Plugin *plugin,
677 sqlite3_stmt * stmt, PluginDatumProcessor proc, void *proc_cls)
680 struct GNUNET_TIME_Absolute expiration;
681 unsigned long long rowid;
685 n = sqlite3_step (stmt);
689 size = sqlite3_column_bytes (stmt, 5);
690 rowid = sqlite3_column_int64 (stmt, 6);
691 if (sqlite3_column_bytes (stmt, 4) != sizeof (GNUNET_HashCode))
693 GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING,
696 ("Invalid data in database. Trying to fix (by deletion).\n"));
697 if (SQLITE_OK != sqlite3_reset (stmt))
698 LOG_SQLITE (plugin, NULL,
699 GNUNET_ERROR_TYPE_ERROR |
700 GNUNET_ERROR_TYPE_BULK, "sqlite3_reset");
701 if (GNUNET_OK == delete_by_rowid (plugin, rowid))
702 plugin->env->duc (plugin->env->cls,
703 -(size + GNUNET_DATASTORE_ENTRY_OVERHEAD));
706 expiration.abs_value = sqlite3_column_int64 (stmt, 3);
708 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
710 "Found reply in database with expiration %llu\n",
711 (unsigned long long) expiration.abs_value);
713 ret = proc (proc_cls, sqlite3_column_blob (stmt, 4) /* key */ ,
714 size, sqlite3_column_blob (stmt, 5) /* data */ ,
715 sqlite3_column_int (stmt, 0) /* type */ ,
716 sqlite3_column_int (stmt, 1) /* priority */ ,
717 sqlite3_column_int (stmt, 2) /* anonymity */ ,
719 if (SQLITE_OK != sqlite3_reset (stmt))
720 LOG_SQLITE (plugin, NULL,
721 GNUNET_ERROR_TYPE_ERROR |
722 GNUNET_ERROR_TYPE_BULK, "sqlite3_reset");
723 if ((GNUNET_NO == ret) && (GNUNET_OK == delete_by_rowid (plugin, rowid)))
724 plugin->env->duc (plugin->env->cls,
725 -(size + GNUNET_DATASTORE_ENTRY_OVERHEAD));
728 /* database must be empty */
729 if (SQLITE_OK != sqlite3_reset (stmt))
730 LOG_SQLITE (plugin, NULL,
731 GNUNET_ERROR_TYPE_ERROR |
732 GNUNET_ERROR_TYPE_BULK, "sqlite3_reset");
738 LOG_SQLITE (plugin, NULL,
739 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
741 if (SQLITE_OK != sqlite3_reset (stmt))
742 LOG_SQLITE (plugin, NULL,
743 GNUNET_ERROR_TYPE_ERROR |
744 GNUNET_ERROR_TYPE_BULK, "sqlite3_reset");
746 database_shutdown (plugin);
747 database_setup (plugin->env->cfg, plugin);
750 if (SQLITE_OK != sqlite3_reset (stmt))
751 LOG_SQLITE (plugin, NULL,
752 GNUNET_ERROR_TYPE_ERROR |
753 GNUNET_ERROR_TYPE_BULK, "sqlite3_reset");
754 proc (proc_cls, NULL, 0, NULL, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0);
760 * Select a subset of the items in the datastore and call
761 * the given processor for the item.
763 * @param cls our plugin context
764 * @param offset offset of the result (modulo num-results);
765 * specific ordering does not matter for the offset
766 * @param type entries of which type should be considered?
767 * Use 0 for any type.
768 * @param proc function to call on each matching value;
769 * will be called once with a NULL value at the end
770 * @param proc_cls closure for proc
773 sqlite_plugin_get_zero_anonymity (void *cls,
775 enum GNUNET_BLOCK_Type type,
776 PluginDatumProcessor proc, void *proc_cls)
778 struct Plugin *plugin = cls;
781 GNUNET_assert (type != GNUNET_BLOCK_TYPE_ANY);
782 stmt = plugin->selZeroAnon;
783 if ((SQLITE_OK != sqlite3_bind_int (stmt, 1, type)) ||
784 (SQLITE_OK != sqlite3_bind_int64 (stmt, 2, offset)))
786 LOG_SQLITE (plugin, NULL,
787 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
788 "sqlite3_bind_XXXX");
789 if (SQLITE_OK != sqlite3_reset (stmt))
790 LOG_SQLITE (plugin, NULL,
791 GNUNET_ERROR_TYPE_ERROR |
792 GNUNET_ERROR_TYPE_BULK, "sqlite3_reset");
793 proc (proc_cls, NULL, 0, NULL, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0);
796 execute_get (plugin, stmt, proc, proc_cls);
802 * Get results for a particular key in the datastore.
805 * @param offset offset (mod count).
806 * @param key key to match, never NULL
807 * @param vhash hash of the value, maybe NULL (to
808 * match all values that have the right key).
809 * Note that for DBlocks there is no difference
810 * betwen key and vhash, but for other blocks
812 * @param type entries of which type are relevant?
813 * Use 0 for any type.
814 * @param proc function to call on each matching value;
815 * will be called once with a NULL value at the end
816 * @param proc_cls closure for proc
819 sqlite_plugin_get_key (void *cls,
821 const GNUNET_HashCode * key,
822 const GNUNET_HashCode * vhash,
823 enum GNUNET_BLOCK_Type type,
824 PluginDatumProcessor proc, void *proc_cls)
826 struct Plugin *plugin = cls;
834 GNUNET_assert (proc != NULL);
835 GNUNET_assert (key != NULL);
836 GNUNET_snprintf (scratch, sizeof (scratch),
837 "SELECT count(*) FROM gn090 WHERE hash=?%s%s",
838 vhash == NULL ? "" : " AND vhash=?",
839 type == 0 ? "" : " AND type=?");
840 if (sq_prepare (plugin->dbh, scratch, &stmt) != SQLITE_OK)
842 LOG_SQLITE (plugin, NULL,
843 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
845 proc (proc_cls, NULL, 0, NULL, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0);
849 ret = sqlite3_bind_blob (stmt, sqoff++,
850 key, sizeof (GNUNET_HashCode), SQLITE_TRANSIENT);
851 if ((vhash != NULL) && (ret == SQLITE_OK))
852 ret = sqlite3_bind_blob (stmt, sqoff++,
853 vhash, sizeof (GNUNET_HashCode), SQLITE_TRANSIENT);
854 if ((type != 0) && (ret == SQLITE_OK))
855 ret = sqlite3_bind_int (stmt, sqoff++, type);
856 if (SQLITE_OK != ret)
858 LOG_SQLITE (plugin, NULL, GNUNET_ERROR_TYPE_ERROR, "sqlite_bind");
859 sqlite3_finalize (stmt);
860 proc (proc_cls, NULL, 0, NULL, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0);
863 ret = sqlite3_step (stmt);
864 if (ret != SQLITE_ROW)
866 LOG_SQLITE (plugin, NULL,
867 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
869 sqlite3_finalize (stmt);
870 proc (proc_cls, NULL, 0, NULL, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0);
873 total = sqlite3_column_int (stmt, 0);
874 sqlite3_finalize (stmt);
877 proc (proc_cls, NULL, 0, NULL, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0);
880 limit_off = (int) (offset % total);
883 GNUNET_snprintf (scratch, sizeof (scratch),
884 "SELECT type, prio, anonLevel, expire, hash, value, _ROWID_ "
885 "FROM gn090 WHERE hash=?%s%s "
886 "ORDER BY _ROWID_ ASC LIMIT 1 OFFSET ?",
887 vhash == NULL ? "" : " AND vhash=?",
888 type == 0 ? "" : " AND type=?");
889 if (sq_prepare (plugin->dbh, scratch, &stmt) != SQLITE_OK)
891 LOG_SQLITE (plugin, NULL,
892 GNUNET_ERROR_TYPE_ERROR |
893 GNUNET_ERROR_TYPE_BULK, "sqlite_prepare");
894 proc (proc_cls, NULL, 0, NULL, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0);
898 ret = sqlite3_bind_blob (stmt,
900 key, sizeof (GNUNET_HashCode), SQLITE_TRANSIENT);
901 if ((vhash != NULL) && (ret == SQLITE_OK))
902 ret = sqlite3_bind_blob (stmt,
904 vhash, sizeof (GNUNET_HashCode), SQLITE_TRANSIENT);
905 if ((type != 0) && (ret == SQLITE_OK))
906 ret = sqlite3_bind_int (stmt, sqoff++, type);
907 if (ret == SQLITE_OK)
908 ret = sqlite3_bind_int64 (stmt, sqoff++, limit_off);
909 if (ret != SQLITE_OK)
911 LOG_SQLITE (plugin, NULL,
912 GNUNET_ERROR_TYPE_ERROR |
913 GNUNET_ERROR_TYPE_BULK, "sqlite_bind");
914 proc (proc_cls, NULL, 0, NULL, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0);
917 execute_get (plugin, stmt, proc, proc_cls);
918 sqlite3_finalize (stmt);
924 * Context for 'repl_proc' function.
930 * Function to call for the result (or the NULL).
932 PluginDatumProcessor proc;
945 * Yes if UID was set.
952 * Wrapper for the processor for 'sqlite_plugin_replication_get'.
953 * Decrements the replication counter and calls the original
957 * @param key key for the content
958 * @param size number of bytes in data
959 * @param data content stored
960 * @param type type of the content
961 * @param priority priority of the content
962 * @param anonymity anonymity-level for the content
963 * @param expiration expiration time for the content
964 * @param uid unique identifier for the datum;
965 * maybe 0 if no unique identifier is available
967 * @return GNUNET_OK for normal return,
968 * GNUNET_NO to delete the item
971 repl_proc (void *cls,
972 const GNUNET_HashCode * key,
975 enum GNUNET_BLOCK_Type type,
978 struct GNUNET_TIME_Absolute expiration, uint64_t uid)
980 struct ReplCtx *rc = cls;
983 ret = rc->proc (rc->proc_cls,
984 key, size, data, type, priority, anonymity, expiration, uid);
988 rc->have_uid = GNUNET_YES;
995 * Get a random item for replication. Returns a single random item
996 * from those with the highest replication counters. The item's
997 * replication counter is decremented by one IF it was positive before.
998 * Call 'proc' with all values ZERO or NULL if the datastore is empty.
1000 * @param cls closure
1001 * @param proc function to call the value (once only).
1002 * @param proc_cls closure for proc
1005 sqlite_plugin_get_replication (void *cls,
1006 PluginDatumProcessor proc, void *proc_cls)
1008 struct Plugin *plugin = cls;
1015 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1017 "Getting random block based on replication order.\n");
1019 rc.have_uid = GNUNET_NO;
1021 rc.proc_cls = proc_cls;
1022 stmt = plugin->maxRepl;
1023 if (SQLITE_ROW != sqlite3_step (stmt))
1025 if (SQLITE_OK != sqlite3_reset (stmt))
1026 LOG_SQLITE (plugin, NULL,
1027 GNUNET_ERROR_TYPE_ERROR |
1028 GNUNET_ERROR_TYPE_BULK, "sqlite3_reset");
1030 proc (proc_cls, NULL, 0, NULL, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0);
1033 repl = sqlite3_column_int (stmt, 0);
1034 if (SQLITE_OK != sqlite3_reset (stmt))
1035 LOG_SQLITE (plugin, NULL,
1036 GNUNET_ERROR_TYPE_ERROR |
1037 GNUNET_ERROR_TYPE_BULK, "sqlite3_reset");
1038 stmt = plugin->selRepl;
1039 rvalue = GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK, UINT64_MAX);
1040 if (SQLITE_OK != sqlite3_bind_int64 (stmt, 1, rvalue))
1042 LOG_SQLITE (plugin, NULL,
1043 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
1044 "sqlite3_bind_XXXX");
1045 if (SQLITE_OK != sqlite3_reset (stmt))
1046 LOG_SQLITE (plugin, NULL,
1047 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
1049 proc (proc_cls, NULL, 0, NULL, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0);
1052 if (SQLITE_OK != sqlite3_bind_int (stmt, 2, repl))
1054 LOG_SQLITE (plugin, NULL,
1055 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
1056 "sqlite3_bind_XXXX");
1057 if (SQLITE_OK != sqlite3_reset (stmt))
1058 LOG_SQLITE (plugin, NULL,
1059 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
1061 proc (proc_cls, NULL, 0, NULL, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0);
1064 execute_get (plugin, stmt, &repl_proc, &rc);
1065 if (GNUNET_YES == rc.have_uid)
1067 if (SQLITE_OK != sqlite3_bind_int64 (plugin->updRepl, 1, rc.uid))
1069 LOG_SQLITE (plugin, NULL,
1070 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
1071 "sqlite3_bind_XXXX");
1072 if (SQLITE_OK != sqlite3_reset (plugin->updRepl))
1073 LOG_SQLITE (plugin, NULL,
1074 GNUNET_ERROR_TYPE_ERROR |
1075 GNUNET_ERROR_TYPE_BULK, "sqlite3_reset");
1078 if (SQLITE_DONE != sqlite3_step (plugin->updRepl))
1079 LOG_SQLITE (plugin, NULL,
1080 GNUNET_ERROR_TYPE_ERROR |
1081 GNUNET_ERROR_TYPE_BULK, "sqlite3_step");
1082 if (SQLITE_OK != sqlite3_reset (plugin->updRepl))
1083 LOG_SQLITE (plugin, NULL,
1084 GNUNET_ERROR_TYPE_ERROR |
1085 GNUNET_ERROR_TYPE_BULK, "sqlite3_reset");
1092 * Get a random item that has expired or has low priority.
1093 * Call 'proc' with all values ZERO or NULL if the datastore is empty.
1095 * @param cls closure
1096 * @param proc function to call the value (once only).
1097 * @param proc_cls closure for proc
1100 sqlite_plugin_get_expiration (void *cls,
1101 PluginDatumProcessor proc, void *proc_cls)
1103 struct Plugin *plugin = cls;
1105 struct GNUNET_TIME_Absolute now;
1108 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1110 "Getting random block based on expiration and priority order.\n");
1112 now = GNUNET_TIME_absolute_get ();
1113 stmt = plugin->selExpi;
1114 if (SQLITE_OK != sqlite3_bind_int64 (stmt, 1, now.abs_value))
1116 LOG_SQLITE (plugin, NULL,
1117 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
1118 "sqlite3_bind_XXXX");
1119 if (SQLITE_OK != sqlite3_reset (stmt))
1120 LOG_SQLITE (plugin, NULL,
1121 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
1123 proc (proc_cls, NULL, 0, NULL, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0);
1126 execute_get (plugin, stmt, proc, proc_cls);
1133 * @param cls our plugin context
1136 sqlite_plugin_drop (void *cls)
1138 struct Plugin *plugin = cls;
1140 plugin->drop_on_shutdown = GNUNET_YES;
1145 * Get an estimate of how much space the database is
1148 * @param cls the 'struct Plugin'
1149 * @return the size of the database on disk (estimate)
1151 static unsigned long long
1152 sqlite_plugin_estimate_size (void *cls)
1154 struct Plugin *plugin = cls;
1163 if (SQLITE_VERSION_NUMBER < 3006000)
1165 GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING,
1168 ("sqlite version to old to determine size, assuming zero\n"));
1171 CHECK (SQLITE_OK == sqlite3_exec (plugin->dbh, "VACUUM", NULL, NULL, ENULL));
1173 sqlite3_exec (plugin->dbh,
1174 "PRAGMA auto_vacuum=INCREMENTAL", NULL, NULL, ENULL));
1175 CHECK (SQLITE_OK == sq_prepare (plugin->dbh, "PRAGMA page_count", &stmt));
1176 if (SQLITE_ROW == sqlite3_step (stmt))
1177 pages = sqlite3_column_int64 (stmt, 0);
1180 sqlite3_finalize (stmt);
1181 CHECK (SQLITE_OK == sq_prepare (plugin->dbh, "PRAGMA page_size", &stmt));
1182 CHECK (SQLITE_ROW == sqlite3_step (stmt));
1183 page_size = sqlite3_column_int64 (stmt, 0);
1184 sqlite3_finalize (stmt);
1185 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1187 ("Using sqlite page utilization to estimate payload (%llu pages of size %llu bytes)\n"),
1188 (unsigned long long) pages, (unsigned long long) page_size);
1189 return pages * page_size;
1194 * Entry point for the plugin.
1196 * @param cls the "struct GNUNET_DATASTORE_PluginEnvironment*"
1197 * @return NULL on error, othrewise the plugin context
1200 libgnunet_plugin_datastore_sqlite_init (void *cls)
1202 static struct Plugin plugin;
1203 struct GNUNET_DATASTORE_PluginEnvironment *env = cls;
1204 struct GNUNET_DATASTORE_PluginFunctions *api;
1206 if (plugin.env != NULL)
1207 return NULL; /* can only initialize once! */
1208 memset (&plugin, 0, sizeof (struct Plugin));
1210 if (GNUNET_OK != database_setup (env->cfg, &plugin))
1212 database_shutdown (&plugin);
1215 api = GNUNET_malloc (sizeof (struct GNUNET_DATASTORE_PluginFunctions));
1217 api->estimate_size = &sqlite_plugin_estimate_size;
1218 api->put = &sqlite_plugin_put;
1219 api->update = &sqlite_plugin_update;
1220 api->get_key = &sqlite_plugin_get_key;
1221 api->get_replication = &sqlite_plugin_get_replication;
1222 api->get_expiration = &sqlite_plugin_get_expiration;
1223 api->get_zero_anonymity = &sqlite_plugin_get_zero_anonymity;
1224 api->drop = &sqlite_plugin_drop;
1225 GNUNET_log_from (GNUNET_ERROR_TYPE_INFO,
1226 "sqlite", _("Sqlite database running\n"));
1232 * Exit point from the plugin.
1234 * @param cls the plugin context (as returned by "init")
1235 * @return always NULL
1238 libgnunet_plugin_datastore_sqlite_done (void *cls)
1241 struct GNUNET_DATASTORE_PluginFunctions *api = cls;
1242 struct Plugin *plugin = api->cls;
1245 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1246 "sqlite", "sqlite plugin is done\n");
1250 if (plugin->drop_on_shutdown)
1251 fn = GNUNET_strdup (plugin->fn);
1253 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1254 "sqlite", "Shutting down database\n");
1256 database_shutdown (plugin);
1261 if (0 != UNLINK (fn))
1262 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "unlink", fn);
1266 GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1267 "sqlite", "sqlite plugin is finished\n");
1272 /* end of plugin_datastore_sqlite.c */