add support for connecting to postgres database

This commit is contained in:
Joel Wetzell
2026-09-05 08:22:38 -05:00
parent 4b97937f95
commit 8023af90fd
4 changed files with 249 additions and 4 deletions
+103
View File
@@ -0,0 +1,103 @@
package module
import (
"context"
"database/sql"
"fmt"
"log/slog"
"sync"
"github.com/google/jsonschema-go/jsonschema"
"github.com/jwetzell/showbridge-go/internal/common"
"github.com/jwetzell/showbridge-go/internal/config"
_ "github.com/jackc/pgx/v5/stdlib"
)
func init() {
RegisterModule(ModuleRegistration{
Type: "db.postgres",
Title: "PostgreSQL Database",
ParamsSchema: &jsonschema.Schema{
Type: "object",
Properties: map[string]*jsonschema.Schema{
"url": {
Title: "Database URL",
Description: "the connection URL for the PostgreSQL database",
Type: "string",
MinLength: new(1),
},
},
Required: []string{"url"},
AdditionalProperties: &jsonschema.Schema{Not: &jsonschema.Schema{}},
},
New: func(config config.ModuleConfig) (common.Module, error) {
params := config.Params
urlString, err := params.GetString("url")
if err != nil {
return nil, fmt.Errorf("db.postgres url error: %w", err)
}
return &DbPostgres{Url: urlString, config: config, logger: CreateLogger(config)}, nil
},
})
}
type DbPostgres struct {
config config.ModuleConfig
Url string
ctx context.Context
inputHandler common.InputHandler
db *sql.DB
logger *slog.Logger
dbMu sync.Mutex
cancel context.CancelFunc
}
func (dbs *DbPostgres) Id() string {
return dbs.config.Id
}
func (dbs *DbPostgres) Type() string {
return dbs.config.Type
}
func (dbs *DbPostgres) Start(ctx context.Context, inputHandler common.InputHandler) error {
dbs.logger.Debug("running")
dbs.inputHandler = inputHandler
moduleContext, cancel := context.WithCancel(ctx)
dbs.ctx = moduleContext
dbs.cancel = cancel
db, err := sql.Open("pgx", dbs.Url)
if err != nil {
return fmt.Errorf("db.postgres error connecting to database: %w", err)
}
dbs.dbMu.Lock()
dbs.db = db
dbs.dbMu.Unlock()
<-dbs.ctx.Done()
dbs.logger.Debug("done")
return nil
}
func (dbs *DbPostgres) Stop() {
if dbs.cancel != nil {
defer dbs.cancel()
}
dbs.dbMu.Lock()
defer dbs.dbMu.Unlock()
if dbs.db != nil {
dbs.db.Close()
}
}
func (dbs *DbPostgres) QueryContext(ctx context.Context, query string, args ...any) (*sql.Rows, error) {
dbs.dbMu.Lock()
defer dbs.dbMu.Unlock()
if dbs.db == nil {
return nil, fmt.Errorf("database not initialized")
}
return dbs.db.QueryContext(ctx, query, args...)
}
+126
View File
@@ -0,0 +1,126 @@
package module_test
import (
"testing"
"time"
"github.com/jwetzell/showbridge-go/internal/config"
"github.com/jwetzell/showbridge-go/internal/module"
)
func TestDbPostgresFromRegistry(t *testing.T) {
registration, ok := module.GetModuleRegistration("db.postgres")
if !ok {
t.Fatalf("db.postgres module not registered")
}
moduleInstance, err := registration.New(config.ModuleConfig{
Id: "test",
Type: "db.postgres",
Params: map[string]any{
"url": "postgres://localhost:5432",
},
})
if err != nil {
t.Fatalf("failed to create db.postgres module: %s", err)
}
if moduleInstance.Id() != "test" {
t.Fatalf("db.postgres module has wrong id: %s", moduleInstance.Id())
}
if moduleInstance.Type() != "db.postgres" {
t.Fatalf("db.postgres module has wrong type: %s", moduleInstance.Type())
}
}
func TestGoodDbPostgres(t *testing.T) {
testCases := []struct {
name string
params map[string]any
}{}
for _, test := range testCases {
t.Run(test.name, func(t *testing.T) {
registration, ok := module.GetModuleRegistration("db.postgres")
if !ok {
t.Fatalf("db.postgres module not registered")
}
moduleInstance, err := registration.New(config.ModuleConfig{
Id: "test",
Type: "db.postgres",
Params: test.params,
})
if err != nil {
t.Fatalf("db.postgres failed to create module: %s", err)
}
// TODO(jwetzell) this is kind of hacky
go func() {
time.Sleep(1 * time.Second)
moduleInstance.Stop()
}()
err = moduleInstance.Start(t.Context(), nil)
if err != nil {
t.Fatalf("db.postgres failed to start: %s", err)
}
})
}
}
func TestBadDbPostgres(t *testing.T) {
tests := []struct {
name string
params map[string]any
errorString string
}{
{
name: "no url param",
params: map[string]any{},
errorString: "db.postgres url error: not found",
},
{
name: "non-string url",
params: map[string]any{"url": 123},
errorString: "db.postgres url error: not a string",
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
registration, ok := module.GetModuleRegistration("db.postgres")
if !ok {
t.Fatalf("db.postgres module not registered")
}
moduleInstance, err := registration.New(config.ModuleConfig{
Id: "test",
Type: "db.postgres",
Params: test.params,
})
if err != nil {
if test.errorString != err.Error() {
t.Fatalf("db.postgres got error '%s', expected '%s'", err.Error(), test.errorString)
}
return
}
err = moduleInstance.Start(t.Context(), nil)
if err == nil {
t.Fatalf("db.postgres expected to fail")
}
if err.Error() != test.errorString {
t.Fatalf("db.postgres got error '%s', expected '%s'", err.Error(), test.errorString)
}
})
}
}