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

4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
  1. package mysql
  2. import (
  3. "context"
  4. "git.aiterp.net/lucifer/new-server/models"
  5. "github.com/jmoiron/sqlx"
  6. )
  7. type BridgeRepo struct {
  8. DBX *sqlx.DB
  9. }
  10. func (b *BridgeRepo) Find(ctx context.Context, id int) (models.Bridge, error) {
  11. var bridge models.Bridge
  12. err := b.DBX.GetContext(ctx, &bridge, "SELECT * FROM bridge WHERE id = ?", id)
  13. if err != nil {
  14. return models.Bridge{}, dbErr(err)
  15. }
  16. return bridge, nil
  17. }
  18. func (b *BridgeRepo) FetchAll(ctx context.Context) ([]models.Bridge, error) {
  19. bridges := make([]models.Bridge, 0, 8)
  20. err := b.DBX.SelectContext(ctx, &bridges, "SELECT * FROM bridge")
  21. if err != nil {
  22. return nil, dbErr(err)
  23. }
  24. return bridges, nil
  25. }
  26. func (b *BridgeRepo) Save(ctx context.Context, bridge *models.Bridge) error {
  27. if bridge.ID > 0 {
  28. _, err := b.DBX.ExecContext(
  29. ctx,
  30. "UPDATE bridge SET name = ?, address = ?, token = ? WHERE id = ?",
  31. bridge.Name, bridge.Address, bridge.Token, bridge.ID,
  32. )
  33. if err != nil {
  34. return dbErr(err)
  35. }
  36. } else {
  37. rs, err := b.DBX.ExecContext(
  38. ctx,
  39. "INSERT INTO bridge (name, driver, address, token) VALUES (?, ?, ?, ?)",
  40. bridge.Name, bridge.Driver, bridge.Address, bridge.Token,
  41. )
  42. if err != nil {
  43. return dbErr(err)
  44. }
  45. id, err := rs.LastInsertId()
  46. if err != nil {
  47. return dbErr(err)
  48. }
  49. bridge.ID = int(id)
  50. }
  51. return nil
  52. }
  53. func (b *BridgeRepo) Delete(ctx context.Context, bridge *models.Bridge) error {
  54. _, err := b.DBX.ExecContext(ctx, "DELETE FROM bridge WHERE id = ?", bridge.ID)
  55. if err != nil {
  56. return dbErr(err)
  57. }
  58. _, err = b.DBX.ExecContext(ctx, "DELETE FROM device WHERE bridge_id = ?", bridge.ID)
  59. if err != nil {
  60. return dbErr(err)
  61. }
  62. bridge.ID = 0
  63. return nil
  64. }