Skip to content

Commit 4b847fe

Browse files
committed
chore: fix tests
1 parent ba9cc4c commit 4b847fe

11 files changed

Lines changed: 492 additions & 216 deletions

File tree

cmd/main.go

Lines changed: 56 additions & 54 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ package main
33
import (
44
"fmt"
55
"os"
6+
"path/filepath"
67
"strconv"
78

89
"github.com/samber/lo"
@@ -17,17 +18,13 @@ import (
1718
)
1819

1920
var (
20-
postgres server.Postgres
21-
22-
verbose bool
21+
postgres server.Postgres
2322
createDb string
2423
configFile string
2524
encoding string
2625
locale string
2726
authMethod string
2827
opts pgtune.OptimizeOptions
29-
// Auto-detected directories
30-
detectedDirs *utils.PostgreSQLDirs
3128
)
3229

3330
func getIntVar(name string) int {
@@ -69,10 +66,10 @@ This unified tool combines PostgreSQL server management, configuration generatio
6966

7067
// Load configuration if specified
7168
if configFile != "" {
72-
if pgConfig, err := config.LoadPostgresConf(configFile); err == nil {
69+
if pconfig, err := config.LoadPostgresConf(configFile); err == nil {
7370
return err
7471
} else {
75-
postgres.Config = pgConfig
72+
postgres.Config = pconfig
7673
}
7774
} else if postgres.Config == nil {
7875
postgres.Config = config.DefaultPostgresConf()
@@ -90,6 +87,10 @@ This unified tool combines PostgreSQL server management, configuration generatio
9087
return err
9188
}
9289

90+
if postgres.DryRun {
91+
clicky.Infof("📋 Dry run mode enabled")
92+
}
93+
9394
return nil
9495
},
9596
}
@@ -101,15 +102,11 @@ This unified tool combines PostgreSQL server management, configuration generatio
101102
rootCmd.PersistentFlags().IntVarP(&postgres.Port, "port", "p", lo.CoalesceOrEmpty(getIntVar("PG_PORT"), 5432), "PostgreSQL port")
102103
rootCmd.PersistentFlags().StringVar(&postgres.DataDir, "data-dir", os.Getenv("PGDATA"), "PostgreSQL data directory (auto-detected if not specified)")
103104
rootCmd.PersistentFlags().StringVar(&postgres.BinDir, "bin-dir", "", "PostgreSQL binary directory (auto-detected if not specified)")
105+
rootCmd.PersistentFlags().BoolVar(&postgres.DryRun, "dry-run", false, "Enable dry-run mode to simulate actions without making changes")
104106
rootCmd.PersistentFlags().StringVarP(&configFile, "config", "c", "", "Configuration file path")
105107
rootCmd.PersistentFlags().StringVar(&locale, "locale", "C", "Locale for initialized database")
106108
rootCmd.PersistentFlags().StringVar(&encoding, "encoding", "UTF8", "Encoding for initialized database")
107-
rootCmd.PersistentFlags().BoolVar(&opts.Enabled, "pg-tune", os.Getenv("PG_TUNE") == "true", "Enable pg_tune optimization")
108-
rootCmd.PersistentFlags().IntVar(&opts.MaxConnections, "max-connections", getIntVar("PG_TUNE_MAX_CONNECTIONS"), "Max connections for pg_tune (0 = auto-calculate)")
109-
rootCmd.PersistentFlags().IntVar(&opts.MemoryMB, "memory", getIntVar("PG_TUNE_MEMORY"), "Override detected memory in MB for pg_tune")
110-
rootCmd.PersistentFlags().IntVar(&opts.Cores, "cpus", getIntVar("PG_TUNE_CPUS"), "Override detected CPU count for pg_tune")
111-
rootCmd.PersistentFlags().StringVar(&opts.DBType, "type", "web", "Database type for pg_tune: web, oltp, dw, desktop, mixed")
112-
rootCmd.PersistentFlags().StringVar(&authMethod, "auth-method", lo.CoalesceOrEmpty(os.Getenv("PG_AUTH_METHOD"), string(pkg.AuthScramSHA)), "Authentication method for pg_hba.conf (auto-detected if not specified)")
109+
113110
clicky.BindAllFlags(rootCmd.PersistentFlags())
114111

115112
// Add command groups
@@ -140,22 +137,26 @@ This command can automatically:
140137
- Reset the superuser password
141138
142139
Examples:
143-
pgconfig auto-start Start PostgreSQL normally
144-
pgconfig auto-start --auto-init Initialize and start if needed
145-
pgconfig auto-start --pg-tune Optimize config before starting
146-
pgconfig auto-start --auto-upgrade Upgrade if needed, then start
147-
pgconfig auto-start --auto-reset-password Reset password, then start
148-
pgconfig auto-start --auto-init --pg-tune Initialize, optimize, then start
149-
pgconfig auto-start --dry-run Validate permissions without starting`,
140+
postgres-cli auto-start Start PostgreSQL normally
141+
postgres-cli auto-start --auto-init Initialize and start if needed
142+
postgres-cli auto-start --pg-tune Optimize config before starting
143+
postgres-cli auto-start --auto-upgrade Upgrade if needed, then start
144+
postgres-cli auto-start --auto-reset-password Reset password, then start
145+
postgres-cli auto-start --auto-init --pg-tune Initialize, optimize, then start
146+
postgres-cli auto-start --dry-run Validate permissions without starting`,
150147
RunE: runAutoStart,
151148
}
152149

153-
cmd.Flags().Bool("auto-init", true, "Automatically initialize database if data directory doesn't exist")
154-
cmd.Flags().Bool("pg-tune", true, "Run pg_tune to optimize postgresql.conf before starting")
150+
cmd.Flags().IntVar(&opts.MaxConnections, "max-connections", getIntVar("PG_TUNE_MAX_CONNECTIONS"), "Max connections for pg_tune (0 = auto-calculate)")
151+
cmd.Flags().IntVar(&opts.MemoryMB, "memory", getIntVar("PG_TUNE_MEMORY"), "Override detected memory in MB for pg_tune")
152+
cmd.Flags().IntVar(&opts.Cores, "cpus", getIntVar("PG_TUNE_CPUS"), "Override detected CPU count for pg_tune")
153+
cmd.Flags().StringVar(&opts.DBType, "type", "web", "Database type for pg_tune: web, oltp, dw, desktop, mixed")
154+
cmd.Flags().StringVar(&authMethod, "auth-method", lo.CoalesceOrEmpty(os.Getenv("PG_AUTH_METHOD"), string(pkg.AuthScramSHA)), "Authentication method for pg_hba.conf (auto-detected if not specified)")
155+
cmd.Flags().BoolVar(&opts.Enabled, "pg-tune", true, "Run pg_tune to optimize postgresql.conf before starting")
155156
cmd.Flags().Bool("auto-upgrade", true, "Automatically upgrade PostgreSQL if version mismatch detected")
156157
cmd.Flags().Bool("auto-reset-password", true, "Reset postgres superuser password on start")
158+
cmd.Flags().Bool("auto-init", true, "Automatically initialize database if data directory doesn't exist")
157159
cmd.Flags().Int("upgrade-to", 0, "Target PostgreSQL version for upgrade (default: auto-detect latest)")
158-
cmd.Flags().Bool("dry-run", false, "Validate permissions and configuration without making changes")
159160

160161
return cmd
161162
}
@@ -166,34 +167,35 @@ func runAutoStart(cmd *cobra.Command, args []string) error {
166167
autoUpgrade, _ := cmd.Flags().GetBool("auto-upgrade")
167168
autoResetPassword, _ := cmd.Flags().GetBool("auto-reset-password")
168169
upgradeTo, _ := cmd.Flags().GetInt("upgrade-to")
169-
dryRun, _ := cmd.Flags().GetBool("dry-run")
170170

171171
// Log current user context
172172
uid, gid, username, err := utils.GetCurrentUserInfo()
173173
if err != nil {
174174
return fmt.Errorf("failed to get user info: %w", err)
175175
}
176-
fmt.Printf("Running as user: %s (UID: %d, GID: %d)\n", username, uid, gid)
177176

178-
clicky.Infof("✅ Permission checks passed")
179-
180-
// If dry-run mode, exit successfully
181-
if dryRun {
182-
clicky.Infof("\n✅ Dry-run validation completed successfully")
183-
clicky.Infof("All permission checks passed. Ready to start PostgreSQL.")
184-
return nil
185-
}
177+
clicky.Infof("Running auto-start with: %s", clicky.Map(map[string]any{
178+
"auto-init": autoInit,
179+
"pg-tune": opts.Enabled,
180+
"auto-upgrade": autoUpgrade,
181+
"auto-reset-password": autoResetPassword,
182+
"upgrade-to": upgradeTo,
183+
"database": postgres.Database,
184+
"uid": uid,
185+
"gid": gid,
186+
"username": username,
187+
}))
186188

187189
// Check if already running
188-
if postgres.IsRunning() {
190+
if !postgres.DryRun && postgres.IsRunning() {
189191
clicky.Infof("PostgreSQL is already running")
190192
return nil
191193
}
192194

193195
// Step 1: Auto-init if data directory doesn't exist
194196
if !postgres.Exists() {
195197
if autoInit {
196-
clicky.Infof("🔧 Initializing PostgreSQL database...")
198+
197199
if err := postgres.InitDB(); err != nil {
198200
return fmt.Errorf("failed to initialize database: %w", err)
199201
}
@@ -217,61 +219,61 @@ func runAutoStart(cmd *cobra.Command, args []string) error {
217219
}
218220

219221
if currentVersion < targetVersion {
220-
fmt.Printf("🚀 Upgrading PostgreSQL from version %d to %d...\n", currentVersion, targetVersion)
221222
if err := postgres.Upgrade(targetVersion); err != nil {
222223
return fmt.Errorf("failed to upgrade PostgreSQL: %w", err)
223224
}
224-
clicky.Infof("✅ PostgreSQL upgrade completed successfully")
225225
} else {
226226
fmt.Printf("✅ PostgreSQL is already at version %d (target: %d)\n", currentVersion, targetVersion)
227227
}
228228
}
229229

230230
// Step 3: Run pg_tune if requested
231231
if opts.Enabled {
232-
clicky.Infof("🔧 Running pg_tune to optimize configuration...")
233232

234-
err := pgtune.OptimizeAndSave(opts)
233+
content, err := pgtune.OptimizeAndSave(opts)
235234
if err != nil {
236235
return fmt.Errorf("failed to run pg_tune: %w", err)
237236
}
237+
if postgres.DryRun {
238+
clicky.Infof("📄 Generated postgresql.auto.conf by pg_tune:")
238239

239-
clicky.Infof("✅ Configuration optimized successfully")
240+
fmt.Println(clicky.CodeBlock("properties", content).ANSI())
241+
} else {
242+
configPath := filepath.Join(opts.DataDir, "postgresql.auto.conf")
243+
if err := os.WriteFile(configPath, []byte(content), 0644); err != nil {
244+
return fmt.Errorf("failed to write postgresql.auto.conf: %w", err)
245+
}
246+
clicky.Infof("✅ pg_tune optimization applied and saved to %s", configPath)
247+
248+
}
240249
}
241250

242251
// Step 4: Reset password if requested
243252
if autoResetPassword {
244-
newPassword := os.Getenv("POSTGRES_PASSWORD")
253+
254+
newPassword, err := utils.FileEnv("POSTGRES_PASSWORD", "")
255+
if err != nil {
256+
return fmt.Errorf("failed to read password: %w", err)
257+
}
245258
sensitivePassword := utils.NewSensitiveString(newPassword)
246259
if err := postgres.ResetPassword(sensitivePassword); err != nil {
247260
return fmt.Errorf("failed to reset password: %w", err)
248261
}
249-
clicky.Infof("✅ Password reset completed successfully")
262+
250263
}
251264

252265
if createDb != "" {
253-
fmt.Printf("🛠️ Ensuring database '%s' exists...\n", createDb)
266+
254267
if err := postgres.CreateDatabase(createDb); err != nil {
255268
//FIXME
256269
fmt.Printf("❌ Failed to create database '%s': %v\n", createDb, err)
257270
// return fmt.Errorf("failed to create database '%s': %w", createDb, err)
258-
} else {
259-
fmt.Printf("✅ Database '%s' is ready\n", createDb)
260-
261271
}
262272
}
263273

264274
if err := postgres.SetupPgHBA(authMethod); err != nil {
265275
return fmt.Errorf("failed to setup pg_hba.conf: %w", err)
266276
}
267-
268-
// // Step 5: Start PostgreSQL
269-
// clicky.Infof("🚀 Starting PostgreSQL...")
270-
// if err := postgres.Start(); err != nil {
271-
// return fmt.Errorf("failed to start PostgreSQL: %w", err)
272-
// }
273-
274-
clicky.Infof("✅ Ready to start")
275277
return nil
276278
}
277279

cmd/server.go

Lines changed: 0 additions & 100 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,6 @@ func createServerCommands() *cobra.Command {
1919

2020
// Add all server commands
2121
serverCmd.AddCommand(
22-
createInfoCommands(),
2322
createHealthCommand(),
2423
createInitDBCommand(),
2524
createResetPasswordCommand(),
@@ -86,102 +85,6 @@ func createRestartCommand() *cobra.Command {
8685
}
8786
}
8887

89-
// createInfoCommands creates the info subcommand group
90-
func createInfoCommands() *cobra.Command {
91-
infoCmd := &cobra.Command{
92-
Use: "info",
93-
Short: "Information and status commands",
94-
Long: "Commands for getting information about the PostgreSQL instance",
95-
}
96-
97-
// describe-config command
98-
describeConfigCmd := &cobra.Command{
99-
Use: "describe-config",
100-
Short: "Describe PostgreSQL configuration parameters",
101-
Long: "Execute 'postgres --describe-config' and return parsed parameters",
102-
RunE: func(cmd *cobra.Command, args []string) error {
103-
104-
params, err := postgres.DescribeConfig()
105-
if err != nil {
106-
return fmt.Errorf("failed to describe config: %w", err)
107-
}
108-
109-
fmt.Println(clicky.MustFormat(params))
110-
return nil
111-
},
112-
}
113-
describeConfigCmd.Flags().StringP("output", "o", "table", "Output format (table, json, yaml)")
114-
115-
// detect-version command
116-
detectVersionCmd := &cobra.Command{
117-
Use: "detect-version",
118-
Short: "Detect PostgreSQL version from data directory",
119-
Long: "Read the PostgreSQL version from the PG_VERSION file in the data directory",
120-
RunE: func(cmd *cobra.Command, args []string) error {
121-
122-
version, err := postgres.DetectVersion()
123-
if err != nil {
124-
return fmt.Errorf("failed to detect version: %w", err)
125-
}
126-
127-
fmt.Printf("PostgreSQL version: %d\n", version)
128-
return nil
129-
},
130-
}
131-
132-
// get-version command
133-
getVersionCmd := &cobra.Command{
134-
Use: "get-version",
135-
Short: "Get PostgreSQL version from binary",
136-
Long: "Execute 'postgres --version' to get version information",
137-
RunE: func(cmd *cobra.Command, args []string) error {
138-
139-
version := postgres.GetVersion()
140-
if version == "" {
141-
return fmt.Errorf("failed to get version")
142-
}
143-
144-
fmt.Printf("PostgreSQL version: %s\n", version)
145-
return nil
146-
},
147-
}
148-
149-
// exists command
150-
existsCmd := &cobra.Command{
151-
Use: "exists",
152-
Short: "Check if PostgreSQL data directory exists and is valid",
153-
Long: "Check if the data directory contains valid PostgreSQL files",
154-
RunE: func(cmd *cobra.Command, args []string) error {
155-
156-
exists := postgres.Exists()
157-
fmt.Printf("PostgreSQL data directory exists: %t\n", exists)
158-
if !exists {
159-
return fmt.Errorf("PostgreSQL data directory does not exist or is invalid")
160-
}
161-
return nil
162-
},
163-
}
164-
165-
// is-running command
166-
isRunningCmd := &cobra.Command{
167-
Use: "is-running",
168-
Short: "Check if PostgreSQL server is running",
169-
Long: "Check if PostgreSQL process is running by examining the PID file",
170-
RunE: func(cmd *cobra.Command, args []string) error {
171-
172-
running := postgres.IsRunning()
173-
fmt.Printf("PostgreSQL is running: %t\n", running)
174-
if !running {
175-
return fmt.Errorf("PostgreSQL is not running")
176-
}
177-
return nil
178-
},
179-
}
180-
181-
infoCmd.AddCommand(describeConfigCmd, detectVersionCmd, getVersionCmd, existsCmd, isRunningCmd)
182-
return infoCmd
183-
}
184-
18588
// createHealthCommand creates the health command
18689
func createHealthCommand() *cobra.Command {
18790
return &cobra.Command{
@@ -227,12 +130,9 @@ func createResetPasswordCommand() *cobra.Command {
227130
return fmt.Errorf("password is required")
228131
}
229132

230-
clicky.Infof("Resetting password for user %s", postgres.Username)
231-
232133
if err := postgres.ResetPassword(postgres.Password); err != nil {
233134
return fmt.Errorf("failed to reset password: %w", err)
234135
}
235-
fmt.Println("Password reset successfully")
236136
return nil
237137
},
238138
}

cmd/version.go

Lines changed: 13 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -16,9 +16,17 @@ var (
1616

1717
// GetVersionInfo returns formatted version information
1818
func GetVersionInfo() string {
19-
return fmt.Sprintf(`postgres-cli version: %s
20-
Git commit: %s
21-
Build date: %s
22-
Go version: %s
23-
OS/Arch: %s/%s`, Version, GitCommit, BuildDate, runtime.Version(), runtime.GOOS, runtime.GOARCH)
19+
// Shorten git commit to first 7 chars
20+
shortCommit := GitCommit
21+
if len(shortCommit) > 7 {
22+
shortCommit = shortCommit[:7]
23+
}
24+
25+
return fmt.Sprintf("postgres-cli v%s (git:%s, built:%s, %s, %s/%s)",
26+
Version,
27+
shortCommit,
28+
BuildDate,
29+
runtime.Version(),
30+
runtime.GOOS,
31+
runtime.GOARCH)
2432
}

docker-entrypoint.sh

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,7 @@ fi
4646
postgres-cli server status
4747

4848
# Run postgres-cli auto-start (includes permission checks)
49-
postgres-cli auto-start --pg-tune --auto-upgrade --upgrade-to=$PG_VERSION --auto-init --data-dir "$PGDATA" --auto-reset-password
49+
postgres-cli auto-start --upgrade-to=$PG_VERSION --data-dir "$PGDATA" $POSTGRES_CLI_ARGS
5050

5151
cat $PGDATA/pg_hba.conf
5252

0 commit comments

Comments
 (0)