-
Notifications
You must be signed in to change notification settings - Fork 8
/
main.go
113 lines (92 loc) · 3.21 KB
/
main.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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
// 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 main
import (
"context"
"fmt"
"log"
"strings"
"time"
"github.com/cenkalti/backoff/v4"
"github.com/jackc/pgx/v4"
"namespacelabs.dev/foundation/framework/resources/provider"
"namespacelabs.dev/foundation/library/database/postgres"
)
const (
providerPkg = "namespacelabs.dev/foundation/library/oss/postgres"
connBackoff = 500 * time.Millisecond
)
func main() {
intent := &postgres.DatabaseIntent{}
ctx, r := provider.MustPrepare(intent)
cluster := &postgres.ClusterInstance{}
if err := r.Unmarshal(fmt.Sprintf("%s:cluster", providerPkg), cluster); err != nil {
log.Fatalf("unable to read required resource \"cluster\": %v", err)
}
conn, err := ensureDatabase(ctx, cluster, intent.Name)
if err != nil {
log.Fatalf("unable to create database %q: %v", intent.Name, err)
}
defer conn.Close(ctx)
for _, schema := range intent.Schema {
if _, err = conn.Exec(ctx, string(schema.Contents)); err != nil {
log.Fatalf("unable to apply schema %q: %v", schema.Path, err)
}
}
instance := &postgres.DatabaseInstance{
Name: intent.Name,
Cluster: cluster,
}
provider.EmitResult(instance)
}
func ensureDatabase(ctx context.Context, cluster *postgres.ClusterInstance, name string) (*pgx.Conn, error) {
// Postgres needs a database to connect to so we pin one that is guaranteed to exist.
conn, err := connect(ctx, cluster, "postgres")
if err != nil {
return nil, err
}
defer conn.Close(ctx)
exists, err := existsDatabase(ctx, conn, name)
if err != nil {
return nil, err
}
if !exists {
// SQL arguments can only be values, not identifiers.
// https://www.postgresql.org/docs/9.5/xfunc-sql.html
// `existsDb` already uses the database name as an SQL argument, so we already passed its validation.
// Still, let's do some basic sanity checking (whitespaces are forbidden), as we need to use Sprintf here.
if len(strings.Fields(name)) > 1 {
return nil, fmt.Errorf("invalid database name: %s", name)
}
if _, err := conn.Exec(ctx, fmt.Sprintf("CREATE DATABASE %s;", name)); err != nil {
return nil, fmt.Errorf("failed to create database %q: %w", name, err)
}
}
return connect(ctx, cluster, name)
}
func existsDatabase(ctx context.Context, conn *pgx.Conn, name string) (bool, error) {
rows, err := conn.Query(ctx, "SELECT FROM pg_database WHERE datname = $1;", name)
if err != nil {
return false, fmt.Errorf("failed to check for database %q: %w", name, err)
}
defer rows.Close()
return rows.Next(), nil
}
func connect(ctx context.Context, cluster *postgres.ClusterInstance, db string) (conn *pgx.Conn, err error) {
cfg, err := pgx.ParseConfig(fmt.Sprintf("postgres://postgres:%s@%s/%s", cluster.Password, cluster.Url, db))
if err != nil {
return nil, err
}
cfg.ConnectTimeout = connBackoff
// Retry until backend is ready.
err = backoff.Retry(func() error {
conn, err = pgx.ConnectConfig(ctx, cfg)
if err == nil {
return nil
}
log.Printf("failed to connect to postgres: %v\n", err)
return err
}, backoff.WithContext(backoff.NewConstantBackOff(connBackoff), ctx))
return conn, err
}