• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

pace / bricks / 13116624682

03 Feb 2025 03:13PM UTC coverage: 56.662% (-0.2%) from 56.856%
13116624682

push

github

web-flow
Merge pull request #382 from pace/bun-poc

Add Bun backend

144 of 189 new or added lines in 8 files covered. (76.19%)

48 existing lines in 4 files now uncovered.

5337 of 9419 relevant lines covered (56.66%)

21.97 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

92.86
/backend/postgres/postgres.go
1
// Copyright © 2024 by PACE Telematics GmbH. All rights reserved.
2

3
package postgres
4

5
import (
6
        "context"
7
        "database/sql"
8
        "net"
9
        "os"
10
        "path/filepath"
11
        "strconv"
12
        "time"
13

14
        "github.com/caarlos0/env/v10"
15
        "github.com/pace/bricks/backend/postgres/hooks"
16
        "github.com/pace/bricks/maintenance/health/servicehealthcheck"
17
        "github.com/prometheus/client_golang/prometheus"
18
        "github.com/uptrace/bun"
19
        "github.com/uptrace/bun/dialect/pgdialect"
20
        "github.com/uptrace/bun/driver/pgdriver"
21

22
        "github.com/pace/bricks/maintenance/log"
23
)
24

25
type Config struct {
26
        Port     int    `env:"POSTGRES_PORT" envDefault:"5432"`
27
        Host     string `env:"POSTGRES_HOST" envDefault:"postgres"`
28
        Password string `env:"POSTGRES_PASSWORD" envDefault:"mysecretpassword"`
29
        User     string `env:"POSTGRES_USER" envDefault:"postgres"`
30
        Database string `env:"POSTGRES_DB" envDefault:"postgres"`
31

32
        // ApplicationName is the application name. Used in logs on Pg side.
33
        // Only availaible from pg-9.0.
34
        ApplicationName string `env:"POSTGRES_APPLICATION_NAME" envDefault:"-"`
35
        // Dial timeout for establishing new connections.
36
        DialTimeout time.Duration `env:"POSTGRES_DIAL_TIMEOUT" envDefault:"5s"`
37
        // Name of the Table that is created to try if database is writeable
38
        HealthCheckTableName string `env:"POSTGRES_HEALTH_CHECK_TABLE_NAME" envDefault:"healthcheck"`
39
        // Amount of time to cache the last health check result
40
        HealthCheckResultTTL time.Duration `env:"POSTGRES_HEALTH_CHECK_RESULT_TTL" envDefault:"10s"`
41
        // Indicator whether write (insert,update,delete) queries should be logged
42
        LogWrite bool `env:"POSTGRES_LOG_WRITES" envDefault:"true"`
43
        // Indicator whether read (select) queries should be logged
44
        LogRead bool `env:"POSTGRES_LOG_READS" envDefault:"false"`
45
        // Timeout for socket reads. If reached, commands will fail
46
        // with a timeout instead of blocking.
47
        ReadTimeout time.Duration `env:"POSTGRES_READ_TIMEOUT" envDefault:"30s"`
48
        // Timeout for socket writes. If reached, commands will fail
49
        // with a timeout instead of blocking.
50
        WriteTimeout time.Duration `env:"POSTGRES_WRITE_TIMEOUT" envDefault:"30s"`
51
}
52

53
var cfg Config
54

55
func init() {
1✔
56
        prometheus.MustRegister(hooks.MetricQueryTotal)
1✔
57
        prometheus.MustRegister(hooks.MetricQueryFailed)
1✔
58
        prometheus.MustRegister(hooks.MetricQueryDurationSeconds)
1✔
59
        prometheus.MustRegister(hooks.MetricQueryAffectedTotal)
1✔
60

1✔
61
        err := env.Parse(&cfg)
1✔
62
        if err != nil {
1✔
63
                log.Fatalf("Failed to parse postgres environment: %v", err)
×
64
        }
×
65

66
        // if the application name is unset infer it from the:
67
        // jaeger service name , service name or executable name
68
        if cfg.ApplicationName == "-" {
2✔
69
                names := []string{
1✔
70
                        os.Getenv("JAEGER_SERVICE_NAME"),
1✔
71
                        os.Getenv("SERVICE_NAME"),
1✔
72
                        filepath.Base(os.Args[0]),
1✔
73
                }
1✔
74
                for _, name := range names {
2✔
75
                        if name != "" {
2✔
76
                                cfg.ApplicationName = name
1✔
77
                                break
1✔
78
                        }
79
                }
80
        }
81

82
        servicehealthcheck.RegisterHealthCheck("postgresdefault", NewHealthCheck(NewDB(context.Background())))
1✔
83
}
84

85
func NewDB(ctx context.Context, options ...ConfigOption) *bun.DB {
2✔
86
        for _, opt := range options {
3✔
87
                opt(&cfg)
1✔
88
        }
1✔
89

90
        connector := pgdriver.NewConnector(
2✔
91
                pgdriver.WithAddr(net.JoinHostPort(cfg.Host, strconv.Itoa(cfg.Port))),
2✔
92
                pgdriver.WithApplicationName(cfg.ApplicationName),
2✔
93
                pgdriver.WithDatabase(cfg.Database),
2✔
94
                pgdriver.WithDialTimeout(cfg.DialTimeout),
2✔
95
                pgdriver.WithPassword(cfg.Password),
2✔
96
                pgdriver.WithReadTimeout(cfg.ReadTimeout),
2✔
97
                pgdriver.WithUser(cfg.User),
2✔
98
                pgdriver.WithWriteTimeout(cfg.WriteTimeout),
2✔
99
                pgdriver.WithInsecure(true),
2✔
100
        )
2✔
101

2✔
102
        sqldb := sql.OpenDB(connector)
2✔
103
        db := bun.NewDB(sqldb, pgdialect.New())
2✔
104

2✔
105
        log.Ctx(ctx).Info().Str("addr", connector.Config().Addr).
2✔
106
                Str("user", connector.Config().User).
2✔
107
                Str("database", connector.Config().Database).
2✔
108
                Str("as", connector.Config().AppName).
2✔
109
                Msg("PostgreSQL connection pool created")
2✔
110

2✔
111
        // Add hooks
2✔
112
        db.AddQueryHook(&hooks.TracingHook{})
2✔
113
        db.AddQueryHook(hooks.NewMetricsHook(cfg.Host, cfg.Database))
2✔
114

2✔
115
        if cfg.LogWrite || cfg.LogRead {
4✔
116
                db.AddQueryHook(hooks.NewLoggingHook(cfg.LogRead, cfg.LogWrite))
2✔
117
        } else {
2✔
NEW
118
                log.Ctx(ctx).Warn().Msg("Connection pool has logging queries disabled completely")
×
119
        }
×
120

121
        return db
2✔
122
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc