aboutsummaryrefslogtreecommitdiff
path: root/db.c
diff options
context:
space:
mode:
Diffstat (limited to 'db.c')
-rw-r--r--db.c62
1 files changed, 61 insertions, 1 deletions
diff --git a/db.c b/db.c
index 983080f..12230c3 100644
--- a/db.c
+++ b/db.c
@@ -10,7 +10,7 @@
#define SQLITE(func,...) do{if(sqlite3_##func(__VA_ARGS__)!=SQLITE_OK){die_sqlite("sqlite3_" #func);}}while(0)
-sqlite3 *database;
+sqlite3 *database=NULL;
__attribute__((noreturn))
static void die_sqlite(const char *func){
@@ -19,6 +19,8 @@ static void die_sqlite(const char *func){
void db_init(void){
+ SQLITE(config,SQLITE_CONFIG_SERIALIZED);
+ SQLITE(initialize);
SQLITE(open_v2,"db.db",&database,SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE,NULL);
char *str=malloc(schema_sql_len+1,char);
memcpy(str,schema_sql,schema_sql_len);
@@ -29,6 +31,8 @@ void db_init(void){
void db_close(void){
sqlite3_close(database);
+ SQLITE(shutdown);
+ database=NULL;
}
@@ -229,6 +233,54 @@ i64 db_find_user(const char *name){
return userid;
}
+struct db_strings_list db_user_tokens(i64 userid){
+ sqlite3_stmt *stmt;
+ SQLITE(prepare_v2,database,"select token from Firebase where user = ?",-1,&stmt,NULL);
+ SQLITE(bind_int64,stmt,1,userid);
+
+ struct db_strings_list sl;
+ i64 cap=4;
+ sl.count=0;
+ sl.list=malloc(cap,char*);
+
+ int ret;
+ while((ret=sqlite3_step(stmt))==SQLITE_ROW){
+ if(sl.count==cap){
+ cap*=2;
+ sl.list=realloc(sl.list,cap,char*);
+ }
+ sl.list[sl.count]=strdup((const char*)sqlite3_column_text(stmt,0));
+ sl.count++;
+ }
+
+ if(ret!=SQLITE_DONE)die_sqlite("sqlite3_step");
+ SQLITE(finalize,stmt);
+
+ return sl;
+}
+
+bool db_add_token(i64 userid,const char *token){
+ assert(userid!=-1);
+ sqlite3_stmt *stmt;
+ SQLITE(prepare_v2,database,"insert into Firebase (user, token) values (?, ?)",-1,&stmt,NULL);
+ SQLITE(bind_int64,stmt,1,userid);
+ SQLITE(bind_text,stmt,2,token,-1,SQLITE_STATIC);
+ bool success=sqlite3_step(stmt)==SQLITE_DONE;
+ SQLITE(finalize,stmt);
+ return success;
+}
+
+bool db_delete_token(i64 userid,const char *token){
+ assert(userid!=-1);
+ sqlite3_stmt *stmt;
+ SQLITE(prepare_v2,database,"delete from Firebase where user = ? and token = ?",-1,&stmt,NULL);
+ SQLITE(bind_int64,stmt,1,userid);
+ SQLITE(bind_text,stmt,2,token,-1,SQLITE_STATIC);
+ bool success=sqlite3_step(stmt)==SQLITE_DONE;
+ SQLITE(finalize,stmt);
+ return success;
+}
+
void db_create_message(i64 roomid,i64 userid,i64 timestamp,const char *message){
sqlite3_stmt *stmt;
@@ -307,3 +359,11 @@ void db_nullify_message_list(struct db_message_list ml){
if(ml.list)free(ml.list);
ml.list=NULL;
}
+
+void db_nullify_strings_list(struct db_strings_list sl){
+ for(i64 i=0;i<sl.count;i++){
+ free(sl.list[i]);
+ }
+ if(sl.list)free(sl.list);
+ sl.list=NULL;
+}