/
init_db.go
75 lines (60 loc) · 1.79 KB
/
init_db.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
package command
import (
"errors"
"fmt"
"os"
"strings"
"github.com/spf13/cobra"
"github.com/simplesurance/baur/v3/internal/command/term"
"github.com/simplesurance/baur/v3/pkg/baur"
"github.com/simplesurance/baur/v3/pkg/storage"
)
const initDbExample = `
baur init db postgres://postgres@localhost:5432/baur?sslmode=disable
`
var initDbLongHelp = fmt.Sprintf(`
Creates the baur tables in a PostgreSQL database.
The Postgres URL is read from the repository configuration file.
Alternatively the URL can be passed as argument or
by setting the '%s' environment variable.`,
term.Highlight(envVarPSQLURL))
var initDbCmd = &cobra.Command{
Use: "db [POSTGRES_URL]",
Short: "create baur tables in a PostgreSQL database",
Example: strings.TrimSpace(initDbExample),
Long: strings.TrimSpace(initDbLongHelp),
Run: initDb,
Args: cobra.MaximumNArgs(1),
ValidArgsFunction: cobra.NoFileCompletions,
}
func init() {
initCmd.AddCommand(initDbCmd)
}
func initDb(_ *cobra.Command, args []string) {
var dbURL string
if len(args) == 1 {
dbURL = args[0]
} else {
repo, err := findRepository()
if err != nil {
if os.IsNotExist(err) {
stderr.Printf("could not find '%s' repository config file.\n"+
"Run '%s' first or pass the Postgres URL as argument.\n",
term.Highlight(baur.RepositoryCfgFile), term.Highlight(cmdInitRepo))
exitFunc(1)
}
stderr.Println(err)
exitFunc(1)
}
dbURL = mustGetPSQLURI(repo.Cfg)
}
storageClt, err := newStorageClient(dbURL)
exitOnErr(err, "establishing connection failed")
defer storageClt.Close()
err = storageClt.Init(ctx)
if errors.Is(err, storage.ErrExists) {
fatal("database already exists")
}
exitOnErr(err)
stdout.Println("database tables created successfully")
}