1
0
mirror of https://github.com/pocketbase/pocketbase.git synced 2025-03-19 14:17:48 +02:00
pocketbase/core/log_query.go

66 lines
1.6 KiB
Go
Raw Normal View History

2024-09-29 19:23:19 +03:00
package core
2023-11-26 13:33:17 +02:00
import (
"time"
"github.com/pocketbase/dbx"
"github.com/pocketbase/pocketbase/tools/types"
)
// LogQuery returns a new Log select query.
2024-09-29 19:23:19 +03:00
func (app *BaseApp) LogQuery() *dbx.SelectQuery {
return app.AuxModelQuery(&Log{})
2023-11-26 13:33:17 +02:00
}
// FindLogById finds a single Log entry by its id.
2024-09-29 19:23:19 +03:00
func (app *BaseApp) FindLogById(id string) (*Log, error) {
model := &Log{}
2023-11-26 13:33:17 +02:00
2024-09-29 19:23:19 +03:00
err := app.LogQuery().
2023-11-26 13:33:17 +02:00
AndWhere(dbx.HashExp{"id": id}).
Limit(1).
One(model)
if err != nil {
return nil, err
}
return model, nil
}
2024-09-29 19:23:19 +03:00
// LogsStatsItem defines the total number of logs for a specific time period.
2023-11-26 13:33:17 +02:00
type LogsStatsItem struct {
Date types.DateTime `db:"date" json:"date"`
2024-09-29 19:23:19 +03:00
Total int `db:"total" json:"total"`
2023-11-26 13:33:17 +02:00
}
// LogsStats returns hourly grouped requests logs statistics.
2024-09-29 19:23:19 +03:00
func (app *BaseApp) LogsStats(expr dbx.Expression) ([]*LogsStatsItem, error) {
2023-11-26 13:33:17 +02:00
result := []*LogsStatsItem{}
2024-09-29 19:23:19 +03:00
query := app.LogQuery().
2023-11-26 13:33:17 +02:00
Select("count(id) as total", "strftime('%Y-%m-%d %H:00:00', created) as date").
GroupBy("date")
if expr != nil {
query.AndWhere(expr)
}
err := query.All(&result)
return result, err
}
// DeleteOldLogs delete all requests that are created before createdBefore.
//
// For better performance the logs delete is executed as plain SQL statement,
// aka. no delete model hook events will be fired.
2024-09-29 19:23:19 +03:00
func (app *BaseApp) DeleteOldLogs(createdBefore time.Time) error {
2023-11-26 13:33:17 +02:00
formattedDate := createdBefore.UTC().Format(types.DefaultDateLayout)
expr := dbx.NewExp("[[created]] <= {:date}", dbx.Params{"date": formattedDate})
2024-09-29 19:23:19 +03:00
_, err := app.auxNonconcurrentDB.Delete((&Log{}).TableName(), expr).Execute()
2023-11-26 13:33:17 +02:00
return err
}