62 lines
1.3 KiB
Go
62 lines
1.3 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 tags (
|
||
|
id integer primary key,
|
||
|
tag text,
|
||
|
)`
|
||
|
if _, err := d.Exec(q); err != nil {
|
||
|
return err
|
||
|
}
|
||
|
q = `select count(*) from tags`
|
||
|
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()
|
||
|
}
|