@@ -2,6 +2,7 @@ package store
22
33import (
44 "os"
5+ "time"
56
67 "github.com/denisbrodbeck/machineid"
78 "github.com/flarco/g"
@@ -48,6 +49,7 @@ func InitDB() {
4849
4950 allTables := []interface {}{
5051 & Setting {},
52+ & QueryHistory {},
5153 }
5254
5355 for _ , table := range allTables {
@@ -95,3 +97,52 @@ func GetMachineID() string {
9597 Db .First (& s )
9698 return s .Value
9799}
100+
101+ // QueryHistory stores executed query history entries
102+ type QueryHistory struct {
103+ ID uint `json:"id" gorm:"primaryKey;autoIncrement"`
104+ WorkspaceKey * string `json:"workspace_key" gorm:"index"`
105+ Connection string `json:"connection"`
106+ Query string `json:"query"`
107+ Status string `json:"status"`
108+ DurationMs int64 `json:"duration_ms"`
109+ RowCount int `json:"row_count"`
110+ ErrorMessage string `json:"error_message,omitempty"`
111+ CreatedAt time.Time `json:"created_at" gorm:"autoCreateTime;index"`
112+ }
113+
114+ // SaveQueryHistory persists a query history entry
115+ func SaveQueryHistory (entry * QueryHistory ) error {
116+ if Db == nil {
117+ return nil
118+ }
119+ return Db .Create (entry ).Error
120+ }
121+
122+ // GetQueryHistory retrieves query history entries filtered by workspace key
123+ func GetQueryHistory (workspaceKey * string , limit , offset int ) (entries []QueryHistory , total int64 , err error ) {
124+ if Db == nil {
125+ return nil , 0 , nil
126+ }
127+
128+ q := Db .Model (& QueryHistory {})
129+ if workspaceKey == nil {
130+ q = q .Where ("workspace_key IS NULL" )
131+ } else {
132+ q = q .Where ("workspace_key = ?" , * workspaceKey )
133+ }
134+
135+ if err = q .Count (& total ).Error ; err != nil {
136+ return nil , 0 , g .Error (err , "could not count query history" )
137+ }
138+
139+ if limit <= 0 {
140+ limit = 50
141+ }
142+
143+ if err = q .Order ("created_at DESC" ).Limit (limit ).Offset (offset ).Find (& entries ).Error ; err != nil {
144+ return nil , 0 , g .Error (err , "could not get query history" )
145+ }
146+
147+ return entries , total , nil
148+ }
0 commit comments