package model
|
|
import (
|
"apsClient/pkg/mysqlx"
|
"fmt"
|
"gorm.io/gorm"
|
)
|
|
type (
|
Device struct {
|
ID int `json:"id" gorm:"primaryKey;type:bigint(20);comment:设备ID"`
|
Name string `json:"name" gorm:"index;type:varchar(255);comment:设备名称"`
|
IP string `json:"IP" gorm:"index;type:varchar(255);comment:设备IP"`
|
Account string `json:"account" gorm:"index;type:varchar(255);comment:root账号"`
|
Password string `json:"password" gorm:"index;type:varchar(255);comment:root密码"`
|
Port string `json:"port" gorm:"index;type:varchar(255);comment:端口号"`
|
}
|
|
DeviceSearch struct {
|
Device
|
Order string
|
PageNum int
|
PageSize int
|
Orm *gorm.DB
|
}
|
)
|
|
func (slf Device) TableName() string {
|
return "device"
|
}
|
|
func NewDeviceSearch(db *gorm.DB) *DeviceSearch {
|
if db == nil {
|
db = mysqlx.GetDB()
|
}
|
return &DeviceSearch{Orm: db}
|
}
|
|
func (slf *DeviceSearch) SetDeviceName(name string) *DeviceSearch {
|
slf.Name = name
|
return slf
|
}
|
|
func (slf *DeviceSearch) SetDeviceIp(ip string) *DeviceSearch {
|
slf.IP = ip
|
return slf
|
}
|
|
func (slf *DeviceSearch) First() (*Device, error) {
|
var (
|
record = new(Device)
|
db = slf.build()
|
)
|
|
if err := db.First(record).Error; err != nil {
|
return record, err
|
}
|
|
return record, nil
|
}
|
|
func (slf *DeviceSearch) SetPage(page, size int) *DeviceSearch {
|
slf.PageNum, slf.PageSize = page, size
|
return slf
|
}
|
|
func (slf *DeviceSearch) SetOrder(order string) *DeviceSearch {
|
slf.Order = order
|
return slf
|
}
|
|
func (slf *DeviceSearch) Find() ([]*Device, int64, error) {
|
var (
|
records = make([]*Device, 0)
|
total int64
|
db = slf.build()
|
)
|
|
if err := db.Count(&total).Error; err != nil {
|
return records, total, fmt.Errorf("find count err: %v", err)
|
}
|
|
if slf.PageNum*slf.PageSize > 0 {
|
db = db.Offset((slf.PageNum - 1) * slf.PageSize).Limit(slf.PageSize)
|
}
|
|
if err := db.Find(&records).Error; err != nil {
|
return records, total, fmt.Errorf("find records err: %v", err)
|
}
|
|
return records, total, nil
|
}
|
|
func (slf *DeviceSearch) build() *gorm.DB {
|
var db = slf.Orm.Model(&Device{})
|
|
if slf.ID > 0 {
|
db = db.Where("id = ?", slf.ID)
|
}
|
|
if slf.IP != "" {
|
db = db.Where("ip = ?", slf.IP)
|
}
|
|
if slf.Account != "" {
|
db = db.Where("account = ?", slf.Account)
|
}
|
|
if slf.Password != "" {
|
db = db.Where("password = ?", slf.Password)
|
}
|
|
if slf.Port != "" {
|
db = db.Where("port = ?", slf.Port)
|
}
|
|
return db
|
}
|
|
func (slf *DeviceSearch) Create(record *Device) error {
|
var db = slf.build()
|
|
if err := db.Create(record).Error; err != nil {
|
return fmt.Errorf("create err: %v, record: %+v", err, record)
|
}
|
|
return nil
|
}
|
|
func (slf *DeviceSearch) SetId(id int) *DeviceSearch {
|
slf.ID = id
|
return slf
|
}
|
|
func (slf *DeviceSearch) SetIds(ids []int) *DeviceSearch {
|
slf.Orm = slf.Orm.Where("id in (?)", ids)
|
return slf
|
}
|