From 8ee456ac53bae2993f58458361738320d1045e96 Mon Sep 17 00:00:00 2001 From: augustin64 Date: Wed, 12 Jul 2023 21:55:27 +0200 Subject: [PATCH] Keep database integrity (e.g. no x2 id) --- src/db.c | 25 +++++++++++++++++++++++-- src/include/config.h | 3 +++ 2 files changed, 26 insertions(+), 2 deletions(-) diff --git a/src/db.c b/src/db.c index dd9a8d0..baa8dae 100644 --- a/src/db.c +++ b/src/db.c @@ -156,6 +156,8 @@ void delete_task(int id) { void get_task(int id, task_t* t) { + t->id = -1; + sqlite3* db = get_db(); sqlite3_stmt* stmt; @@ -185,7 +187,7 @@ void get_task(int id, task_t* t) { sqlite3_finalize(stmt); sqlite3_close(db); - // t.id will be (-1) if not found + // t->id will be (-1) if not found } int list_tasks() { @@ -224,5 +226,24 @@ int list_tasks() { } int get_new_task_id() { - return rand()%10000; + task_t t; + + int new_id = rand() %MAX_TASK_ID; + t.id = new_id; + + int i=0; + while (t.id != -1 && i < NEW_TASK_ID_MAX_RETRIES) { // If t.id==-1, task is not found so the id is sage to use + new_id = rand() %MAX_TASK_ID; + get_task(new_id, &t); + i++; + } + + if (i == NEW_TASK_ID_MAX_RETRIES) { + printf(RED BOLD "Il semblerait que vous ayez un nombre de tâches se rapprochant de %d.\n" RESET, MAX_TASK_ID); + printf(YELLOW "Il peut être judicieux de supprimer les tâches effectuées pour libérer de la place (et des identifiants).\n"); + printf("Vous pouvez également modifier la limite du nombre d'identifiants et recompiler le projet.\n" RESET); + return -1; + } + + return new_id; } \ No newline at end of file diff --git a/src/include/config.h b/src/include/config.h index 3aac598..61c5dc0 100644 --- a/src/include/config.h +++ b/src/include/config.h @@ -4,4 +4,7 @@ #define VERSION "0.0.0" #define DB_FILE "takl.sqlite3" +#define MAX_TASK_ID 10000 // max is set to MAX_TASK_ID-1 +#define NEW_TASK_ID_MAX_RETRIES 10000 // number of retries before giving up + #endif \ No newline at end of file