migration to chi

This commit is contained in:
2025-03-12 16:30:40 +03:00
parent ae81fbcce9
commit 45bb32e7a6
46 changed files with 1352 additions and 1323 deletions
+51
View File
@@ -0,0 +1,51 @@
package database
import (
"time"
)
type Post struct {
ID uint16 `json:"id"`
Title string `json:"title"`
ShortPost string `json:"short_post" db:"short_post"`
FullPost string `json:"full_post" db:"full_post"`
Date time.Time `json:"date"`
AuthorID uint64 `json:"author_id" db:"author_id" sql:"REFERENCES users(id)"`
Author string `json:"author"`
}
func FetchTotalNews() (int, error) {
count := 0
err := Database.Get(&count, `select count("news") from news;`)
return count, err
}
func FetchNews(offset, limit int) ([]Post, error) {
news := make([]Post, 0)
err := Database.Select(&news, "select news.*, u.username as author from news inner join users u on news.author_id = u.id offset $1 limit $2;", offset, limit)
return news, err
}
func CreatePost(post *Post) (*Post, error) {
destPost := new(Post)
r, err := Database.NamedQuery("insert into news (title, short_post, full_post, author_id) values (:title, :short_post, :full_post, :author_id) returning *;", post)
if err != nil {
return nil, err
}
if r.Next() {
err = r.StructScan(destPost)
}
return destPost, err
}
func FetchPost(id int) (*Post, error) {
post := &Post{}
err := Database.Get(post, "select news.*, u.username as author from news inner join users u on news.author_id = u.id where news.id = $1;", id)
return post, err
}
func UpdatePost(post *Post) error {
_, err := Database.NamedExec("update news set title=:title, short_post=:short_post, full_post=:full_post where id=:id;", post)
return err
}
func DeletePost(id int) error {
_, err := Database.Exec("delete from news where id=$1;", id)
return err
}