You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
diary/model/model.go

84 lines
1.7 KiB

/// Defines objects that interact with the db
package model
import (
"database/sql"
"isthisnagee.com/tools/diary/db"
"log"
)
type DiaryEntry struct {
Id int `json:"id"`
Title string `json:"title"`
CreatedAt int `json:"created_at"`
Version int `json:"version"`
}
type App struct {
*db.DbCtx
}
func NewApp(db_path string) App {
app, err := db.Init(db_path)
if err != nil {
log.Fatal(err.Error())
}
return App{app}
}
func (app *App) NewDiaryEntry(title string) *DiaryEntry {
var diary_entry DiaryEntry
var result, err = app.Db.Exec("INSERT INTO diary_log (title) values (?);", title)
if err != nil {
panic(err)
}
id, err := result.LastInsertId()
if err != nil {
panic(err)
}
if err := app.Db.QueryRow(
"SELECT id, title, created_at, version FROM diary_log where id=?",
id,
).Scan(&diary_entry.Id, &diary_entry.Title, &diary_entry.CreatedAt, &diary_entry.Version); err != nil {
panic(err)
}
return &diary_entry
}
func (app *App) GetDiaryEntry(id int) (*DiaryEntry, error) {
var diary_entry DiaryEntry
if err := app.Db.QueryRow(
"SELECT id, title, created_at, version FROM diary_log where id=?",
id,
).Scan(&diary_entry.Id, &diary_entry.Title, &diary_entry.CreatedAt, &diary_entry.Version); err != nil {
if err == sql.ErrNoRows {
return nil, &NotFoundError{given_id: id}
}
return nil, err
}
return &diary_entry, nil
}
func (app *App) DeleteDiaryEntry(id int) (bool, error) {
result, err := app.Db.Exec("DELETE FROM diary_log where id=?", id)
if err != nil {
return false, err
}
num_rows_affected, err := result.RowsAffected()
if err != nil {
return false, err
}
if num_rows_affected == 0 {
return false, &NotFoundError{given_id: id}
}
return true, nil
}