|
| 1 | +package cmd |
| 2 | + |
| 3 | +import ( |
| 4 | + "fmt" |
| 5 | + "regexp" |
| 6 | + |
| 7 | + log "github.com/sirupsen/logrus" |
| 8 | + "github.com/spf13/cobra" |
| 9 | + |
| 10 | + "github.com/onyx-dot-app/onyx/tools/ods/internal/docker" |
| 11 | + "github.com/onyx-dot-app/onyx/tools/ods/internal/postgres" |
| 12 | + "github.com/onyx-dot-app/onyx/tools/ods/internal/prompt" |
| 13 | +) |
| 14 | + |
| 15 | +// validIdentifier matches valid PostgreSQL identifiers (letters, digits, underscores, starting with letter/underscore) |
| 16 | +var validIdentifier = regexp.MustCompile(`^[a-zA-Z_][a-zA-Z0-9_]*$`) |
| 17 | + |
| 18 | +// DBDropOptions holds options for the db drop command. |
| 19 | +type DBDropOptions struct { |
| 20 | + Yes bool |
| 21 | + Schema string |
| 22 | +} |
| 23 | + |
| 24 | +// NewDBDropCommand creates the db drop command. |
| 25 | +func NewDBDropCommand() *cobra.Command { |
| 26 | + opts := &DBDropOptions{} |
| 27 | + |
| 28 | + cmd := &cobra.Command{ |
| 29 | + Use: "drop", |
| 30 | + Short: "Drop and recreate the database", |
| 31 | + Long: `Drop and recreate the PostgreSQL database. |
| 32 | +
|
| 33 | +This command will: |
| 34 | + 1. Find the running PostgreSQL container |
| 35 | + 2. Drop all connections to the database |
| 36 | + 3. Drop the database (or schema if --schema is specified) |
| 37 | + 4. Recreate the database (or schema) |
| 38 | +
|
| 39 | +WARNING: This is a destructive operation. All data will be lost.`, |
| 40 | + Run: func(cmd *cobra.Command, args []string) { |
| 41 | + runDBDrop(opts) |
| 42 | + }, |
| 43 | + } |
| 44 | + |
| 45 | + cmd.Flags().BoolVar(&opts.Yes, "yes", false, "Skip confirmation prompt") |
| 46 | + cmd.Flags().StringVar(&opts.Schema, "schema", "", "Drop a specific schema instead of the entire database") |
| 47 | + |
| 48 | + return cmd |
| 49 | +} |
| 50 | + |
| 51 | +func runDBDrop(opts *DBDropOptions) { |
| 52 | + // Find PostgreSQL container |
| 53 | + container, err := docker.FindPostgresContainer() |
| 54 | + if err != nil { |
| 55 | + log.Fatalf("Failed to find PostgreSQL container: %v", err) |
| 56 | + } |
| 57 | + log.Infof("Found PostgreSQL container: %s", container) |
| 58 | + |
| 59 | + config := postgres.NewConfigFromEnv() |
| 60 | + |
| 61 | + // Confirmation prompt |
| 62 | + if !opts.Yes { |
| 63 | + var msg string |
| 64 | + if opts.Schema != "" { |
| 65 | + msg = fmt.Sprintf("This will DROP the schema '%s' in database '%s'. All data will be lost. Continue? (yes/no): ", |
| 66 | + opts.Schema, config.Database) |
| 67 | + } else { |
| 68 | + msg = fmt.Sprintf("This will DROP and RECREATE the database '%s'. All data will be lost. Continue? (yes/no): ", |
| 69 | + config.Database) |
| 70 | + } |
| 71 | + |
| 72 | + if !prompt.Confirm(msg) { |
| 73 | + log.Info("Aborted.") |
| 74 | + return |
| 75 | + } |
| 76 | + } |
| 77 | + |
| 78 | + env := config.Env() |
| 79 | + |
| 80 | + if opts.Schema != "" { |
| 81 | + // Validate schema name to prevent SQL injection |
| 82 | + if !validIdentifier.MatchString(opts.Schema) { |
| 83 | + log.Fatalf("Invalid schema name: %s", opts.Schema) |
| 84 | + } |
| 85 | + |
| 86 | + // Drop and recreate schema |
| 87 | + log.Infof("Dropping schema: %s", opts.Schema) |
| 88 | + dropSchemaSQL := fmt.Sprintf("DROP SCHEMA IF EXISTS %s CASCADE;", opts.Schema) |
| 89 | + createSchemaSQL := fmt.Sprintf("CREATE SCHEMA %s;", opts.Schema) |
| 90 | + |
| 91 | + args := append(config.PsqlArgs(), "-c", dropSchemaSQL) |
| 92 | + if err := docker.ExecWithEnv(container, env, append([]string{"psql"}, args...)...); err != nil { |
| 93 | + log.Fatalf("Failed to drop schema: %v", err) |
| 94 | + } |
| 95 | + |
| 96 | + args = append(config.PsqlArgs(), "-c", createSchemaSQL) |
| 97 | + if err := docker.ExecWithEnv(container, env, append([]string{"psql"}, args...)...); err != nil { |
| 98 | + log.Fatalf("Failed to create schema: %v", err) |
| 99 | + } |
| 100 | + |
| 101 | + log.Infof("Schema '%s' dropped and recreated successfully", opts.Schema) |
| 102 | + } else { |
| 103 | + // Drop and recreate entire database |
| 104 | + log.Infof("Dropping database: %s", config.Database) |
| 105 | + |
| 106 | + // Use template1 as maintenance database (can't drop a DB while connected to it) |
| 107 | + maintenanceDB := "template1" |
| 108 | + |
| 109 | + // Terminate existing connections |
| 110 | + // Validate database name to prevent SQL injection |
| 111 | + if !validIdentifier.MatchString(config.Database) { |
| 112 | + log.Fatalf("Invalid database name: %s", config.Database) |
| 113 | + } |
| 114 | + |
| 115 | + // Terminate existing connections |
| 116 | + terminateSQL := fmt.Sprintf( |
| 117 | + "SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE datname = '%s' AND pid <> pg_backend_pid();", |
| 118 | + config.Database) |
| 119 | + |
| 120 | + args := []string{"psql", "-U", config.User, "-d", maintenanceDB, "-c", terminateSQL} |
| 121 | + if err := docker.ExecWithEnv(container, env, args...); err != nil { |
| 122 | + log.Warnf("Failed to terminate connections (this may be okay): %v", err) |
| 123 | + } |
| 124 | + |
| 125 | + // Drop database |
| 126 | + dropSQL := fmt.Sprintf("DROP DATABASE IF EXISTS %s;", config.Database) |
| 127 | + args = []string{"psql", "-U", config.User, "-d", maintenanceDB, "-c", dropSQL} |
| 128 | + if err := docker.ExecWithEnv(container, env, args...); err != nil { |
| 129 | + log.Fatalf("Failed to drop database: %v", err) |
| 130 | + } |
| 131 | + |
| 132 | + // Create database |
| 133 | + createSQL := fmt.Sprintf("CREATE DATABASE %s;", config.Database) |
| 134 | + args = []string{"psql", "-U", config.User, "-d", maintenanceDB, "-c", createSQL} |
| 135 | + if err := docker.ExecWithEnv(container, env, args...); err != nil { |
| 136 | + log.Fatalf("Failed to create database: %v", err) |
| 137 | + } |
| 138 | + |
| 139 | + log.Infof("Database '%s' dropped and recreated successfully", config.Database) |
| 140 | + log.Info("Run 'ods db upgrade' to apply migrations") |
| 141 | + } |
| 142 | +} |
0 commit comments