|
| 1 | +/* |
| 2 | +2026 © Postgres.ai |
| 3 | +*/ |
| 4 | + |
| 5 | +package snapshot |
| 6 | + |
| 7 | +import ( |
| 8 | + "context" |
| 9 | + "fmt" |
| 10 | + "regexp" |
| 11 | + |
| 12 | + "github.com/docker/docker/api/types/container" |
| 13 | + "github.com/docker/docker/api/types/filters" |
| 14 | + "github.com/docker/docker/client" |
| 15 | + |
| 16 | + "gitlab.com/postgres-ai/database-lab/v3/internal/diagnostic" |
| 17 | + "gitlab.com/postgres-ai/database-lab/v3/internal/retrieval/engine/postgres/tools" |
| 18 | + "gitlab.com/postgres-ai/database-lab/v3/internal/retrieval/engine/postgres/tools/cont" |
| 19 | + "gitlab.com/postgres-ai/database-lab/v3/internal/retrieval/engine/postgres/tools/health" |
| 20 | + "gitlab.com/postgres-ai/database-lab/v3/pkg/config/global" |
| 21 | + "gitlab.com/postgres-ai/database-lab/v3/pkg/log" |
| 22 | +) |
| 23 | + |
| 24 | +const ( |
| 25 | + renameContainerPrefix = "dblab_rename_" |
| 26 | + dbNameRules = "must start with a letter or underscore" + |
| 27 | + " and contain only letters, digits, underscores, and hyphens" |
| 28 | +) |
| 29 | + |
| 30 | +var validDBNameRegex = regexp.MustCompile(`^[a-zA-Z_][a-zA-Z0-9_-]*$`) |
| 31 | + |
| 32 | +// renameParams holds parameters for running database renames in a standalone container. |
| 33 | +type renameParams struct { |
| 34 | + dockerClient *client.Client |
| 35 | + engineProps *global.EngineProps |
| 36 | + globalCfg *global.Config |
| 37 | + dataDir string |
| 38 | + renames map[string]string |
| 39 | +} |
| 40 | + |
| 41 | +// executeDatabaseRenames runs ALTER DATABASE RENAME statements inside an already-running container. |
| 42 | +func executeDatabaseRenames( |
| 43 | + ctx context.Context, |
| 44 | + dockerClient *client.Client, |
| 45 | + containerID, user, connDB string, |
| 46 | + renames map[string]string, |
| 47 | +) error { |
| 48 | + for oldName, newName := range renames { |
| 49 | + log.Msg(fmt.Sprintf("Renaming database %q to %q", oldName, newName)) |
| 50 | + |
| 51 | + cmd := buildRenameCommand(user, connDB, oldName, newName) |
| 52 | + |
| 53 | + output, err := tools.ExecCommandWithOutput(ctx, dockerClient, containerID, container.ExecOptions{Cmd: cmd}) |
| 54 | + if err != nil { |
| 55 | + return fmt.Errorf("failed to rename database %q to %q: %w", oldName, newName, err) |
| 56 | + } |
| 57 | + |
| 58 | + log.Msg("Rename result: ", output) |
| 59 | + } |
| 60 | + |
| 61 | + return nil |
| 62 | +} |
| 63 | + |
| 64 | +// runDatabaseRename renames databases using ALTER DATABASE in a temporary container. |
| 65 | +func runDatabaseRename(ctx context.Context, params renameParams) error { |
| 66 | + if len(params.renames) == 0 { |
| 67 | + return nil |
| 68 | + } |
| 69 | + |
| 70 | + connDB := params.globalCfg.Database.Name() |
| 71 | + |
| 72 | + if err := validateDatabaseRenames(params.renames, connDB); err != nil { |
| 73 | + return err |
| 74 | + } |
| 75 | + |
| 76 | + pgVersion, err := tools.DetectPGVersion(params.dataDir) |
| 77 | + if err != nil { |
| 78 | + return fmt.Errorf("failed to detect postgres version: %w", err) |
| 79 | + } |
| 80 | + |
| 81 | + image := fmt.Sprintf("postgresai/extended-postgres:%g", pgVersion) |
| 82 | + |
| 83 | + if err := tools.PullImage(ctx, params.dockerClient, image); err != nil { |
| 84 | + return fmt.Errorf("failed to pull image for database rename: %w", err) |
| 85 | + } |
| 86 | + |
| 87 | + pwd, err := tools.GeneratePassword() |
| 88 | + if err != nil { |
| 89 | + return fmt.Errorf("failed to generate password: %w", err) |
| 90 | + } |
| 91 | + |
| 92 | + hostConfig, err := cont.BuildHostConfig(ctx, params.dockerClient, params.dataDir, nil) |
| 93 | + if err != nil { |
| 94 | + return fmt.Errorf("failed to build host config: %w", err) |
| 95 | + } |
| 96 | + |
| 97 | + containerName := renameContainerPrefix + params.engineProps.InstanceID |
| 98 | + |
| 99 | + containerID, err := tools.CreateContainerIfMissing(ctx, params.dockerClient, containerName, |
| 100 | + &container.Config{ |
| 101 | + Labels: map[string]string{ |
| 102 | + cont.DBLabControlLabel: cont.DBLabRenameLabel, |
| 103 | + cont.DBLabInstanceIDLabel: params.engineProps.InstanceID, |
| 104 | + cont.DBLabEngineNameLabel: params.engineProps.ContainerName, |
| 105 | + }, |
| 106 | + Env: []string{ |
| 107 | + "PGDATA=" + params.dataDir, |
| 108 | + "POSTGRES_PASSWORD=" + pwd, |
| 109 | + }, |
| 110 | + Image: image, |
| 111 | + Healthcheck: health.GetConfig( |
| 112 | + params.globalCfg.Database.User(), |
| 113 | + connDB, |
| 114 | + ), |
| 115 | + }, |
| 116 | + hostConfig, |
| 117 | + ) |
| 118 | + if err != nil { |
| 119 | + return fmt.Errorf("failed to create rename container: %w", err) |
| 120 | + } |
| 121 | + |
| 122 | + defer tools.RemoveContainer(ctx, params.dockerClient, containerID, cont.StopPhysicalTimeout) |
| 123 | + |
| 124 | + defer func() { |
| 125 | + if err != nil { |
| 126 | + tools.PrintContainerLogs(ctx, params.dockerClient, containerName) |
| 127 | + tools.PrintLastPostgresLogs(ctx, params.dockerClient, containerName, params.dataDir) |
| 128 | + |
| 129 | + filterArgs := filters.NewArgs( |
| 130 | + filters.KeyValuePair{Key: "label", |
| 131 | + Value: fmt.Sprintf("%s=%s", cont.DBLabControlLabel, cont.DBLabRenameLabel)}) |
| 132 | + |
| 133 | + if diagErr := diagnostic.CollectDiagnostics(ctx, params.dockerClient, filterArgs, containerName, params.dataDir); diagErr != nil { |
| 134 | + log.Err("failed to collect rename container diagnostics", diagErr) |
| 135 | + } |
| 136 | + } |
| 137 | + }() |
| 138 | + |
| 139 | + log.Msg(fmt.Sprintf("Running rename container: %s. ID: %v", containerName, containerID)) |
| 140 | + |
| 141 | + if err = params.dockerClient.ContainerStart(ctx, containerID, container.StartOptions{}); err != nil { |
| 142 | + return fmt.Errorf("failed to start rename container: %w", err) |
| 143 | + } |
| 144 | + |
| 145 | + log.Msg("Waiting for rename container readiness") |
| 146 | + log.Msg(fmt.Sprintf("View logs using the command: %s %s", tools.ViewLogsCmd, containerName)) |
| 147 | + |
| 148 | + if err = tools.CheckContainerReadiness(ctx, params.dockerClient, containerID); err != nil { |
| 149 | + return fmt.Errorf("rename container readiness check failed: %w", err) |
| 150 | + } |
| 151 | + |
| 152 | + user := params.globalCfg.Database.User() |
| 153 | + |
| 154 | + if err = executeDatabaseRenames(ctx, params.dockerClient, containerID, user, connDB, params.renames); err != nil { |
| 155 | + return err |
| 156 | + } |
| 157 | + |
| 158 | + if err = tools.RunCheckpoint(ctx, params.dockerClient, containerID, user, connDB); err != nil { |
| 159 | + return fmt.Errorf("failed to run checkpoint after rename: %w", err) |
| 160 | + } |
| 161 | + |
| 162 | + if err = tools.StopPostgres(ctx, params.dockerClient, containerID, params.dataDir, tools.DefaultStopTimeout); err != nil { |
| 163 | + log.Msg("failed to stop postgres after rename", err) |
| 164 | + } |
| 165 | + |
| 166 | + return nil |
| 167 | +} |
| 168 | + |
| 169 | +func buildRenameCommand(username, connDB, oldName, newName string) []string { |
| 170 | + return []string{ |
| 171 | + "psql", |
| 172 | + "-U", username, |
| 173 | + "-d", connDB, |
| 174 | + "-XAtc", fmt.Sprintf(`ALTER DATABASE "%s" RENAME TO "%s"`, oldName, newName), |
| 175 | + } |
| 176 | +} |
| 177 | + |
| 178 | +func validateDatabaseRenames(renames map[string]string, connDB string) error { |
| 179 | + targets := make(map[string]string, len(renames)) |
| 180 | + |
| 181 | + for oldName, newName := range renames { |
| 182 | + if oldName == "" || newName == "" { |
| 183 | + return fmt.Errorf("database rename names must not be empty") |
| 184 | + } |
| 185 | + |
| 186 | + if !validDBNameRegex.MatchString(oldName) { |
| 187 | + return fmt.Errorf("invalid database name %q: %s", oldName, dbNameRules) |
| 188 | + } |
| 189 | + |
| 190 | + if !validDBNameRegex.MatchString(newName) { |
| 191 | + return fmt.Errorf("invalid database name %q: %s", newName, dbNameRules) |
| 192 | + } |
| 193 | + |
| 194 | + if oldName == connDB { |
| 195 | + return fmt.Errorf("cannot rename database %q: it is used as the connection database", oldName) |
| 196 | + } |
| 197 | + |
| 198 | + if newName == connDB { |
| 199 | + return fmt.Errorf("cannot rename database %q to %q: target name is the connection database", oldName, newName) |
| 200 | + } |
| 201 | + |
| 202 | + if oldName == newName { |
| 203 | + return fmt.Errorf("cannot rename database %q to itself", oldName) |
| 204 | + } |
| 205 | + |
| 206 | + if prev, ok := targets[newName]; ok { |
| 207 | + return fmt.Errorf("duplicate rename target %q: both %q and %q rename to the same database", newName, prev, oldName) |
| 208 | + } |
| 209 | + |
| 210 | + targets[newName] = oldName |
| 211 | + } |
| 212 | + |
| 213 | + for oldName, newName := range renames { |
| 214 | + if _, ok := renames[newName]; ok { |
| 215 | + return fmt.Errorf("chained rename conflict: %q renames to %q, which is also a rename source", oldName, newName) |
| 216 | + } |
| 217 | + } |
| 218 | + |
| 219 | + return nil |
| 220 | +} |
0 commit comments