fixed postgresql functions, ready to insert json data to db

This commit is contained in:
2025-11-22 04:27:52 -08:00
parent 0a0c9ce418
commit e07cdbd36c

33
muzi.c
View File

@@ -33,18 +33,21 @@ bool table_exists(const char *name, PGconn *conn);
int create_table(const char *name, PGconn *conn); int create_table(const char *name, PGconn *conn);
bool table_exists(const char *name, PGconn *conn) { bool table_exists(const char *name, PGconn *conn) {
const char *paramValues[1] = {name};
Oid paramTypes[1] = {25};
PGresult *result = PGresult *result =
PQexecParams(conn, PQexecParams(conn,
"SELECT EXISTS (SELECT 1 FROM pg_tables WHERE schemaname = " "SELECT EXISTS (SELECT 1 FROM pg_tables "
"'public' AND tablename = $1);", "WHERE schemaname = 'public' AND tablename = $1);",
1, NULL, &name, NULL, NULL, 0); 1, paramTypes, paramValues, NULL, NULL, 0);
if (PQresultStatus(result) != PGRES_TUPLES_OK) { if (PQresultStatus(result) != PGRES_TUPLES_OK) {
printf("SELECT EXISTS failed: %s\n", PQerrorMessage(conn)); printf("SELECT EXISTS failed: %s\n", PQerrorMessage(conn));
PQclear(result); PQclear(result);
return false; return false;
} }
bool exists = strcmp(PQgetvalue(result, 0, 0), "t") == 0;
PQclear(result); PQclear(result);
return (strcmp(PQgetvalue(result, 0, 0), "t") == 0); return exists;
} }
bool db_exists(void) { bool db_exists(void) {
@@ -110,17 +113,18 @@ int json_to_db(const char *json_file) {
bool e = table_exists("history", conn); bool e = table_exists("history", conn);
if (e) { if (e) {
printf("history table exists\n");
} else { } else {
printf("history table doesn't exist\n"); printf("Creating history table.\n");
PGresult *result = PQexec(
PQexec(conn, "CREATE TABLE history ( date TEXT)"); conn,
"CREATE TABLE history ( id INT PRIMARY KEY GENERATED ALWAYS AS "
e = table_exists("history", conn); "IDENTITY, year INT, month INT, day INT, time VARCHAR(10), timestamp "
if (e) { "VARCHAR(20), song_name VARCHAR(100), artist VARCHAR(100), "
printf("history table exists\n"); "album_artist VARCHAR(100), album_name VARCHAR(100));");
} else { if (PQresultStatus(result) != PGRES_COMMAND_OK) {
printf("still doesn't exist!!\n"); printf("History table creation failed: %s\n", PQerrorMessage(conn));
PQfinish(conn);
return EXIT_FAILURE;
} }
} }
@@ -329,6 +333,7 @@ int import_spotify(void) {
int main(void) { int main(void) {
// import_spotify(); // import_spotify();
// add_dir_to_db("./spotify-data/extracted"); // add_dir_to_db("./spotify-data/extracted");
json_to_db("test");
return EXIT_SUCCESS; return EXIT_SUCCESS;
} }