apache/answer · error

connect database failed

Error message

connect database failed: %w

What it means

ResetPassword wraps a failure from initDatabase(config.Data.Database.Driver, config.Data.Database.Connection), i.e. the CLI could not open a connection to the configured database (driver not supported or connection failed).

Solutions

  1. Verify database.driver and database.connection values in the config file.
  2. Confirm the database is running and reachable (ping/port test).
  3. Check username/password and that the driver name is one the app supports.

Example fix

// before
connection = "postgres://app:secret@db-host:5432/appdb"
// after (verify reachability, correct host/port)
connection = "postgres://app:secret@127.0.0.1:5432/appdb"
Defensive patterns

Strategy: validation

Validate before calling

addr, err := net.LookupHost("db-host")
if err != nil { return fmt.Errorf("db host unresolvable") }
conn, err := net.DialTimeout("tcp", "db-host:5432", 3*time.Second)
if err != nil { return fmt.Errorf("db port closed: %w", err) }
conn.Close()

Try / catch

if err := cli.ResetPassword(ctx, dataDir, opts); err != nil {
    if strings.Contains(err.Error(), "connect database failed") {
        log.Fatalf("verify DB driver/connection in config: %v", err)
    }
}

Prevention

When it happens

Trigger: Database driver string invalid (not mysql/postgres/sqlite3) or the connection DSN is unreachable — wrong host/port, DB down, bad credentials.

Common situations: Config points at a DB container that isn't running, credentials rotated, DNS/hostname typo, unsupported driver value in config.

Understand the failure class

Background: ECONNREFUSED and "connection refused" / "could not connect to server" errors: what they mean and how to fix them — this error's family across 44 libraries.

Related errors


AI-assisted analysis of apache/answer@3b9f137061 (2026-09-05). Data as JSON: /api/errors/eda890fd8388ac99. Report an issue: GitHub.

Appendix: source

Thrown at internal/cli/reset_password.go:79

	charsetSpecial,
}

type ResetPasswordOptions struct {
	Email    string
	Password string
}

func ResetPassword(ctx context.Context, dataDirPath string, opts *ResetPasswordOptions) error {
	path.FormatAllPath(dataDirPath)

	config, err := conf.ReadConfig(path.GetConfigFilePath())
	if err != nil {
		return fmt.Errorf("read config file failed: %w", err)
	}

	db, err := initDatabase(config.Data.Database.Driver, config.Data.Database.Connection)
	if err != nil {
		return fmt.Errorf("connect database failed: %w", err)
	}
	defer func() {
		_ = db.Close()
	}()

	cache, cacheCleanup, err := data.NewCache(config.Data.Cache)
	if err != nil {
		return fmt.Errorf("initialize cache failed: %w", err)
	}
	defer cacheCleanup()

	dataData, dataCleanup, err := data.NewData(db, cache)
	if err != nil {
		return fmt.Errorf("initialize data layer failed: %w", err)
	}
	defer dataCleanup()

	userRepo := user.NewUserRepo(dataData)

View on GitHub (pinned to 3b9f137061)