From e10c43dfd6e1cc8b8ede0eb7e2a72f5295835fd9 Mon Sep 17 00:00:00 2001 From: Chewing_Bever Date: Wed, 8 Nov 2023 09:05:38 +0100 Subject: [PATCH] fix(lsm): work when first creating db --- lsm/src/store/lsm_store.c | 18 ++++++++++++++++++ lsm/src/store/lsm_store_sync.c | 4 ++-- 2 files changed, 20 insertions(+), 2 deletions(-) diff --git a/lsm/src/store/lsm_store.c b/lsm/src/store/lsm_store.c index 9c0ab83..43eb475 100644 --- a/lsm/src/store/lsm_store.c +++ b/lsm/src/store/lsm_store.c @@ -44,11 +44,20 @@ lsm_error lsm_store_load(lsm_store **ptr, lsm_str *data_path) { FILE *db_file = fopen(db_file_path, "r+b"); if (db_file == NULL) { + // Create the file first, then reopen it in extended read db_file = fopen(db_file_path, "wb"); if (db_file == NULL) { return lsm_error_failed_io; } + + fclose(db_file); + + FILE *db_file = fopen(db_file_path, "r+b"); + + if (db_file == NULL) { + return lsm_error_failed_io; + } } // Same for idx file @@ -60,6 +69,7 @@ lsm_error lsm_store_load(lsm_store **ptr, lsm_str *data_path) { FILE *idx_file = fopen(idx_file_path, "r+b"); if (idx_file == NULL) { + // Create the file first idx_file = fopen(idx_file_path, "wb"); if (idx_file == NULL) { @@ -75,6 +85,14 @@ lsm_error lsm_store_load(lsm_store **ptr, lsm_str *data_path) { } fflush(idx_file); + fclose(idx_file); + + // If opening it in extended read mode still fails now, there's a problem + FILE *idx_file = fopen(idx_file_path, "r+b"); + + if (idx_file == NULL) { + return lsm_error_failed_io; + } } store->data_path = data_path; diff --git a/lsm/src/store/lsm_store_sync.c b/lsm/src/store/lsm_store_sync.c index caaa42b..3a668d4 100644 --- a/lsm/src/store/lsm_store_sync.c +++ b/lsm/src/store/lsm_store_sync.c @@ -73,8 +73,6 @@ lsm_error lsm_entry_sync(lsm_store *store, lsm_entry_handle *handle) { lsm_entry_write_db(&entry_size, store->db_file, handle->wrapper->entry); fflush(store->db_file); - // TODO fsync db file? - if (res != lsm_error_ok) { pthread_mutex_unlock(&store->db_lock); @@ -177,6 +175,8 @@ lsm_error lsm_store_load_db(lsm_store *store) { lsm_str *key; lsm_entry_handle *handle; + rewind(store->idx_file); + // idx file starts with block count size_t res = fread(&store->idx_file_block_count, sizeof(uint64_t), 1, store->idx_file);