diff --git a/pkg/mindflow/database/sqlite/db.go b/pkg/mindflow/database/sqlite/db.go index 359447b..3c5a130 100644 --- a/pkg/mindflow/database/sqlite/db.go +++ b/pkg/mindflow/database/sqlite/db.go @@ -16,6 +16,8 @@ var ( //go:embed queries/categoryById.sql queryCategoryById string + //go:embed queries/categoryGetAll.sql + queryCategoryGetAll string //go:embed queries/categoryNew.sql queryCategoryNew string //go:embed queries/postGetAll.sql @@ -29,12 +31,13 @@ var ( ) var ( - stmtCategoryById *sql.Stmt - stmtCategoryNew *sql.Stmt - stmtPostGetAll *sql.Stmt - stmtPostNew *sql.Stmt - stmtPostEdit *sql.Stmt - stmtPostDelete *sql.Stmt + stmtCategoryById *sql.Stmt + stmtCategoryGetAll *sql.Stmt + stmtCategoryNew *sql.Stmt + stmtPostGetAll *sql.Stmt + stmtPostNew *sql.Stmt + stmtPostEdit *sql.Stmt + stmtPostDelete *sql.Stmt ) func initDBStatements(db *sql.DB) error { @@ -50,6 +53,11 @@ func initDBStatements(db *sql.DB) error { return errors.Wrap(err, "failed to prepare queryCategoryById") } + stmtCategoryGetAll, err = db.Prepare(queryCategoryGetAll) + if err != nil { + return errors.Wrap(err, "failed to prepare queryCategoryGetAll") + } + stmtCategoryNew, err = db.Prepare(queryCategoryNew) if err != nil { return errors.Wrap(err, "failed to prepare queryCategoryNew") @@ -185,6 +193,34 @@ func (s *SQLiteMindflow) Posts() (posts []mindflow.Post, err error) { return posts, nil } +func (s *SQLiteMindflow) Categories() (categories []mindflow.Category, err error) { + tx, err := s.db.Begin() + if err != nil { + return nil, err + } + defer tx.Rollback() + + rows, err := tx.Stmt(stmtCategoryGetAll).Query() + if err != nil { + return nil, err + } + defer rows.Close() + + for rows.Next() { + var category mindflow.Category + + if err = rows.Scan(&category.ID, &category.Name); err != nil { + return nil, err + } + + categories = append(categories, category) + } + + tx.Commit() + + return categories, nil +} + func (s *SQLiteMindflow) NewCategory(name string) (int64, error) { tx, err := s.db.Begin() if err != nil { diff --git a/pkg/mindflow/database/sqlite/queries/categoryGetAll.sql b/pkg/mindflow/database/sqlite/queries/categoryGetAll.sql new file mode 100644 index 0000000..d92a7cf --- /dev/null +++ b/pkg/mindflow/database/sqlite/queries/categoryGetAll.sql @@ -0,0 +1,4 @@ +SELECT + `category_id`, + `name` + FROM `category`; \ No newline at end of file diff --git a/pkg/mindflow/mindflow.go b/pkg/mindflow/mindflow.go index 5f7cdeb..712e02c 100644 --- a/pkg/mindflow/mindflow.go +++ b/pkg/mindflow/mindflow.go @@ -5,6 +5,7 @@ type Mindflow interface { Edit(post *Post) error Delete(id int64) error Posts() ([]Post, error) + Categories() ([]Category, error) NewCategory(name string) (int64, error) GetCategoryByID(id int64) (string, error) Close() error