60 lines
1.4 KiB
Go
60 lines
1.4 KiB
Go
package db
|
|
|
|
import (
|
|
"JISQueueing/common"
|
|
"database/sql"
|
|
|
|
// Import the SQLite library we're going to use so SQL can use it.
|
|
_ "github.com/mattn/go-sqlite3"
|
|
)
|
|
|
|
var db *sql.DB
|
|
var alreadyUsingMemory bool
|
|
|
|
func Init_DB(config common.Configuration) {
|
|
openDatabase(config.Database)
|
|
}
|
|
|
|
func openDatabase(fileLocation string) {
|
|
db, _ = sql.Open("sqlite3", fileLocation)
|
|
db.SetMaxOpenConns(1)
|
|
|
|
// Initializes the tables
|
|
db.Exec(`CREATE TABLE IF NOT EXISTS tickets (
|
|
id INTEGER NOT NULL UNIQUE PRIMARY KEY AUTOINCREMENT,
|
|
email TEXT NOT NULL,
|
|
name TEXT NOT NULL,
|
|
staff TEXT NOT NULL,
|
|
time_start DATE NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
|
time_end DATE)`)
|
|
|
|
db.Exec(`CREATE TABLE IF NOT EXISTS clients (
|
|
email TEXT NOT NULL UNIQUE PRIMARY KEY,
|
|
name TEXT NOT NULL,
|
|
first_ticket INT NOT NULL)`)
|
|
|
|
db.Exec(`CREATE TABLE IF NOT EXISTS staff (
|
|
username TEXT NOT NULL UNIQUE PRIMARY KEY,
|
|
password TEXT NOT NULL,
|
|
name TEXT NOT NULL,
|
|
email TEXT NOT NULL,
|
|
admin BIT NOT NULL)`)
|
|
}
|
|
|
|
//UseInMemoryDatabase requests DB to be ran in memory instead of a file which can be useful during testing.
|
|
//Creates a (seemingly) new DB every time by dropping all tables.
|
|
func UseInMemoryDatabase() {
|
|
if db != nil {
|
|
if alreadyUsingMemory {
|
|
dropAllTables()
|
|
}
|
|
db.Close()
|
|
}
|
|
openDatabase("file::memory:?cache=shared")
|
|
alreadyUsingMemory = true
|
|
}
|
|
|
|
func dropAllTables() {
|
|
db.Exec("DROP TABLE tickets; DROP TABLE clients; DROP TABLE staff;")
|
|
}
|