diff options
Diffstat (limited to 'db.c')
-rw-r--r-- | db.c | 61 |
1 files changed, 61 insertions, 0 deletions
@@ -0,0 +1,61 @@ +#include <string.h> +#include <sqlite3.h> +#include "db.h" +#include "schema.sql.h" + + +#define SQLITE(func,...) do{if(sqlite3_##func(__VA_ARGS__)!=SQLITE_OK){die_sqlite("sqlite3_" #func);}}while(0) + + +sqlite3 *database; + +__attribute__((noreturn)) +static void die_sqlite(const char *func){ + die("%s: %s",func,sqlite3_errmsg(database)); +} + + +void db_init(void){ + 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); + str[schema_sql_len]='\0'; + sqlite3_exec(database,str,NULL,NULL,NULL); + free(str); +} + +void db_close(void){ + sqlite3_close(database); +} + + +i64 db_create_user(const char *name,const char *pass){ + sqlite3_stmt *stmt; + SQLITE(prepare_v2,database,"insert into Users (username, pass) values (?, ?)",-1,&stmt,NULL); + SQLITE(bind_text,stmt,1,name,-1,SQLITE_STATIC); + SQLITE(bind_text,stmt,2,pass,-1,SQLITE_STATIC); + if(sqlite3_step(stmt)!=SQLITE_DONE)die_sqlite("sqlite3_step"); + SQLITE(finalize,stmt); + + i64 userid=sqlite3_last_insert_rowid(database); + + SQLITE(prepare_v2,database,"insert into UserNames (name, user) values (?, ?)",-1,&stmt,NULL); + SQLITE(bind_text,stmt,1,name,-1,SQLITE_STATIC); + SQLITE(bind_int64,stmt,2,userid); + if(sqlite3_step(stmt)!=SQLITE_DONE)die_sqlite("sqlite3_step"); + SQLITE(finalize,stmt); + + return userid; +} + +i64 db_find_user(const char *name){ + sqlite3_stmt *stmt; + SQLITE(prepare_v2,database,"select user from UserNames where name = ?",-1,&stmt,NULL); + SQLITE(bind_text,stmt,1,name,-1,SQLITE_STATIC); + i64 userid=-1; + if(sqlite3_step(stmt)==SQLITE_ROW){ + userid=sqlite3_column_int64(stmt,1); + } + SQLITE(finalize,stmt); + return userid; +} |