You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

79 lines
1.7 KiB

package mysql
import (
"context"
"git.aiterp.net/lucifer/new-server/models"
"github.com/jmoiron/sqlx"
)
type BridgeRepo struct {
DBX *sqlx.DB
}
func (b *BridgeRepo) Find(ctx context.Context, id int) (models.Bridge, error) {
var bridge models.Bridge
err := b.DBX.GetContext(ctx, &bridge, "SELECT * FROM bridge WHERE id = ?", id)
if err != nil {
return models.Bridge{}, dbErr(err)
}
return bridge, nil
}
func (b *BridgeRepo) FetchAll(ctx context.Context) ([]models.Bridge, error) {
bridges := make([]models.Bridge, 0, 8)
err := b.DBX.GetContext(ctx, &bridges, "SELECT * FROM bridge")
if err != nil {
return nil, dbErr(err)
}
return bridges, nil
}
func (b *BridgeRepo) Save(ctx context.Context, bridge *models.Bridge) error {
if bridge.ID > 0 {
_, err := b.DBX.ExecContext(
ctx,
"UPDATE bridge SET name = ?, address = ?, token = ? WHERE id = ?",
bridge.Name, bridge.Address, bridge.Token, bridge.ID,
)
if err != nil {
return dbErr(err)
}
} else {
rs, err := b.DBX.ExecContext(
ctx,
"INSERT INTO bridge (name, driver, address, token) VALUES (?, ?, ?, ?)",
bridge.Name, bridge.Driver, bridge.Address, bridge.Token,
)
if err != nil {
return dbErr(err)
}
id, err := rs.LastInsertId()
if err != nil {
return dbErr(err)
}
bridge.ID = int(id)
}
return nil
}
func (b *BridgeRepo) Delete(ctx context.Context, bridge *models.Bridge) error {
_, err := b.DBX.ExecContext(ctx, "DELETE FROM bridge WHERE id = ?", bridge.ID)
if err != nil {
return dbErr(err)
}
_, err = b.DBX.ExecContext(ctx, "DELETE FROM device WHERE bridge_id = ?", bridge.ID)
if err != nil {
return dbErr(err)
}
bridge.ID = 0
return nil
}