memos/store/query.go
2021-12-09 22:02:57 +08:00

100 lines
2.8 KiB
Go

package store
import (
"memos/common"
"strings"
)
type Query struct {
Id string `json:"id"`
UserId string `json:"userId"`
Title string `json:"title"`
Querystring string `json:"querystring"`
PinnedAt string `json:"pinnedAt"`
CreatedAt string `json:"createdAt"`
UpdatedAt string `json:"updatedAt"`
}
func CreateNewQuery(title string, querystring string, userId string) (Query, error) {
nowDateTimeStr := common.GetNowDateTimeStr()
newQuery := Query{
Id: common.GenUUID(),
Title: title,
Querystring: querystring,
UserId: userId,
PinnedAt: "",
CreatedAt: nowDateTimeStr,
UpdatedAt: nowDateTimeStr,
}
query := `INSERT INTO queries (id, title, querystring, user_id, pinned_at, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?)`
_, err := DB.Exec(query, newQuery.Id, newQuery.Title, newQuery.Querystring, newQuery.UserId, newQuery.PinnedAt, newQuery.CreatedAt, newQuery.UpdatedAt)
return newQuery, err
}
type QueryPatch struct {
Title *string
Querystring *string
PinnedAt *string
}
func UpdateQuery(id string, queryPatch *QueryPatch) (Query, error) {
query, _ := GetQueryById(id)
set, args := []string{}, []interface{}{}
if v := queryPatch.Title; v != nil {
query.Title = *v
set, args = append(set, "title=?"), append(args, *v)
}
if v := queryPatch.Querystring; v != nil {
query.Querystring = *v
set, args = append(set, "querystring=?"), append(args, *v)
}
if v := queryPatch.PinnedAt; v != nil {
query.PinnedAt = *v
set, args = append(set, "pinned_at=?"), append(args, *v)
}
set, args = append(set, "updated_at=?"), append(args, common.GetNowDateTimeStr())
args = append(args, id)
sqlQuery := `UPDATE queries SET ` + strings.Join(set, ",") + ` WHERE id=?`
_, err := DB.Exec(sqlQuery, args...)
return query, err
}
func DeleteQuery(queryId string) (error, error) {
query := `DELETE FROM queries WHERE id=?`
_, err := DB.Exec(query, queryId)
return nil, err
}
func GetQueryById(queryId string) (Query, error) {
sqlQuery := `SELECT id, title, querystring, user_id, pinned_at, created_at, updated_at FROM queries WHERE id=?`
query := Query{}
err := DB.QueryRow(sqlQuery, queryId).Scan(&query.Id, &query.Title, &query.Querystring, &query.UserId, &query.PinnedAt, &query.CreatedAt, &query.UpdatedAt)
return query, err
}
func GetQueriesByUserId(userId string) ([]Query, error) {
query := `SELECT id, title, querystring, user_id, pinned_at, created_at, updated_at FROM queries WHERE user_id=?`
rows, _ := DB.Query(query, userId)
defer rows.Close()
queries := []Query{}
for rows.Next() {
query := Query{}
rows.Scan(&query.Id, &query.Title, &query.Querystring, &query.UserId, &query.PinnedAt, &query.CreatedAt, &query.UpdatedAt)
queries = append(queries, query)
}
err := rows.Err()
return queries, err
}