aboutsummaryrefslogtreecommitdiff
path: root/miniDB/db_commands.c
diff options
context:
space:
mode:
authorHyder Hadi <hyder@hyderhadi.xyz>2026-06-09 16:33:38 +0300
committerHyder Hadi <hyder@hyderhadi.xyz>2026-06-09 16:33:38 +0300
commitd6b915a043f868611d49e814730ffc2f7c82a048 (patch)
treee7d6e687de0b40b30a5cadfc1bd35aa1b0c70a1f /miniDB/db_commands.c
parent5a6a3dd7c8f535721467248cf5f93f8e0ef1e633 (diff)
Made a simple miniDB during the governmental job XD
simple miniDB that has couple of commands, that uses my hashMap implementation to store (key,value) pairs.
Diffstat (limited to 'miniDB/db_commands.c')
-rw-r--r--miniDB/db_commands.c97
1 files changed, 97 insertions, 0 deletions
diff --git a/miniDB/db_commands.c b/miniDB/db_commands.c
new file mode 100644
index 0000000..4e6edae
--- /dev/null
+++ b/miniDB/db_commands.c
@@ -0,0 +1,97 @@
+#include "HashMap.h"
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#define SUCCESS 1
+#define FAILED 0
+#define EXIT -1
+
+void parse(char *input, char *tokens[], int max_tokens) {
+
+ int i = 0;
+
+ char *token = strtok(input, " ");
+
+ while (token != NULL && i < max_tokens) {
+
+ tokens[i] = token;
+
+ i++;
+
+ token = strtok(NULL, " ");
+ }
+}
+
+int db_commands(struct hashTable *self, FILE *fh, char *fileName) {
+
+ printf("db> ");
+
+ char *input = read_line();
+ if (!input) {
+ return FAILED;
+ }
+
+ char *tokens[3];
+
+ parse(input, tokens, 3);
+
+ char *endptr;
+
+ int value = strtol(tokens[2], &endptr, 10);
+
+ if (strcmp(tokens[0], "INSERT") == 0) {
+
+ if (*endptr != '\0')
+ return FAILED;
+
+ self->insert(self, tokens[1], value);
+ return SUCCESS;
+ } else if (strcmp(tokens[0], "EXIT") == 0) {
+ printf("BYE\n");
+ return EXIT;
+ } else if (strcmp(tokens[0], "GET") == 0) {
+ struct Entry *cur = self->find(self, tokens[1]);
+ if (cur) {
+ printf("%d\n", cur->__value);
+ return SUCCESS;
+ }
+ return FAILED;
+ } else if (strcmp(tokens[0], "DELETE") == 0) {
+ self->pop(self, tokens[1]);
+ } else if (strcmp(tokens[0], "SAVE") == 0) {
+ fh = fopen(fileName, "w");
+
+ int iteratorCount = 0;
+
+ while (iteratorCount < self->__buckets) {
+ if (self->__items[iteratorCount].__key == NULL) {
+ iteratorCount++;
+ continue;
+ }
+ fprintf(fh, "%s %d\n", self->__items[iteratorCount].__key, self->__items[iteratorCount].__value);
+ iteratorCount++;
+ }
+
+ fclose(fh);
+ return SUCCESS;
+ } else if (strcmp(tokens[0], "LOAD") == 0) {
+ tokens[1] = fileName;
+ fh = fopen(tokens[1], "r");
+
+ char key[100];
+ int val;
+ while (fscanf(fh, "%s %d\n", key, &val) == 2) {
+ self->insert(self, key, val);
+ }
+ fclose(fh);
+ return SUCCESS;
+ } else if (strcmp(tokens[0], "HELP") == 0) {
+ printf("INSERT <key> <value>\nDELETE <key>\nGET <key>\nSAVE\nLOAD <filename>\nEXIT\nDUMPTBL\n");
+ return SUCCESS;
+ }
+ else if(strcmp(tokens[0], "DUMPTBL") == 0) {
+ self->dump(self);
+ }
+ return FAILED;
+} \ No newline at end of file