github.com/TBD54566975/ftl@v0.219.0/internal/modulecontext/database.go (about) 1 package modulecontext 2 3 import ( 4 "database/sql" 5 "fmt" 6 "strconv" 7 8 ftlv1 "github.com/TBD54566975/ftl/backend/protos/xyz/block/ftl/v1" 9 ) 10 11 // Database represents a database connection based on a DSN 12 // It holds a private field for the database which is accessible through moduleCtx.GetDatabase(name) 13 type Database struct { 14 DSN string 15 DBType DBType 16 isTestDB bool 17 db *sql.DB 18 } 19 20 // NewDatabase creates a Database that can be added to ModuleContext 21 func NewDatabase(dbType DBType, dsn string) (Database, error) { 22 db, err := sql.Open("pgx", dsn) 23 if err != nil { 24 return Database{}, err 25 } 26 return Database{ 27 DSN: dsn, 28 DBType: dbType, 29 db: db, 30 }, nil 31 } 32 33 // NewTestDatabase creates a Database that can be added to ModuleContext 34 // 35 // Test databases can be used within module tests 36 func NewTestDatabase(dbType DBType, dsn string) (Database, error) { 37 db, err := NewDatabase(dbType, dsn) 38 if err != nil { 39 return Database{}, err 40 } 41 db.isTestDB = true 42 return db, nil 43 } 44 45 type DBType ftlv1.ModuleContextResponse_DBType 46 47 const ( 48 DBTypePostgres = DBType(ftlv1.ModuleContextResponse_POSTGRES) 49 ) 50 51 func (x DBType) String() string { 52 switch x { 53 case DBTypePostgres: 54 return "Postgres" 55 default: 56 panic(fmt.Sprintf("unknown DB type: %s", strconv.Itoa(int(x)))) 57 } 58 }