Added script management
This commit is contained in:
parent
ba7375fe15
commit
04b1325031
7 changed files with 575 additions and 4 deletions
110
script.go
Normal file
110
script.go
Normal file
|
|
@ -0,0 +1,110 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
// External
|
||||
werr "git.gibonuddevalla.se/go/wrappederror"
|
||||
"github.com/jmoiron/sqlx"
|
||||
|
||||
// Standard
|
||||
"encoding/json"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
type Script struct {
|
||||
ID int
|
||||
Group string
|
||||
Name string
|
||||
Source string
|
||||
Updated time.Time
|
||||
}
|
||||
|
||||
func GetScripts() (scripts []Script, err error) {
|
||||
scripts = []Script{}
|
||||
|
||||
var rows *sqlx.Rows
|
||||
rows, err = db.Queryx(`
|
||||
SELECT *
|
||||
FROM script
|
||||
ORDER BY
|
||||
"group" ASC,
|
||||
name ASC
|
||||
`)
|
||||
if err != nil {
|
||||
err = werr.Wrap(err)
|
||||
return
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
for rows.Next() {
|
||||
var script Script
|
||||
err = rows.StructScan(&script)
|
||||
if err != nil {
|
||||
err = werr.Wrap(err)
|
||||
return
|
||||
}
|
||||
scripts = append(scripts, script)
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
func UpdateScript(scriptID int, data []byte) (script Script, err error) {
|
||||
err = json.Unmarshal(data, &script)
|
||||
if err != nil {
|
||||
err = werr.Wrap(err)
|
||||
return
|
||||
}
|
||||
|
||||
script.ID = scriptID
|
||||
script.Group = strings.TrimSpace(script.Group)
|
||||
script.Name = strings.TrimSpace(script.Name)
|
||||
|
||||
if script.Group == "" || script.Name == "" {
|
||||
err = werr.New("Group and name must be provided.")
|
||||
return
|
||||
}
|
||||
|
||||
if script.ID < 1 {
|
||||
row := db.QueryRowx(`
|
||||
INSERT INTO script("group", "name", "source")
|
||||
VALUES($1, $2, $3)
|
||||
RETURNING
|
||||
id
|
||||
`,
|
||||
strings.TrimSpace(script.Group),
|
||||
strings.TrimSpace(script.Name),
|
||||
script.Source,
|
||||
)
|
||||
err = row.Scan(&script.ID)
|
||||
} else {
|
||||
_, err = db.Exec(`
|
||||
UPDATE script
|
||||
SET
|
||||
"group" = $2,
|
||||
"name" = $3,
|
||||
"source" = $4
|
||||
WHERE
|
||||
id = $1
|
||||
`,
|
||||
scriptID,
|
||||
strings.TrimSpace(script.Group),
|
||||
strings.TrimSpace(script.Name),
|
||||
script.Source,
|
||||
)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
err = werr.Wrap(err)
|
||||
return
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
func DeleteScript(scriptID int) (err error) {
|
||||
_, err = db.Exec(`DELETE FROM script WHERE id = $1`, scriptID)
|
||||
if err != nil {
|
||||
err = werr.Wrap(err)
|
||||
return
|
||||
}
|
||||
return
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue