91 lines
2.4 KiB
Go
91 lines
2.4 KiB
Go
package repository
|
|
|
|
import (
|
|
"encoding/json"
|
|
"u-desk/internal/storage"
|
|
"u-desk/internal/storage/models"
|
|
"gorm.io/gorm"
|
|
)
|
|
|
|
type ResultRepository interface {
|
|
Save(connectionID uint, database, sql string, resultType string, data interface{}, columns []string, rowsAffected int, executionTime int64) (*models.SqlResultHistory, error)
|
|
FindByID(id uint) (*models.SqlResultHistory, error)
|
|
Search(connectionID *uint, keyword string, limit, offset int) ([]models.SqlResultHistory, int64, error)
|
|
Delete(id uint) error
|
|
}
|
|
|
|
type resultRepository struct {
|
|
db *gorm.DB
|
|
}
|
|
|
|
func NewResultRepository() (ResultRepository, error) {
|
|
db := storage.GetDB()
|
|
if db == nil {
|
|
var err error
|
|
db, err = storage.Init()
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
}
|
|
return &resultRepository{db}, nil
|
|
}
|
|
|
|
func (r *resultRepository) Save(connectionID uint, database, sql string, resultType string, data interface{}, columns []string, rowsAffected int, executionTime int64) (*models.SqlResultHistory, error) {
|
|
dataJSON, _ := json.Marshal(data)
|
|
columnsJSON, _ := json.Marshal(columns)
|
|
|
|
history := &models.SqlResultHistory{
|
|
ConnectionID: connectionID,
|
|
Database: database,
|
|
Sql: sql,
|
|
Type: resultType,
|
|
Data: string(dataJSON),
|
|
Columns: string(columnsJSON),
|
|
RowsAffected: rowsAffected,
|
|
ExecutionTime: executionTime,
|
|
}
|
|
|
|
return history, r.db.Create(history).Error
|
|
}
|
|
|
|
func (r *resultRepository) FindByID(id uint) (*models.SqlResultHistory, error) {
|
|
var history models.SqlResultHistory
|
|
err := r.db.First(&history, id).Error
|
|
if err == gorm.ErrRecordNotFound {
|
|
return nil, nil
|
|
}
|
|
return &history, err
|
|
}
|
|
|
|
func (r *resultRepository) Search(connectionID *uint, keyword string, limit, offset int) ([]models.SqlResultHistory, int64, error) {
|
|
query := r.db.Model(&models.SqlResultHistory{})
|
|
|
|
if connectionID != nil {
|
|
query = query.Where("connection_id = ?", *connectionID)
|
|
}
|
|
if keyword != "" {
|
|
query = query.Where("sql LIKE ? OR database LIKE ?", "%"+keyword+"%", "%"+keyword+"%")
|
|
}
|
|
|
|
var total int64
|
|
if err := query.Count(&total).Error; err != nil {
|
|
return nil, 0, err
|
|
}
|
|
|
|
var histories []models.SqlResultHistory
|
|
query = query.Order("created_at DESC")
|
|
if limit > 0 {
|
|
query = query.Limit(limit)
|
|
}
|
|
if offset > 0 {
|
|
query = query.Offset(offset)
|
|
}
|
|
|
|
return histories, total, query.Find(&histories).Error
|
|
}
|
|
|
|
func (r *resultRepository) Delete(id uint) error {
|
|
return r.db.Delete(&models.SqlResultHistory{}, id).Error
|
|
}
|
|
|