95 lines
2.2 KiB
Go
95 lines
2.2 KiB
Go
package database
|
|
|
|
import (
|
|
"TheAdversary/schema"
|
|
"database/sql"
|
|
"fmt"
|
|
)
|
|
|
|
type ArticleQueryOptions struct {
|
|
Name bool
|
|
Title bool
|
|
Summary bool
|
|
From int64
|
|
To int64
|
|
Limit int
|
|
}
|
|
|
|
func (db *Database) GetArticleByName(name string) (*schema.Article, error) {
|
|
article := &schema.Article{}
|
|
err := db.gormDB.Table("article").Where("name = ?", name).Scan(article).Error
|
|
if article.Added == 0 {
|
|
return nil, sql.ErrNoRows
|
|
}
|
|
return article, err
|
|
}
|
|
|
|
func (db *Database) GetArticles(query string, options ArticleQueryOptions) ([]*schema.Article, error) {
|
|
request := db.gormDB.Table("article")
|
|
var where bool
|
|
if options.Name {
|
|
if where {
|
|
request.Or("name LIKE ?", fmt.Sprintf("%%%s%%", query))
|
|
} else {
|
|
request.Where("name LIKE ?", fmt.Sprintf("%%%s%%", query))
|
|
where = true
|
|
}
|
|
}
|
|
if options.Title {
|
|
if where {
|
|
request.Or("title LIKE ?", fmt.Sprintf("%%%s%%", query))
|
|
} else {
|
|
request.Where("title LIKE ?", fmt.Sprintf("%%%s%%", query))
|
|
where = true
|
|
}
|
|
}
|
|
if options.Summary {
|
|
if where {
|
|
request.Or("summary LIKE ?", fmt.Sprintf("%%%s%%", query))
|
|
} else {
|
|
request.Where("summary LIKE ?", fmt.Sprintf("%%%s%%", query))
|
|
where = true
|
|
}
|
|
}
|
|
if !(options.From == 0 || options.To == 0) {
|
|
var from, to int64
|
|
if options.From != 0 {
|
|
from = options.From
|
|
}
|
|
if options.To != 0 {
|
|
to = options.To
|
|
}
|
|
request.Where("added BETWEEN ? AND ?", from, to)
|
|
}
|
|
if options.Limit > 0 {
|
|
request.Limit(options.Limit)
|
|
}
|
|
rows, err := request.Rows()
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
var articles []*schema.Article
|
|
for rows.Next() {
|
|
article := &schema.Article{}
|
|
if err = db.gormDB.ScanRows(rows, article); err != nil {
|
|
return nil, err
|
|
}
|
|
articles = append(articles, article)
|
|
}
|
|
|
|
return articles, nil
|
|
}
|
|
|
|
func (db *Database) AddArticle(article *schema.Article) error {
|
|
return db.gormDB.Table("article").Create(article).Error
|
|
}
|
|
|
|
func (db *Database) UpdateArticle(name string, article *schema.Article) error {
|
|
return db.gormDB.Table("article").Where("name = ?", name).Save(article).Error
|
|
}
|
|
|
|
func (db *Database) DeleteArticlesByNames(names ...string) error {
|
|
return db.gormDB.Table("article").Where("name IN (?)", names).Delete("*").Error
|
|
}
|