Files
server/database/func.go
T
2023-01-14 06:02:17 -07:00

125 lines
2.8 KiB
Go

package database
import (
"context"
"fmt"
"github.com/google/uuid"
)
func (d *Database) GetPipelineById(id uuid.UUID) (Pipeline, error) {
query := `
SELECT name, url, poll_interval
FROM pipelines
WHERE id=$1;`
pipeline := Pipeline{
Id: id,
}
err := d.Conn.QueryRow(context.Background(), query, id).Scan(&pipeline.Name, &pipeline.Url, &pipeline.PollInterval)
if err != nil {
return pipeline, fmt.Errorf("Could not query database for pipeline with id %v: %w", id.String(), err)
}
return pipeline, nil
}
func (d *Database) CreatePipeline(name string, url string, pollInterval int) (Pipeline, error) {
query := `
INSERT INTO pipelines (id, name, url, poll_interval)
VALUES (uuid_generate_v4(), $1, $2, $3)
RETURNING id, name, url, poll_interval;`
pipeline := Pipeline{}
var idStr string
err := d.Conn.QueryRow(context.Background(), query, name, url, pollInterval).Scan(&idStr, &pipeline.Name, &pipeline.Url, &pipeline.PollInterval)
if err != nil {
return pipeline, err
}
id, err := uuid.Parse(idStr)
if err != nil {
return pipeline, err
}
pipeline.Id = id
return pipeline, nil
}
func (db *Database) GetWebhooksForPipeline(id uuid.UUID) ([]Webhook, error) {
query := `
SELECT id, server_type, secret
FROM webhooks
WHERE pipeline=$1;`
webhooks := make([]Webhook, 0)
rows, err := db.Conn.Query(context.Background(), query, id)
if err != nil {
log.Fatal(err)
}
defer rows.Close()
for rows.Next() {
var webhook Webhook
var idStr string
if err := rows.Scan(&idStr, &webhook.ServerType, &webhook.Secret); err != nil {
return webhooks, err
}
webhook.Id, err = uuid.Parse(idStr)
if err != nil {
return webhooks, err
}
webhooks = append(webhooks, webhook)
}
return webhooks, nil
}
func (d *Database) GetWebhookById(id uuid.UUID) (Webhook, error) {
query := `
SELECT server_type, secret, pipeline
FROM webhooks
WHERE id=$1;`
webhook := Webhook{
Id: id,
}
err := d.Conn.QueryRow(context.Background(), query, id).Scan(&webhook.ServerType, &webhook.Secret, &webhook.Pipeline)
if err != nil {
return webhook, fmt.Errorf("Could not query database for webhook with id %v: %w", id.String(), err)
}
return webhook, nil
}
func (d *Database) CreateWebhook(serverType WebhookSender, pipelineId uuid.UUID) (Webhook, error) {
//WITH secret_val as (select substr(md5(random()::text), 0, 50)),
query := `
INSERT INTO webhooks (id, server_type, secret, pipeline)
VALUES (uuid_generate_v4(), $1, (select substr(md5(random()::text), 0, 50)), $2)
RETURNING id, server_type, secret, pipeline;`
webhook := Webhook{}
var idStr string
err := d.Conn.QueryRow(context.Background(), query, string(serverType), pipelineId).Scan(&idStr, &webhook.ServerType, &webhook.Secret, &webhook.Pipeline)
if err != nil {
return webhook, err
}
id, err := uuid.Parse(idStr)
if err != nil {
return webhook, err
}
webhook.Id = id
return webhook, nil
}