Skip to content

Commit

Permalink
fix: construct db dsn in Go runtime
Browse files Browse the repository at this point in the history
  • Loading branch information
jvmakine committed Nov 22, 2024
1 parent 0a5f94f commit 240c16a
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 11 deletions.
19 changes: 13 additions & 6 deletions go-runtime/server/database.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"context"
"database/sql"
"fmt"
"os"
"reflect"
"time"

Expand Down Expand Up @@ -47,11 +48,17 @@ func InitDatabase(ref reflection.Ref, dbtype string, protoDBtype modulecontext.D
DBType: dbtype,
DB: once.Once(func(ctx context.Context) (*sql.DB, error) {
logger := log.FromContext(ctx)

provider := modulecontext.FromContext(ctx).CurrentContext()
dsn, testDB, err := provider.GetDatabase(ref.Name, protoDBtype)
if err != nil {
return nil, fmt.Errorf("failed to get database %q: %w", ref.Name, err)
var dsn string
if protoDBtype == modulecontext.DBTypePostgres {
proxyAddress := os.Getenv("PG_PROXY_ADDRESS")
dsn = "postgres://" + proxyAddress + "/" + ref.Name
} else {
provider := modulecontext.FromContext(ctx).CurrentContext()
d, _, err := provider.GetDatabase(ref.Name, protoDBtype)
if err != nil {
return nil, fmt.Errorf("failed to get database %q: %w", ref.Name, err)
}
dsn = d
}

logger.Debugf("Opening database: %s", ref.Name)
Expand All @@ -71,7 +78,7 @@ func InitDatabase(ref reflection.Ref, dbtype string, protoDBtype modulecontext.D
return nil, fmt.Errorf("failed to register database metrics: %w", err)
}
db.SetConnMaxIdleTime(time.Minute)
if testDB {
if os.Getenv("FTL_INTEGRATION_TEST") == "true" {
// In tests we always close the connections, as the DB being clean might invalidate pooled connections
db.SetMaxIdleConns(0)
} else {
Expand Down
1 change: 1 addition & 0 deletions internal/integration/harness.go
Original file line number Diff line number Diff line change
Expand Up @@ -218,6 +218,7 @@ func run(t *testing.T, actionsOrOptions ...ActionOrOption) {
for key, value := range opts.envars {
t.Setenv(key, value)
}
t.Setenv("FTL_INTEGRATION_TEST", "true")

cwd, err := os.Getwd()
assert.NoError(t, err)
Expand Down
5 changes: 0 additions & 5 deletions internal/modulecontext/module_context.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import (
"encoding/json"
"errors"
"fmt"
"os"
"strings"
"sync"
"time"
Expand Down Expand Up @@ -160,10 +159,6 @@ func (m ModuleContext) GetSecret(name string, value any) error {
func (m ModuleContext) GetDatabase(name string, dbType DBType) (string, bool, error) {
db, ok := m.databases[name]
if !ok {
if dbType == DBTypePostgres {
proxyAddress := os.Getenv("PG_PROXY_ADDRESS")
return "postgres://" + proxyAddress + "/" + name, false, nil
}
return "", false, fmt.Errorf("missing DSN for database %s", name)
}
if db.DBType != dbType {
Expand Down

0 comments on commit 240c16a

Please sign in to comment.