Better trigger create

This commit is contained in:
Magnus Åhall 2024-05-30 15:06:41 +02:00
parent 4c622561e3
commit 37bf692984
3 changed files with 85 additions and 2 deletions

View file

@ -7,6 +7,7 @@ import (
"github.com/lib/pq"
// Standard
"database/sql"
"encoding/json"
"fmt"
"strings"
@ -20,6 +21,13 @@ type Trigger struct {
Datapoints []string
}
func TriggerCreate(sectionID int, name string) (t Trigger, err error) { // {{{
t.SectionID = sectionID
t.Name = name
t.Expression = "false"
err = t.Update()
return
} // }}}
func TriggersRetrieve() (areas []Area, err error) { // {{{
areas = []Area{}
@ -137,15 +145,34 @@ func (t *Trigger) Update() (err error) { // {{{
}
jsonDatapoints, _ := json.Marshal(t.Datapoints)
if t.ID == 0 {
_, err = service.Db.Conn.Exec(`
var row *sql.Row
row = service.Db.Conn.QueryRow(`
INSERT INTO "trigger"(name, section_id, expression, datapoints)
VALUES($1, $2, $3, $4)
RETURNING id
`,
t.Name,
t.SectionID,
t.Expression,
jsonDatapoints,
)
err = row.Scan(&t.ID)
if err != nil {
err = we.Wrap(err).WithData(
struct {
SectionID int
Name string
Expression string
JsonDataPoints []byte
}{
t.SectionID,
t.Name,
t.Expression,
jsonDatapoints,
},
)
return
}
} else {
_, err = service.Db.Conn.Exec(`
UPDATE "trigger"