3 #include <readline/readline.h>
9 printf(" Usage: add [PARENT]\n");
10 printf(" Adds a new task.\n");
11 printf(" If you specify a PARENT, the new task will be a subtask of PARENT.\n");
14 char *escape(char *string
) {
15 int length
= strlen(string
);
16 char *escaped
= malloc((length
+1)*sizeof(char));
19 for (i
= 0, j
= 0; string
[i
] != '\0'; i
++, j
++) {
20 if (string
[i
] == '\'') {
22 escaped
= realloc(escaped
, (length
+1)*sizeof(char));
26 escaped
[j
] = string
[i
];
34 int add(sqlite3
*db
, MArray tokens
) {
39 char *escapedDescription
;
42 sqlite3_stmt
*statement
;
44 if (tokens
->len
== 2 && !strcmp(myarray_get(tokens
, char *, 1), "help")) {
47 } else if (tokens
->len
== 2) {
48 if (sscanf(myarray_get(tokens
, char *, 1), "%d%n", &parent
, &parsed
) < 1 || parsed
!= strlen(myarray_get(tokens
, char *, 1)) || parent
< 0) {
49 printf("Invalid argument. PARENT must be a positive integer.\n");
54 query
= sqlite3_mprintf("SELECT COUNT(key) FROM todo WHERE key = %d;", parent
);
55 if (sqlite3_prepare_v2(db
, query
, -1, &statement
, NULL
) != SQLITE_OK
) {
56 printf("Couldn't prepare for the query that checks that a valid parent has been selected.\n");
60 while (sqlite3_step(statement
) == SQLITE_ROW
) {
61 valid_parent
= sqlite3_column_int(statement
, 0);
63 sqlite3_finalize(statement
);
67 printf("The parent for which you want to create a subtask does not exist.\n");
70 } else if (tokens
->len
> 2) {
71 printf("Invalid amount of arguments.\n");
76 description
= readline("Please enter a description for the new task:\n");
77 if (!description
|| strlen(description
) <= 0) {
78 printf("Your description must not be an empty string.\n");
79 if (description
) free(description
);
83 escapedDescription
= escape(description
);
87 query
= sqlite3_mprintf("INSERT INTO todo (description, createdDate, parent) VALUES (\'%s\', %d, %d);", escapedDescription
, time(NULL
), parent
);
89 query
= sqlite3_mprintf("INSERT INTO todo (description, createdDate) VALUES (\'%s\', %d);", escapedDescription
, time(NULL
));
92 if (sqlite3_exec(db
, query
, NULL
, NULL
, &errmsg
) != SQLITE_OK
) {
93 printf("An error occurred while trying to add a new task: %s\n", errmsg
);