MCPcopy
hub / github.com/sqlc-dev/sqlc / configurePostgres

Function configurePostgres

internal/sqltest/native/postgres.go:117–166  ·  view source on GitHub ↗
()

Source from the content-addressed store, hash-verified

115}
116
117func configurePostgres() error {
118 // Set password for postgres user using sudo -u postgres
119 cmd := exec.Command("sudo", "-u", "postgres", "psql", "-c", "ALTER USER postgres PASSWORD 'postgres';")
120 if output, err := cmd.CombinedOutput(); err != nil {
121 // This might fail if password is already set, which is fine
122 slog.Debug("native/postgres", "set-password", string(output))
123 }
124
125 // Update pg_hba.conf to allow password authentication
126 // First, find the pg_hba.conf file
127 output, err := exec.Command("sudo", "-u", "postgres", "psql", "-t", "-c", "SHOW hba_file;").CombinedOutput()
128 if err != nil {
129 return fmt.Errorf("could not find hba_file: %w", err)
130 }
131
132 hbaFile := strings.TrimSpace(string(output))
133 if hbaFile == "" {
134 return fmt.Errorf("empty hba_file path")
135 }
136
137 // Check if we need to update pg_hba.conf
138 catOutput, err := exec.Command("sudo", "cat", hbaFile).CombinedOutput()
139 if err != nil {
140 return fmt.Errorf("could not read %s: %w", hbaFile, err)
141 }
142
143 // If md5 or scram-sha-256 auth is not configured for local connections, add it
144 content := string(catOutput)
145 if !strings.Contains(content, "host all all 127.0.0.1/32 md5") &&
146 !strings.Contains(content, "host all all 127.0.0.1/32 scram-sha-256") {
147
148 // Prepend a rule for localhost password authentication
149 newRule := "host all all 127.0.0.1/32 md5\n"
150
151 // Use sed to add the rule at the beginning (after comments)
152 cmd := exec.Command("sudo", "bash", "-c",
153 fmt.Sprintf(`echo '%s' | cat - %s > /tmp/pg_hba.conf.new && sudo mv /tmp/pg_hba.conf.new %s`,
154 newRule, hbaFile, hbaFile))
155 if output, err := cmd.CombinedOutput(); err != nil {
156 slog.Debug("native/postgres", "update-hba-error", string(output))
157 }
158
159 // Reload PostgreSQL to apply changes
160 if err := reloadPostgres(); err != nil {
161 slog.Debug("native/postgres", "reload-error", err)
162 }
163 }
164
165 return nil
166}
167
168func reloadPostgres() error {
169 // Try systemctl reload

Callers 1

startPostgreSQLServerFunction · 0.85

Calls 1

reloadPostgresFunction · 0.85

Tested by

no test coverage detected