diff options
author | Andinus <andinus@nand.sh> | 2020-03-26 20:32:30 +0530 |
---|---|---|
committer | Andinus <andinus@nand.sh> | 2020-03-26 20:32:30 +0530 |
commit | 80c9e876b0ed1a5fb84e31cb06837466c006fa9e (patch) | |
tree | 2e797560370c1a0c37d22c46acb55e34dba39627 /storage | |
parent | 221601b8ba64bad10d84f891d4e8dd7f40a6d799 (diff) | |
download | perseus-80c9e876b0ed1a5fb84e31cb06837466c006fa9e.tar.gz |
Add storage & sqlite3 package
Diffstat (limited to 'storage')
-rw-r--r-- | storage/sqlite3/init.go | 74 | ||||
-rw-r--r-- | storage/storage.go | 17 |
2 files changed, 91 insertions, 0 deletions
diff --git a/storage/sqlite3/init.go b/storage/sqlite3/init.go new file mode 100644 index 0000000..d199031 --- /dev/null +++ b/storage/sqlite3/init.go @@ -0,0 +1,74 @@ +package sqlite3 + +import ( + "database/sql" + "fmt" + "log" + "os" + "sync" + + _ "github.com/mattn/go-sqlite3" +) + +// DB holds the database connection, mutex & path. +type DB struct { + Path string + Mu *sync.RWMutex + Conn *sql.DB +} + +// initErr will log the error and close the database connection if +// necessary. +func initErr(db *DB, err error) { + if db.Conn != nil { + db.Conn.Close() + } + log.Fatalf("Initialization Error :: %s", err.Error()) +} + +// Init initializes a sqlite3 database. +func Init(db *DB) { + var err error + + // We set the database path, first the environment variable + // PERSEUS_DBPATH is checked. If it doesn't exist then use set + // it to the default (perseus.db). + envDBPath, exists := os.LookupEnv("PERSEUS_DBPATH") + if !exists { + envDBPath = "perseus.db" + } + db.Path = envDBPath + + db.Conn, err = sql.Open("sqlite3", db.Path) + if err != nil { + log.Printf("sqlite3/init.go: %s\n", + "Failed to open database connection") + initErr(db, err) + } + + // Create account table, this will hold information on account + // like id, type & other user specific information. We are + // using id because later we may want to add username change + // or account delete functionality. If we add user delete + // function then we'll just have to change the username here. + stmt, err := db.Conn.Prepare(` +CREATE TABLE IF NOT EXISTS account ( + id TEXT PRIMARY KEY, + type TEXT NOT NULL DEFAULT user, + username TEXT NOT NULL, + password TEXT NOT NULL);`) + + if err != nil { + log.Printf("sqlite3/init.go: %s\n", + "Failed to prepare statement") + initErr(db, err) + } + + _, err = stmt.Exec() + stmt.Close() + if err != nil { + log.Printf("sqlite3/init.go: %s\n", + "Failed to execute statement") + initErr(db, err) + } +} diff --git a/storage/storage.go b/storage/storage.go new file mode 100644 index 0000000..24f770d --- /dev/null +++ b/storage/storage.go @@ -0,0 +1,17 @@ +package storage + +import ( + "sync" + + "tildegit.org/andinus/perseus/storage/sqlite3" +) + +// Init initializes the database. +func Init() *sqlite3.DB { + var db sqlite3.DB = sqlite3.DB{ + Mu: new(sync.RWMutex), + } + + sqlite3.Init(&db) + return &db +} |