87 lines
2.5 KiB
Go
87 lines
2.5 KiB
Go
// Package store holds the connectors module's SQL: the accepted connector
|
|
// specs the host starts at boot.
|
|
package store
|
|
|
|
import (
|
|
"context"
|
|
"database/sql/driver"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
|
|
"github.com/jmoiron/sqlx"
|
|
)
|
|
|
|
// Accepted is one connector an operator accepted, with the authority it
|
|
// declared.
|
|
type Accepted struct {
|
|
OrgID string `db:"org_id"`
|
|
Name string `db:"name"`
|
|
Path string `db:"path"`
|
|
SHA256 string `db:"sha256"`
|
|
Egress Strings `db:"egress"`
|
|
Env Strings `db:"env"`
|
|
Settings json.RawMessage `db:"settings"`
|
|
}
|
|
|
|
// Store is the connectors module's Postgres store.
|
|
type Store struct {
|
|
db *sqlx.DB
|
|
}
|
|
|
|
// New returns a store on db.
|
|
func New(db *sqlx.DB) *Store { return &Store{db: db} }
|
|
|
|
// List returns an organisation's accepted connectors.
|
|
func (s *Store) List(ctx context.Context, orgID string) ([]Accepted, error) {
|
|
var out []Accepted
|
|
if err := s.db.SelectContext(ctx, &out, `
|
|
SELECT org_id, name, path, sha256, egress, env, settings
|
|
FROM connectors.accepted WHERE org_id = $1 ORDER BY name`, orgID); err != nil {
|
|
return nil, fmt.Errorf("list connectors: %w", err)
|
|
}
|
|
return out, nil
|
|
}
|
|
|
|
// Upsert records an accepted connector, replacing an earlier acceptance.
|
|
func (s *Store) Upsert(ctx context.Context, a Accepted) error {
|
|
if _, err := s.db.NamedExecContext(ctx, `
|
|
INSERT INTO connectors.accepted (org_id, name, path, sha256, egress, env, settings)
|
|
VALUES (:org_id, :name, :path, :sha256, :egress, :env, :settings)
|
|
ON CONFLICT (org_id, name) DO UPDATE
|
|
SET path = EXCLUDED.path, sha256 = EXCLUDED.sha256, egress = EXCLUDED.egress,
|
|
env = EXCLUDED.env, settings = EXCLUDED.settings, updated_at = now()`, a); err != nil {
|
|
return fmt.Errorf("accept connector: %w", err)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// Strings is a string list stored as a JSON array. Value has a value receiver
|
|
// so database/sql finds it on a struct field; Scan needs a pointer.
|
|
type Strings []string //nolint:recvcheck // database/sql's Valuer and Scanner idiom
|
|
|
|
// Value encodes the list as JSON.
|
|
func (s Strings) Value() (driver.Value, error) {
|
|
if s == nil {
|
|
return []byte("[]"), nil
|
|
}
|
|
return json.Marshal([]string(s))
|
|
}
|
|
|
|
// Scan decodes a JSON array.
|
|
func (s *Strings) Scan(src any) error {
|
|
var raw []byte
|
|
switch v := src.(type) {
|
|
case []byte:
|
|
raw = v
|
|
case string:
|
|
raw = []byte(v)
|
|
case nil:
|
|
*s = nil
|
|
return nil
|
|
default:
|
|
return errors.New("strings: unsupported column type")
|
|
}
|
|
return json.Unmarshal(raw, (*[]string)(s))
|
|
}
|