From a877a19c25fc158d547209f848df3facb74b34cc Mon Sep 17 00:00:00 2001 From: William Casarin Date: Thu, 20 Mar 2025 13:37:23 -0700 Subject: [PATCH] nostrdb: relay: add note relay iteration This is a simple cursor that walks the NDB_DB_NOTE_RELAYS db Signed-off-by: William Casarin --- nostrdb/src/nostrdb.c | 51 +++++++++++++++++++++++++++++++++++++++++++ nostrdb/src/nostrdb.h | 12 ++++++++++ 2 files changed, 63 insertions(+) diff --git a/nostrdb/src/nostrdb.c b/nostrdb/src/nostrdb.c index 0e423fad..de8f811d 100644 --- a/nostrdb/src/nostrdb.c +++ b/nostrdb/src/nostrdb.c @@ -7328,6 +7328,57 @@ struct ndb_note * ndb_note_from_bytes(unsigned char *bytes) return note; } +int ndb_note_relay_iterate_start(struct ndb_txn *txn, + struct ndb_note_relay_iterator *iter, + uint64_t note_key) +{ + if (mdb_cursor_open(txn->mdb_txn, txn->lmdb->dbs[NDB_DB_NOTE_RELAYS], + (MDB_cursor**)&iter->mdb_cur)) { + return 0; + } + + iter->txn = txn; + iter->cursor_op = MDB_SET_KEY; + iter->note_key = note_key; + + return 1; +} + +const char *ndb_note_relay_iterate_next(struct ndb_note_relay_iterator *iter) +{ + int rc; + MDB_val k, v; + + if (iter->mdb_cur == NULL) + return NULL; + + k.mv_data = &iter->note_key; + k.mv_size = sizeof(iter->note_key); + + if ((rc = mdb_cursor_get((MDB_cursor *)iter->mdb_cur, &k, &v, + (MDB_cursor_op)iter->cursor_op))) + { + //fprintf(stderr, "autoclosing %d '%s'\n", iter->cursor_op, mdb_strerror(rc)); + // autoclose + ndb_note_relay_iterate_close(iter); + return NULL; + } + + iter->cursor_op = MDB_NEXT_DUP; + + return (const char*)v.mv_data; +} + +void ndb_note_relay_iterate_close(struct ndb_note_relay_iterator *iter) +{ + if (!iter || iter->mdb_cur == NULL) + return; + + mdb_cursor_close((MDB_cursor*)iter->mdb_cur); + + iter->mdb_cur = NULL; +} + void ndb_tags_iterate_start(struct ndb_note *note, struct ndb_iterator *iter) { iter->note = note; diff --git a/nostrdb/src/nostrdb.h b/nostrdb/src/nostrdb.h index 7eb3ba3b..13707fb3 100644 --- a/nostrdb/src/nostrdb.h +++ b/nostrdb/src/nostrdb.h @@ -229,6 +229,13 @@ struct ndb_builder { struct ndb_tag *current_tag; }; +struct ndb_note_relay_iterator { + struct ndb_txn *txn; + uint64_t note_key; + int cursor_op; + void *mdb_cur; +}; + struct ndb_iterator { struct ndb_note *note; struct ndb_tag *tag; @@ -615,6 +622,11 @@ int ndb_tags_iterate_next(struct ndb_iterator *iter); struct ndb_str ndb_iter_tag_str(struct ndb_iterator *iter, int ind); struct ndb_str ndb_tag_str(struct ndb_note *note, struct ndb_tag *tag, int ind); +// RELAY ITER +int ndb_note_relay_iterate_start(struct ndb_txn *txn, struct ndb_note_relay_iterator *iter, uint64_t note_key); +const char *ndb_note_relay_iterate_next(struct ndb_note_relay_iterator *iter); +void ndb_note_relay_iterate_close(struct ndb_note_relay_iterator *iter); + // NAMES const char *ndb_db_name(enum ndb_dbs db); const char *ndb_kind_name(enum ndb_common_kind ck);