85 lines
2.0 KiB
Go
85 lines
2.0 KiB
Go
package db
|
|
|
|
import "github.com/jmoiron/sqlx"
|
|
|
|
type Database struct {
|
|
*sqlx.DB
|
|
}
|
|
|
|
func New(path string) (*Database, error) {
|
|
d, err := sqlx.Open("sqlite3", path)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return &Database{d}, nil
|
|
}
|
|
|
|
func (d *Database) MakeDB() error {
|
|
q := `create table if not exists users (
|
|
id integer primary key,
|
|
email text unique,
|
|
verification integer not null,
|
|
dateCreated integer,
|
|
lastLogin integer
|
|
)`
|
|
if _, err := d.Exec(q); err != nil {
|
|
return err
|
|
}
|
|
q = `create table if not exists mood_categories (
|
|
id integer primary key,
|
|
name text
|
|
)`
|
|
if _, err := d.Exec(q); err != nil {
|
|
return err
|
|
}
|
|
q = `create table if not exists mood_category_texts (
|
|
id integer primary key,
|
|
mood_category_id integer,
|
|
key text,
|
|
value integer,
|
|
foreign key(mood_category_id) references mood_categories(id)
|
|
|
|
)`
|
|
if _, err := d.Exec(q); err != nil {
|
|
return err
|
|
}
|
|
q = `create table if not exists moods (
|
|
id integer primary key,
|
|
user_id integer,
|
|
mood_category_id integer,
|
|
value integer,
|
|
time integer,
|
|
foreign key(user_id) references users(id),
|
|
foreign key(mood_category_id) references mood_categories(id)
|
|
)`
|
|
if _, err := d.Exec(q); err != nil {
|
|
return err
|
|
}
|
|
q = `select count(*) from mood_category_texts mct inner join mood_categories mc on mct.mood_category_id=mc.id`
|
|
var count int
|
|
if err := d.Get(&count, q); err != nil {
|
|
return err
|
|
}
|
|
if count == 0 {
|
|
return d.populateMoods()
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (d *Database) populateMoods() error {
|
|
tx := d.MustBegin()
|
|
res := tx.MustExec(`insert into mood_categories (name) values ('happy')`)
|
|
id, err := res.LastInsertId()
|
|
if err != nil {
|
|
tx.Rollback()
|
|
return err
|
|
}
|
|
tx.MustExec(`insert into mood_category_texts (mood_category_id,key,value) values (?,?,?)`,
|
|
id, "😄", 1)
|
|
tx.MustExec(`insert into mood_category_texts (mood_category_id,key,value) values (?,?,?)`,
|
|
id, "😐", 0)
|
|
tx.MustExec(`insert into mood_category_texts (mood_category_id,key,value) values (?,?,?)`,
|
|
id, "😟", -1)
|
|
return tx.Commit()
|
|
}
|