From c8cd2cebb7c0ddc8b144ddc062cdc8a81d032a4d Mon Sep 17 00:00:00 2001 From: Jordan Bancino Date: Thu, 15 Dec 2022 02:39:58 +0000 Subject: [PATCH] Implement DbDelete() --- TODO.txt | 2 +- man/man7/telodendria-changelog.7 | 8 +++- src/Db.c | 70 ++++++++++++++++++++++++++++++++ src/include/Db.h | 3 ++ 4 files changed, 81 insertions(+), 2 deletions(-) diff --git a/TODO.txt b/TODO.txt index b2e7b01..ecce73a 100644 --- a/TODO.txt +++ b/TODO.txt @@ -11,7 +11,7 @@ Key: Milestone: v0.1.1 ----------------- -[ ] DbDelete() +[x] DbDelete() [ ] UtilRandomString() [ ] Database version file [ ] User registration diff --git a/man/man7/telodendria-changelog.7 b/man/man7/telodendria-changelog.7 index 7eea9bf..cadae6f 100644 --- a/man/man7/telodendria-changelog.7 +++ b/man/man7/telodendria-changelog.7 @@ -1,4 +1,4 @@ -.Dd $Mdocdate: December 14 2022 $ +.Dd $Mdocdate: December 15 2022 $ .Dt TELODENDRIA-CHANGELOG 7 .Os Telodendria Project .Sh NAME @@ -37,6 +37,12 @@ Changes: .It Improved HTTP request logging by removing unnecessary log entries and making errors more specific. +.It +Added a way to safely delete objects from the database. +While the database is for persistent storage, there may +be some ephemeral data that lives there only for a short +while, so it will be necessary to remove that data when +necessary. .El .Pp Bug fixes: diff --git a/src/Db.c b/src/Db.c index 045b630..88c9a83 100644 --- a/src/Db.c +++ b/src/Db.c @@ -537,6 +537,76 @@ DbCreate(Db * db, size_t nArgs,...) return DbLockFromArr(db, args); } +int +DbDelete(Db * db, size_t nArgs,...) +{ + va_list ap; + Array *args; + char *file; + char *hash; + int ret = 1; + DbRef *ref; + + if (!db) + { + return 0; + } + + va_start(ap, nArgs); + args = ArrayFromVarArgs(nArgs, ap); + va_end(ap); + + pthread_mutex_lock(&db->lock); + + hash = DbHashKey(args); + file = DbFileName(db, args); + + ref = HashMapGet(db->cache, hash); + if (ref) + { + pthread_mutex_lock(&ref->lock); + + HashMapDelete(db->cache, hash); + JsonFree(ref->json); + ArrayFree(ref->name); + + db->cacheSize -= ref->size; + + if (ref->next) + { + ref->next->prev = ref->prev; + } + else + { + db->mostRecent = ref->prev; + } + + if (ref->prev) + { + ref->prev->next = ref->next; + } + else + { + db->leastRecent = ref->next; + } + + pthread_mutex_unlock(&ref->lock); + pthread_mutex_destroy(&ref->lock); + Free(ref); + } + + Free(hash); + + if (UtilLastModified(file)) + { + ret = remove(file) == 0; + } + + pthread_mutex_unlock(&db->lock); + + return ret; +} + DbRef * DbLock(Db * db, size_t nArgs,...) { diff --git a/src/include/Db.h b/src/include/Db.h index d1f9397..32cd1ab 100644 --- a/src/include/Db.h +++ b/src/include/Db.h @@ -44,6 +44,9 @@ extern void extern DbRef * DbCreate(Db *, size_t,...); +extern int + DbDelete(Db *, size_t,...); + extern DbRef * DbLock(Db *, size_t,...);