-
Notifications
You must be signed in to change notification settings - Fork 9
/
resource.go
37 lines (29 loc) · 1008 Bytes
/
resource.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
// Copyright 2022 Namespace Labs Inc; All rights reserved.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
package postgres
import (
"context"
"github.com/jackc/pgx/v4/pgxpool"
"go.opentelemetry.io/otel/trace"
"namespacelabs.dev/foundation/framework/resources"
postgrespb "namespacelabs.dev/foundation/library/database/postgres"
)
// Connect to a Postgres Database resource.
func ConnectToResource(ctx context.Context, res *resources.Parsed, resourceRef string, tracer trace.Tracer) (*DB, error) {
db := &postgrespb.DatabaseInstance{}
if err := res.Unmarshal(resourceRef, db); err != nil {
return nil, err
}
config, err := pgxpool.ParseConfig(db.ConnectionUri)
if err != nil {
return nil, err
}
// Only connect when the pool starts to be used.
config.LazyConnect = true
conn, err := pgxpool.ConnectConfig(ctx, config)
if err != nil {
return nil, err
}
return NewDB(db, conn, tracer), nil
}