MCPcopy Index your code
hub / github.com/dreamsofcode-io/zenstats / NewDatabase

Function NewDatabase

internal/config/database.go:43–94  ·  view source on GitHub ↗

NewDatabase creates a database configuration based on the environment variables required. If any env variables are not set or are invalid then this method will throw an error.

()

Source from the content-addressed store, hash-verified

41// variables required. If any env variables are not set or are invalid then
42// this method will throw an error.
43func NewDatabase() (*Database, error) {
44 username, ok := os.LookupEnv("POSTGRES_USER")
45 if !ok {
46 return nil, fmt.Errorf("no POSTGRES_USER env variable set")
47 }
48
49 password, err := loadPassword()
50 if err != nil {
51 return nil, fmt.Errorf("loading password: %w", err)
52 }
53
54 host, ok := os.LookupEnv("POSTGRES_HOST")
55 if !ok {
56 return nil, fmt.Errorf("no POSTGRES_HOST env variable set")
57 }
58
59 portStr, ok := os.LookupEnv("POSTGRES_PORT")
60 if !ok {
61 return nil, fmt.Errorf("no POSTGRES_PORT env variable set")
62 }
63
64 port, err := strconv.Atoi(portStr)
65 if err != nil {
66 return nil, fmt.Errorf("failed to convert port to int: %w", err)
67 }
68
69 dbname, ok := os.LookupEnv("POSTGRES_DB")
70 if !ok {
71 return nil, fmt.Errorf("no POSTGRES_DB env variable set")
72 }
73
74 sslmode, ok := os.LookupEnv("POSTGRES_SSLMODE")
75 if !ok {
76 return nil, fmt.Errorf("no SSLMode env variable set")
77 }
78
79 config := &Database{
80 Username: username,
81 Password: password,
82 Host: host,
83 Port: uint16(port),
84 DBName: dbname,
85 SSLMode: sslmode,
86 }
87
88 err = config.Validate()
89 if err != nil {
90 return nil, fmt.Errorf("failed to validate config: %w", err)
91 }
92
93 return config, nil
94}
95
96// URL generates a database connection url from the configuration fields.
97func (c *Database) URL() string {

Callers 3

loadConfigFunction · 0.92
dbURLFunction · 0.92

Calls 2

ValidateMethod · 0.95
loadPasswordFunction · 0.85

Tested by 1