aboutsummaryrefslogblamecommitdiff
path: root/src/npassd/db.c
blob: f55bede6ee24f1b78cf8d474a70e05050816f596 (plain) (tree)
1
2
3
4
5
6
7
8
9








                                       
















                                                                     






















                                                                            
                                   





                                                                              
#include <errno.h>
#include <linux/limits.h>
#include <stdio.h>

#include "npassd/db.h"
#include "util.h"

#define DB_NAME "secret_service.sqlite"

const char sql_stmt_init[] =
	"CREATE TABLE IF NOT EXISTS collections ("
	"	id INTEGER PRIMARY KEY,"
	"	root TEXT NOT NULL UNIQUE,"
	"	label TEXT UNIQUE,"
	"	alias TEXT UNIQUE,"
	"	created INTEGER,"
	"	modified INTEGER"
	");"
	"CREATE TABLE IF NOT EXISTS collection_attrs ("
	"	id INTEGER PRIMARY KEY,"
	"	key TEXT NOT NULL,"
	"	value TEXT NOT NULL,"
	"	collectionid INTEGER,"
	"	UNIQUE(key, collectionid)"
	"	FOREIGN KEY(collectionid) REFERENCES collections(id)"
	");";

int db_init(const char *store_path, struct sqlite3 **db)
{
	char db_path[PATH_MAX];
	int ret;

	ret = snprintf(db_path, sizeof(db_path), "%s/" DB_NAME, store_path);
	if (ret < 0 || (size_t)ret > sizeof(db_path)) {
		print_err("Path exceeded PATH_MAX");
		return -ENAMETOOLONG;
	}

	ret = sqlite3_open_v2(db_path, db,
			      SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE |
				      SQLITE_OPEN_FULLMUTEX,
			      NULL);
	if (ret != SQLITE_OK) {
		print_err("Can't open database: %s", sqlite3_errmsg(*db));
		return -EPERM;
	}

	ret = sqlite3_exec(*db, sql_stmt_init, NULL, NULL, NULL);
	if (ret != SQLITE_OK) {
		sqlite3_close(*db);
		print_err("Failed to create tables: %s", sqlite3_errmsg(*db));
		return -EPERM;
	}

	return 0;
}