2021-09-11 19:50:34 +01:00
|
|
|
package store
|
|
|
|
|
|
|
|
import (
|
|
|
|
"database/sql"
|
|
|
|
"fmt"
|
|
|
|
"strings"
|
|
|
|
|
|
|
|
_ "github.com/mattn/go-sqlite3"
|
|
|
|
)
|
|
|
|
|
|
|
|
type Store struct {
|
|
|
|
Path string
|
|
|
|
Conn *sql.DB
|
2021-09-11 20:38:38 +01:00
|
|
|
|
|
|
|
userStore *UserStore
|
2021-09-11 19:50:34 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
func addPathOptions(path string) string {
|
|
|
|
if !strings.HasPrefix(path, ":memory:") {
|
|
|
|
path = "file:" + path
|
|
|
|
}
|
|
|
|
return fmt.Sprintf("%s?_foreign_keys=true", path)
|
|
|
|
}
|
|
|
|
|
|
|
|
func NewStore(path string) (*Store, error) {
|
|
|
|
s := &Store{Path: path}
|
|
|
|
|
2021-09-11 23:32:07 +01:00
|
|
|
// ToDo: should do this at start time instead of create time?
|
2021-09-11 19:50:34 +01:00
|
|
|
conn, err := sql.Open("sqlite3", addPathOptions(path))
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2021-09-11 22:50:53 +01:00
|
|
|
s.Conn = conn
|
2021-09-11 19:50:34 +01:00
|
|
|
|
|
|
|
if err := s.EnsureSchema(); err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
2021-09-11 22:50:53 +01:00
|
|
|
// init stores
|
2021-09-11 20:38:38 +01:00
|
|
|
s.userStore = NewUserStore(s)
|
|
|
|
|
2021-09-11 19:50:34 +01:00
|
|
|
return s, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *Store) Close() error {
|
|
|
|
return s.Conn.Close()
|
|
|
|
}
|
|
|
|
|
2021-09-11 20:38:38 +01:00
|
|
|
func (s *Store) User() *UserStore {
|
|
|
|
return s.userStore
|
|
|
|
}
|
|
|
|
|
2021-09-11 19:50:34 +01:00
|
|
|
func (s *Store) EnsureSchema() error {
|
|
|
|
schema := `
|
|
|
|
CREATE TABLE IF NOT EXISTS users (
|
|
|
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
|
|
name VARCHAR(255) NOT NULL,
|
|
|
|
mail VARCHAR(255) UNIQUE NOT NULL,
|
|
|
|
username VARCHAR(255) UNIQUE NOT NULL,
|
|
|
|
password VARCHAR(255) NOT NULL
|
|
|
|
);
|
|
|
|
|
|
|
|
CREATE TABLE IF NOT EXISTS game (
|
|
|
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
|
|
user_id INTEGER NOT NULL,
|
|
|
|
name VARCHAR(255) NOT NULL
|
|
|
|
);
|
|
|
|
|
|
|
|
CREATE TABLE IF NOT EXISTS gamemember (
|
|
|
|
game_id INTEGER NOT NULL,
|
|
|
|
user_id INTEGER NOT NULL,
|
|
|
|
role VARCHAR(255) NOT NULL,
|
|
|
|
|
|
|
|
PRIMARY KEY (game_id, user_id)
|
|
|
|
);
|
|
|
|
`
|
|
|
|
|
|
|
|
_, err := s.Conn.Exec(schema)
|
|
|
|
return err
|
|
|
|
}
|