Refs #32, #37 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
95 lines
2.1 KiB
Go
95 lines
2.1 KiB
Go
// Command pginit applies a psql-style init script with a superuser
|
|
// connection, for databases that cannot mount deploy/dev/postgres-init.sql
|
|
// themselves, such as CI service containers. It understands statements
|
|
// ending in ";" and "\connect <database>" lines.
|
|
//
|
|
// go run ./internal/devtools/pginit postgres://postgres:pw@host:5432/postgres deploy/dev/postgres-init.sql
|
|
package main
|
|
|
|
import (
|
|
"bufio"
|
|
"context"
|
|
"fmt"
|
|
"net/url"
|
|
"os"
|
|
"strings"
|
|
"time"
|
|
|
|
"github.com/jackc/pgx/v5"
|
|
)
|
|
|
|
func main() {
|
|
if len(os.Args) != 3 {
|
|
fmt.Fprintln(os.Stderr, "usage: pginit <superuser-dsn> <script>")
|
|
os.Exit(2)
|
|
}
|
|
if err := run(os.Args[1], os.Args[2]); err != nil {
|
|
fmt.Fprintln(os.Stderr, "pginit:", err)
|
|
os.Exit(1)
|
|
}
|
|
}
|
|
|
|
func run(dsn, script string) error {
|
|
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)
|
|
defer cancel()
|
|
f, err := os.Open(script)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer func() { _ = f.Close() }()
|
|
conn, err := connect(ctx, dsn)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer func() { _ = conn.Close(ctx) }()
|
|
|
|
var stmt strings.Builder
|
|
sc := bufio.NewScanner(f)
|
|
for sc.Scan() {
|
|
line := strings.TrimSpace(sc.Text())
|
|
switch {
|
|
case line == "" || strings.HasPrefix(line, "--"):
|
|
continue
|
|
case strings.HasPrefix(line, `\connect `):
|
|
_ = conn.Close(ctx)
|
|
db := strings.TrimSpace(strings.TrimPrefix(line, `\connect `))
|
|
if conn, err = connect(ctx, withDatabase(dsn, db)); err != nil {
|
|
return err
|
|
}
|
|
continue
|
|
}
|
|
stmt.WriteString(line + "\n")
|
|
if strings.HasSuffix(line, ";") {
|
|
if _, err := conn.Exec(ctx, stmt.String()); err != nil {
|
|
return fmt.Errorf("%s: %w", strings.TrimSpace(stmt.String()), err)
|
|
}
|
|
stmt.Reset()
|
|
}
|
|
}
|
|
return sc.Err()
|
|
}
|
|
|
|
// connect retries while the server is still starting.
|
|
func connect(ctx context.Context, dsn string) (*pgx.Conn, error) {
|
|
for {
|
|
conn, err := pgx.Connect(ctx, dsn)
|
|
if err == nil {
|
|
return conn, nil
|
|
}
|
|
select {
|
|
case <-ctx.Done():
|
|
return nil, err
|
|
case <-time.After(time.Second):
|
|
}
|
|
}
|
|
}
|
|
|
|
func withDatabase(dsn, db string) string {
|
|
u, err := url.Parse(dsn)
|
|
if err != nil {
|
|
return dsn
|
|
}
|
|
u.Path = "/" + db
|
|
return u.String()
|
|
}
|