1
0

Implemented mindflow DB.

This commit is contained in:
Alexander Andreev 2023-05-14 03:35:52 +04:00
parent 8fd83a664c
commit b56de7f5ca
Signed by: Arav
GPG Key ID: D22A817D95815393

View File

@ -4,7 +4,9 @@ import (
"database/sql" "database/sql"
_ "embed" _ "embed"
"fmt" "fmt"
"time"
"git.arav.su/Arav/dwelling-home/pkg/mindflow"
"github.com/pkg/errors" "github.com/pkg/errors"
) )
@ -22,6 +24,8 @@ var (
queryPostNew string queryPostNew string
//go:embed queries/postEdit.sql //go:embed queries/postEdit.sql
queryPostEdit string queryPostEdit string
//go:embed queries/postDelete.sql
queryPostDelete string
) )
var ( var (
@ -30,6 +34,7 @@ var (
stmtPostGetAll *sql.Stmt stmtPostGetAll *sql.Stmt
stmtPostNew *sql.Stmt stmtPostNew *sql.Stmt
stmtPostEdit *sql.Stmt stmtPostEdit *sql.Stmt
stmtPostDelete *sql.Stmt
) )
func initDBStatements(db *sql.DB) error { func initDBStatements(db *sql.DB) error {
@ -65,6 +70,11 @@ func initDBStatements(db *sql.DB) error {
return errors.Wrap(err, "failed to prepare queryPostEdit") return errors.Wrap(err, "failed to prepare queryPostEdit")
} }
stmtPostDelete, err = db.Prepare(queryPostDelete)
if err != nil {
return errors.Wrap(err, "failed to prepare queryPostDelete")
}
return nil return nil
} }
@ -88,3 +98,87 @@ func NewSQLiteMindflow(path string) (*SQLiteMindflow, error) {
func dsn(filePath string) string { func dsn(filePath string) string {
return fmt.Sprintf("file:%s?_journal=WAL&_mutex=full", filePath) return fmt.Sprintf("file:%s?_journal=WAL&_mutex=full", filePath)
} }
func (s *SQLiteMindflow) New(post *mindflow.Post) error {
tx, err := s.db.Begin()
if err != nil {
return err
}
defer tx.Rollback()
r, err := tx.Stmt(stmtPostNew).Exec(post.Category.ID, post.Date.UTC().Unix(), post.Title, post.Body)
if err != nil {
return err
}
post.ID, err = r.LastInsertId()
if err != nil {
return err
}
tx.Commit()
return nil
}
func (s *SQLiteMindflow) Edit(post mindflow.Post) error {
tx, err := s.db.Begin()
if err != nil {
return err
}
defer tx.Rollback()
_, err = tx.Stmt(stmtPostEdit).Exec(post.Category.ID, post.Title, post.Body, post.ID)
if err != nil {
return err
}
tx.Commit()
return nil
}
func (s *SQLiteMindflow) Delete(id int64) error {
tx, err := s.db.Begin()
if err != nil {
return err
}
defer tx.Rollback()
if _, err = tx.Stmt(stmtPostDelete).Exec(id); err != nil {
return err
}
tx.Commit()
return nil
}
func (s *SQLiteMindflow) GetAll() (posts []mindflow.Post, err error) {
tx, err := s.db.Begin()
if err != nil {
return nil, err
}
rows, err := tx.Stmt(stmtPostGetAll).Query()
if err != nil {
return nil, err
}
defer rows.Close()
for rows.Next() {
var post mindflow.Post
var date_unix int64
if err = rows.Scan(&post.ID, &post.Category.ID, &post.Category.Name, &date_unix, &post.Title, &post.Body); err != nil {
return nil, err
}
post.Date = time.Unix(date_unix, 0)
posts = append(posts, post)
}
defer tx.Rollback()
return nil, nil
}