errs/errDS.go

97 lines
1.8 KiB
Go
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

//Запись в базу данных
package errs
import (
"fmt"
"os"
"strconv"
"strings"
"time"
"gorm.io/gorm"
)
var errDS *gorm.DB = nil
//Структура записи ошибки в датасторе
// 0.1.0
type ErrRec struct {
ID int64 `gorm:"primaryKey;autoIncrement:true"`
Time time.Time
Code ErrCode
Msg string
SrcLine string
SrcFunc string
Prev int64
}
//Инициализировать датасторе
// 0.1.0
func InitDS(ds *gorm.DB) *Err {
errDS = ds
if e := errDS.AutoMigrate(&ErrRec{}); e != nil {
return RaiseError(ErrDSError, e.Error())
}
return nil
}
//Произвести запись в датасторе
// 0.1.0
func storeDS(e *Err) *Err {
if errDS == nil {
return e
}
er := &ErrRec{
Time: time.Now(),
Code: e.Code,
Msg: e.Msg,
SrcLine: e.src.File + strconv.Itoa(e.src.Line),
SrcFunc: e.src.Func,
}
if e.Prev != nil {
er.Prev = e.Prev.dsId
}
if e := errDS.Create(&er).Error; e != nil {
//Error write to DS
fmt.Fprintln(os.Stderr, "Error write to DS: ", e.Error())
}
e.dsId = er.ID
return e
}
//Ответ со списком записей
// 0.1.0
type ErrRecs struct {
Total int64
Items []*ErrRec
}
//Получить список записей
// 0.1.1
func DSList(from, count int, filter ...string) *ErrRecs {
rsp := &ErrRecs{
Total: -1,
Items: make([]*ErrRec, 0),
}
tx := errDS.Model(&ErrRec{}).Order("time desc")
for _, f := range filter {
fa := strings.Split(f, ":")
switch fa[0] {
case "code":
tx = tx.Where("code = ?", fa[1])
case "date":
//
default:
//Unknown filter
}
}
if e := tx.Count(&rsp.Total).Error; e != nil {
RaiseError(ErrDSError, e.Error())
}
if e := tx.Offset(from).Limit(count).Find(&rsp.Items).Error; e != nil {
RaiseError(ErrDSError, e.Error())
return nil
}
return rsp
}