Skip to content

PostgreSQL backup tool with Point-In-Time-Recovery and restore verification

FEATURE (restores): add IsRestoreOwnership and IsRestorePrivileges toggles for PostgreSQL

Rostislav Dugin247b8b929525
diff --git a/.gitignore b/.gitignore
index 95002e1f..7b1d4c31 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,19 +1,20 @@
-ansible/
-databasus-data/
-.env
-pgdata/
-pgdata-test/
-mysqldata/
-mariadbdata/
-valkey-data/
-victoria-logs-data/
-wal-queue/
-temp/
-node_modules/
-.idea
-/articles
-
-.DS_Store
-/scripts
-.vscode/settings.json
-.claude
+ansible/
+databasus-data/
+.env
+pgdata/
+pgdata-test/
+mysqldata/
+mariadbdata/
+valkey-data/
+victoria-logs-data/
+wal-queue/
+temp/
+node_modules/
+.idea
+/articles
+
+.DS_Store
+/scripts
+.vscode/settings.json
+.claude
+backend/cleanup_test_db.exe
diff --git a/backend/Makefile b/backend/Makefile
index 661d21fa..35268c74 100644
--- a/backend/Makefile
+++ b/backend/Makefile
@@ -4,6 +4,10 @@ run:
go run cmd/main.go
test:
+ # cleanup_test_db resets the metadata DB AND each test PG container
+ # (drops leftover roles/databases and recreates testdb) so containers
+ # stay usable across runs - tests that REVOKE on public or create
+ # per-run roles would otherwise poison subsequent pg_dump calls.
go run ./cmd/cleanup_test_db
goose -dir ./migrations postgres "$(GOOSE_TEST_DBSTRING)" up
go test -p=1 -count=1 -failfast -timeout 15m ./internal/...
diff --git a/backend/cmd/cleanup_test_db/main.go b/backend/cmd/cleanup_test_db/main.go
index 554e6af6..c5377419 100644
--- a/backend/cmd/cleanup_test_db/main.go
+++ b/backend/cmd/cleanup_test_db/main.go
@@ -1,16 +1,31 @@
-// Resets the test database before `make test` runs.
+// Resets state before `make test` runs. Two distinct resets:
+//
+// 1. The Databasus metadata DB: drop and recreate the test schema referenced
+// by TEST_DATABASE_DSN so Goose migrations apply against a clean slate.
+//
+// 2. Each test PostgreSQL container (versions 12-18): drop every non-system
+// database (leftover backups, restores, and `testdb` itself), recreate
+// `testdb`, and drop every non-system role. This is what makes containers
+// usable across runs - tests like CreateReadOnlyUser issue
+// `REVOKE CREATE ON SCHEMA public FROM PUBLIC` and create per-test roles
+// that otherwise persist across runs and break subsequent pg_dump calls
+// with "permission denied for schema public".
//
// Reads the test DSN through config (config.GetEnv() auto-swaps DatabaseDsn to
// TestDatabaseDsn when IsTesting is true). IsTesting is detected from os.Args
-// containing the substring "test" — the binary path "cleanup_test_db" satisfies
+// containing the substring "test" - the binary path "cleanup_test_db" satisfies
// that. Renaming the binary or its directory will break detection.
package main
import (
+ "context"
+ "database/sql"
"fmt"
+ "log/slog"
"os"
"strings"
+ _ "github.com/lib/pq"
"gorm.io/driver/postgres"
"gorm.io/gorm"
gormLogger "gorm.io/gorm/logger"
@@ -19,10 +34,16 @@ import (
"databasus-backend/internal/util/logger"
)
-const systemDb = "postgres"
+const (
+ systemDb = "postgres"
+ testPgContainerUser = "testuser"
+ testPgContainerPassword = "testpassword"
+ testPgContainerDb = "testdb"
+)
func main() {
log := logger.GetLogger()
+ ctx := context.Background()
env := config.GetEnv()
if !env.IsTesting {
@@ -30,35 +51,188 @@ func main() {
os.Exit(1)
}
+ if err := resetMetadataDb(log, env); err != nil {
+ log.Error("failed to reset metadata DB", "error", err)
+ os.Exit(1)
+ }
+
+ if err := resetTestPostgresContainers(ctx, log, env); err != nil {
+ log.Error("failed to reset test PG containers", "error", err)
+ os.Exit(1)
+ }
+}
+
+func resetMetadataDb(log *slog.Logger, env *config.EnvVariables) error {
targetDbName, systemDsn, err := rewriteDbName(env.DatabaseDsn, systemDb)
if err != nil {
- log.Error("failed to parse TEST_DATABASE_DSN", "error", err)
- os.Exit(1)
+ return fmt.Errorf("parse TEST_DATABASE_DSN: %w", err)
}
- log.Info("resetting test DB", "db", targetDbName)
+ log.Info("resetting metadata DB", "db", targetDbName)
db, err := gorm.Open(postgres.Open(systemDsn), &gorm.Config{
Logger: gormLogger.Default.LogMode(gormLogger.Silent),
})
if err != nil {
- log.Error("failed to connect to system postgres DB", "error", err)
- os.Exit(1)
+ return fmt.Errorf("connect to system postgres DB: %w", err)
}
quoted := quoteIdentifier(targetDbName)
if err := db.Exec(fmt.Sprintf("DROP DATABASE IF EXISTS %s WITH (FORCE)", quoted)).Error; err != nil {
- log.Error("DROP DATABASE failed", "error", err)
- os.Exit(1)
+ return fmt.Errorf("drop database %s: %w", targetDbName, err)
}
if err := db.Exec(fmt.Sprintf("CREATE DATABASE %s", quoted)).Error; err != nil {
- log.Error("CREATE DATABASE failed", "error", err)
- os.Exit(1)
+ return fmt.Errorf("create database %s: %w", targetDbName, err)
+ }
+
+ log.Info("metadata DB reset complete", "db", targetDbName)
+ return nil
+}
+
+func resetTestPostgresContainers(ctx context.Context, log *slog.Logger, env *config.EnvVariables) error {
+ containers := []struct {
+ version string
+ port string
+ }{
+ {"12", env.TestPostgres12Port},
+ {"13", env.TestPostgres13Port},
+ {"14", env.TestPostgres14Port},
+ {"15", env.TestPostgres15Port},
+ {"16", env.TestPostgres16Port},
+ {"17", env.TestPostgres17Port},
+ {"18", env.TestPostgres18Port},
+ }
+
+ for _, c := range containers {
+ if c.port == "" {
+ continue
+ }
+
+ if err := resetOnePostgresContainer(ctx, log, env.TestLocalhost, c.version, c.port); err != nil {
+ return fmt.Errorf("PG %s on %s:%s: %w", c.version, env.TestLocalhost, c.port, err)
+ }
+ }
+
+ return nil
+}
+
+func resetOnePostgresContainer(ctx context.Context, log *slog.Logger, host, version, port string) error {
+ log = log.With("pg_version", version, "port", port)
+
+ systemDsn := fmt.Sprintf(
+ "host=%s port=%s user=%s password=%s dbname=%s sslmode=disable",
+ host, port, testPgContainerUser, testPgContainerPassword, systemDb,
+ )
+
+ db, err := sql.Open("postgres", systemDsn)
+ if err != nil {
+ return fmt.Errorf("open: %w", err)
+ }
+ defer func() { _ = db.Close() }()
+
+ if err := db.PingContext(ctx); err != nil {
+ return fmt.Errorf("ping: %w", err)
+ }
+
+ userDbs, err := listUserDatabases(ctx, db)
+ if err != nil {
+ return fmt.Errorf("list databases: %w", err)
+ }
+
+ for _, name := range userDbs {
+ if _, err := db.ExecContext(ctx, fmt.Sprintf(
+ "SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE datname = %s AND pid <> pg_backend_pid()",
+ quoteLiteral(name),
+ )); err != nil {
+ log.Warn("could not terminate connections to DB", "db", name, "error", err)
+ }
+
+ // No WITH (FORCE) - that's PG 13+ only and we support PG 12.
+ // pg_terminate_backend above already kicked off other sessions.
+ if _, err := db.ExecContext(
+ ctx,
+ fmt.Sprintf("DROP DATABASE IF EXISTS %s", quoteIdentifier(name)),
+ ); err != nil {
+ return fmt.Errorf("drop database %s: %w", name, err)
+ }
+ }
+
+ if _, err := db.ExecContext(
+ ctx,
+ fmt.Sprintf("CREATE DATABASE %s", quoteIdentifier(testPgContainerDb)),
+ ); err != nil {
+ return fmt.Errorf("create database %s: %w", testPgContainerDb, err)
+ }
+
+ userRoles, err := listUserRoles(ctx, db)
+ if err != nil {
+ return fmt.Errorf("list roles: %w", err)
+ }
+
+ owner := quoteIdentifier(testPgContainerUser)
+ for _, role := range userRoles {
+ quotedRole := quoteIdentifier(role)
+ // REASSIGN/DROP OWNED release any objects still pinned to the role so
+ // DROP ROLE can succeed. Failures here are best-effort - the role may
+ // own nothing, in which case these are no-ops.
+ _, _ = db.ExecContext(ctx, fmt.Sprintf("REASSIGN OWNED BY %s TO %s", quotedRole, owner))
+ _, _ = db.ExecContext(ctx, fmt.Sprintf("DROP OWNED BY %s", quotedRole))
+
+ if _, err := db.ExecContext(ctx, fmt.Sprintf("DROP ROLE IF EXISTS %s", quotedRole)); err != nil {
+ log.Warn("could not drop role", "role", role, "error", err)
+ }
+ }
+
+ log.Info("test PG container reset complete")
+ return nil
+}
+
+func listUserDatabases(ctx context.Context, db *sql.DB) ([]string, error) {
+ rows, err := db.QueryContext(ctx, `
+ SELECT datname FROM pg_database
+ WHERE NOT datistemplate
+ AND datname <> $1
+ `, systemDb)
+ if err != nil {
+ return nil, err
}
+ defer func() { _ = rows.Close() }()
- log.Info("test DB reset complete", "db", targetDbName)
+ var names []string
+ for rows.Next() {
+ var name string
+ if err := rows.Scan(&name); err != nil {
+ return nil, err
+ }
+ names = append(names, name)
+ }
+
+ return names, rows.Err()
+}
+
+func listUserRoles(ctx context.Context, db *sql.DB) ([]string, error) {
+ rows, err := db.QueryContext(ctx, `
+ SELECT rolname FROM pg_roles
+ WHERE rolname NOT IN ($1, $2)
+ AND rolname NOT LIKE 'pg\_%' ESCAPE '\'
+ `, systemDb, testPgContainerUser)
+ if err != nil {
+ return nil, err
+ }
+ defer func() { _ = rows.Close() }()
+
+ var names []string
+ for rows.Next() {
+ var name string
+ if err := rows.Scan(&name); err != nil {
+ return nil, err
+ }
+ names = append(names, name)
+ }
+
+ return names, rows.Err()
}
func rewriteDbName(dsn, newDbName string) (origDbName, rewritten string, err error) {
@@ -90,3 +264,7 @@ func rewriteDbName(dsn, newDbName string) (origDbName, rewritten string, err err
func quoteIdentifier(s string) string {
return `"` + strings.ReplaceAll(s, `"`, `""`) + `"`
}
+
+func quoteLiteral(s string) string {
+ return "'" + strings.ReplaceAll(s, "'", "''") + "'"
+}
diff --git a/backend/internal/features/databases/databases/postgresql/model.go b/backend/internal/features/databases/databases/postgresql/model.go
index e3098270..ebf28b68 100644
--- a/backend/internal/features/databases/databases/postgresql/model.go
+++ b/backend/internal/features/databases/databases/postgresql/model.go
@@ -52,6 +52,8 @@ type PostgresqlDatabase struct {
// restore settings (not saved to DB)
IsExcludeExtensions bool `json:"isExcludeExtensions" gorm:"-"`
+ IsRestoreOwnership bool `json:"isRestoreOwnership" gorm:"-"`
+ IsRestorePrivileges bool `json:"isRestorePrivileges" gorm:"-"`
}
func (p *PostgresqlDatabase) TableName() string {
diff --git a/backend/internal/features/restores/usecases/postgresql/restore_backup_uc.go b/backend/internal/features/restores/usecases/postgresql/restore_backup_uc.go
index 19173e31..55f34492 100644
--- a/backend/internal/features/restores/usecases/postgresql/restore_backup_uc.go
+++ b/backend/internal/features/restores/usecases/postgresql/restore_backup_uc.go
@@ -143,8 +143,12 @@ func (uc *RestorePostgresqlBackupUsecase) restoreViaStdin(
"--verbose",
"--clean",
"--if-exists",
- "--no-owner",
- "--no-acl",
+ }
+ if !pg.IsRestoreOwnership {
+ args = append(args, "--no-owner")
+ }
+ if !pg.IsRestorePrivileges {
+ args = append(args, "--no-acl")
}
ctx, cancel := context.WithTimeout(parentCtx, 23*time.Hour)
@@ -386,8 +390,12 @@ func (uc *RestorePostgresqlBackupUsecase) restoreViaFile(
"--verbose",
"--clean",
"--if-exists",
- "--no-owner",
- "--no-acl",
+ }
+ if !pg.IsRestoreOwnership {
+ args = append(args, "--no-owner")
+ }
+ if !pg.IsRestorePrivileges {
+ args = append(args, "--no-acl")
}
return uc.restoreFromStorage(
diff --git a/backend/internal/features/tests/postgresql_backup_restore_test.go b/backend/internal/features/tests/postgresql_backup_restore_test.go
index 959fa031..e7bf335c 100644
--- a/backend/internal/features/tests/postgresql_backup_restore_test.go
+++ b/backend/internal/features/tests/postgresql_backup_restore_test.go
@@ -196,6 +196,54 @@ func Test_BackupAndRestorePostgresql_WithoutExcludeExtensions_ExtensionsAreRecov
}
}
+func Test_BackupAndRestorePostgresql_WithRestoreOwnership_OwnerIsRestored(t *testing.T) {
+ env := config.GetEnv()
+ cases := []struct {
+ name string
+ version string
+ port string
+ }{
+ {"PostgreSQL 12", "12", env.TestPostgres12Port},
+ {"PostgreSQL 13", "13", env.TestPostgres13Port},
+ {"PostgreSQL 14", "14", env.TestPostgres14Port},
+ {"PostgreSQL 15", "15", env.TestPostgres15Port},
+ {"PostgreSQL 16", "16", env.TestPostgres16Port},
+ {"PostgreSQL 17", "17", env.TestPostgres17Port},
+ {"PostgreSQL 18", "18", env.TestPostgres18Port},
+ }
+
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ t.Parallel()
+ testBackupRestoreWithRestoreOwnershipForVersion(t, tc.version, tc.port)
+ })
+ }
+}
+
+func Test_BackupAndRestorePostgresql_WithRestorePrivileges_GrantIsRestored(t *testing.T) {
+ env := config.GetEnv()
+ cases := []struct {
+ name string
+ version string
+ port string
+ }{
+ {"PostgreSQL 12", "12", env.TestPostgres12Port},
+ {"PostgreSQL 13", "13", env.TestPostgres13Port},
+ {"PostgreSQL 14", "14", env.TestPostgres14Port},
+ {"PostgreSQL 15", "15", env.TestPostgres15Port},
+ {"PostgreSQL 16", "16", env.TestPostgres16Port},
+ {"PostgreSQL 17", "17", env.TestPostgres17Port},
+ {"PostgreSQL 18", "18", env.TestPostgres18Port},
+ }
+
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ t.Parallel()
+ testBackupRestoreWithRestorePrivilegesForVersion(t, tc.version, tc.port)
+ })
+ }
+}
+
func Test_BackupPostgresql_SchemaSelection_OnlySpecifiedSchemas(t *testing.T) {
env := config.GetEnv()
cases := []struct {
@@ -803,6 +851,241 @@ func testBackupRestoreWithoutExcludeExtensionsForVersion(
workspaces_testing.RemoveTestWorkspace(workspace, router)
}
+func testBackupRestoreWithRestoreOwnershipForVersion(t *testing.T, pgVersion, port string) {
+ container, err := connectToPostgresContainer(pgVersion, port)
+ assert.NoError(t, err)
+ defer func() {
+ if container.DB != nil {
+ container.DB.Close()
+ }
+ }()
+
+ suffix := uuid.New().String()[:8]
+ ownerRole := fmt.Sprintf("test_owner_%s", suffix)
+ tableName := fmt.Sprintf("test_ownership_data_%s", suffix)
+
+ _, err = container.DB.Exec(fmt.Sprintf(`
+ DROP TABLE IF EXISTS %s;
+ DROP ROLE IF EXISTS %s;
+ CREATE ROLE %s LOGIN PASSWORD 'placeholder';
+ CREATE TABLE %s (
+ id SERIAL PRIMARY KEY,
+ name TEXT NOT NULL,
+ value INTEGER NOT NULL
+ );
+ ALTER TABLE %s OWNER TO %s;
+ INSERT INTO %s (name, value) VALUES ('a', 1), ('b', 2), ('c', 3);
+ `, tableName, ownerRole, ownerRole, tableName, tableName, ownerRole, tableName))
+ assert.NoError(t, err)
+
+ defer func() {
+ _, _ = container.DB.Exec(fmt.Sprintf("DROP TABLE IF EXISTS %s;", tableName))
+ _, _ = container.DB.Exec(fmt.Sprintf("DROP ROLE IF EXISTS %s;", ownerRole))
+ }()
+
+ router := createTestRouter()
+ user := users_testing.CreateTestUser(users_enums.UserRoleMember)
+ workspace := workspaces_testing.CreateTestWorkspace("Ownership Test Workspace", user, router)
+
+ storage := storages.CreateTestStorage(workspace.ID)
+
+ database := createDatabaseViaAPI(
+ t, router, "Ownership Test Database", workspace.ID,
+ container.Host, container.Port,
+ container.Username, container.Password, container.Database,
+ user.Token,
+ )
+
+ enableBackupsViaAPI(
+ t, router, database.ID, storage.ID,
+ backups_config.BackupEncryptionNone, user.Token,
+ )
+
+ createBackupViaAPI(t, router, database.ID, user.Token)
+
+ backup := waitForBackupCompletion(t, router, database.ID, user.Token, 5*time.Minute)
+ assert.Equal(t, backups_core.BackupStatusCompleted, backup.Status)
+
+ newDBName := fmt.Sprintf("restored_ownership_%s_%s", pgVersion, suffix)
+ _, err = container.DB.Exec(fmt.Sprintf("DROP DATABASE IF EXISTS %s;", newDBName))
+ assert.NoError(t, err)
+
+ _, err = container.DB.Exec(fmt.Sprintf("CREATE DATABASE %s;", newDBName))
+ assert.NoError(t, err)
+
+ defer func() {
+ _, _ = container.DB.Exec(fmt.Sprintf("DROP DATABASE IF EXISTS %s;", newDBName))
+ }()
+
+ newDSN := fmt.Sprintf("host=%s port=%d user=%s password=%s dbname=%s sslmode=disable",
+ container.Host, container.Port, container.Username, container.Password, newDBName)
+ newDB, err := sqlx.Connect("postgres", newDSN)
+ assert.NoError(t, err)
+ defer newDB.Close()
+
+ createRestoreWithRestoreFlagsViaAPI(
+ t, router, backup.ID,
+ container.Host, container.Port,
+ container.Username, container.Password, newDBName,
+ true, // isRestoreOwnership
+ false, // isRestorePrivileges
+ user.Token,
+ )
+
+ restore := waitForRestoreCompletion(t, router, backup.ID, user.Token, 5*time.Minute)
+ assert.Equal(t, restores_core.RestoreStatusCompleted, restore.Status)
+
+ var restoredOwner string
+ err = newDB.Get(&restoredOwner, `
+ SELECT tableowner FROM pg_tables
+ WHERE schemaname = 'public' AND tablename = $1
+ `, tableName)
+ assert.NoError(t, err)
+ assert.Equal(
+ t,
+ ownerRole,
+ restoredOwner,
+ "Restored table should retain its original owner when isRestoreOwnership=true",
+ )
+
+ err = os.Remove(filepath.Join(config.GetEnv().DataFolder, backup.ID.String()))
+ if err != nil {
+ t.Logf("Warning: Failed to delete backup file: %v", err)
+ }
+
+ test_utils.MakeDeleteRequest(
+ t,
+ router,
+ "/api/v1/databases/"+database.ID.String(),
+ "Bearer "+user.Token,
+ http.StatusNoContent,
+ )
+ storages.RemoveTestStorage(storage.ID)
+ workspaces_testing.RemoveTestWorkspace(workspace, router)
+}
+
+func testBackupRestoreWithRestorePrivilegesForVersion(t *testing.T, pgVersion, port string) {
+ container, err := connectToPostgresContainer(pgVersion, port)
+ assert.NoError(t, err)
+ defer func() {
+ if container.DB != nil {
+ container.DB.Close()
+ }
+ }()
+
+ suffix := uuid.New().String()[:8]
+ granteeRole := fmt.Sprintf("test_grantee_%s", suffix)
+ tableName := fmt.Sprintf("test_privileges_data_%s", suffix)
+
+ _, err = container.DB.Exec(fmt.Sprintf(`
+ DROP TABLE IF EXISTS %s;
+ DROP ROLE IF EXISTS %s;
+ CREATE ROLE %s LOGIN PASSWORD 'placeholder';
+ CREATE TABLE %s (
+ id SERIAL PRIMARY KEY,
+ name TEXT NOT NULL,
+ value INTEGER NOT NULL
+ );
+ INSERT INTO %s (name, value) VALUES ('a', 1), ('b', 2), ('c', 3);
+ GRANT SELECT, INSERT ON %s TO %s;
+ `, tableName, granteeRole, granteeRole, tableName, tableName, tableName, granteeRole))
+ assert.NoError(t, err)
+
+ defer func() {
+ _, _ = container.DB.Exec(fmt.Sprintf("DROP TABLE IF EXISTS %s;", tableName))
+ _, _ = container.DB.Exec(fmt.Sprintf("DROP ROLE IF EXISTS %s;", granteeRole))
+ }()
+
+ router := createTestRouter()
+ user := users_testing.CreateTestUser(users_enums.UserRoleMember)
+ workspace := workspaces_testing.CreateTestWorkspace("Privileges Test Workspace", user, router)
+
+ storage := storages.CreateTestStorage(workspace.ID)
+
+ database := createDatabaseViaAPI(
+ t, router, "Privileges Test Database", workspace.ID,
+ container.Host, container.Port,
+ container.Username, container.Password, container.Database,
+ user.Token,
+ )
+
+ enableBackupsViaAPI(
+ t, router, database.ID, storage.ID,
+ backups_config.BackupEncryptionNone, user.Token,
+ )
+
+ createBackupViaAPI(t, router, database.ID, user.Token)
+
+ backup := waitForBackupCompletion(t, router, database.ID, user.Token, 5*time.Minute)
+ assert.Equal(t, backups_core.BackupStatusCompleted, backup.Status)
+
+ newDBName := fmt.Sprintf("restored_privileges_%s_%s", pgVersion, suffix)
+ _, err = container.DB.Exec(fmt.Sprintf("DROP DATABASE IF EXISTS %s;", newDBName))
+ assert.NoError(t, err)
+
+ _, err = container.DB.Exec(fmt.Sprintf("CREATE DATABASE %s;", newDBName))
+ assert.NoError(t, err)
+
+ defer func() {
+ _, _ = container.DB.Exec(fmt.Sprintf("DROP DATABASE IF EXISTS %s;", newDBName))
+ }()
+
+ newDSN := fmt.Sprintf("host=%s port=%d user=%s password=%s dbname=%s sslmode=disable",
+ container.Host, container.Port, container.Username, container.Password, newDBName)
+ newDB, err := sqlx.Connect("postgres", newDSN)
+ assert.NoError(t, err)
+ defer newDB.Close()
+
+ createRestoreWithRestoreFlagsViaAPI(
+ t, router, backup.ID,
+ container.Host, container.Port,
+ container.Username, container.Password, newDBName,
+ false, // isRestoreOwnership
+ true, // isRestorePrivileges
+ user.Token,
+ )
+
+ restore := waitForRestoreCompletion(t, router, backup.ID, user.Token, 5*time.Minute)
+ assert.Equal(t, restores_core.RestoreStatusCompleted, restore.Status)
+
+ var grantedPrivileges []string
+ err = newDB.Select(&grantedPrivileges, `
+ SELECT privilege_type FROM information_schema.role_table_grants
+ WHERE grantee = $1
+ AND table_schema = 'public'
+ AND table_name = $2
+ ORDER BY privilege_type
+ `, granteeRole, tableName)
+ assert.NoError(t, err)
+ assert.Contains(
+ t,
+ grantedPrivileges,
+ "SELECT",
+ "Restored table should retain SELECT grant when isRestorePrivileges=true",
+ )
+ assert.Contains(
+ t,
+ grantedPrivileges,
+ "INSERT",
+ "Restored table should retain INSERT grant when isRestorePrivileges=true",
+ )
+
+ err = os.Remove(filepath.Join(config.GetEnv().DataFolder, backup.ID.String()))
+ if err != nil {
+ t.Logf("Warning: Failed to delete backup file: %v", err)
+ }
+
+ test_utils.MakeDeleteRequest(
+ t,
+ router,
+ "/api/v1/databases/"+database.ID.String(),
+ "Bearer "+user.Token,
+ http.StatusNoContent,
+ )
+ storages.RemoveTestStorage(storage.ID)
+ workspaces_testing.RemoveTestWorkspace(workspace, router)
+}
+
func testBackupRestoreWithReadOnlyUserForVersion(t *testing.T, pgVersion, port string) {
container, err := connectToPostgresContainer(pgVersion, port)
assert.NoError(t, err)
@@ -1729,6 +2012,42 @@ func createRestoreWithOptionsViaAPI(
)
}
+func createRestoreWithRestoreFlagsViaAPI(
+ t *testing.T,
+ router *gin.Engine,
+ backupID uuid.UUID,
+ host string,
+ port int,
+ username string,
+ password string,
+ database string,
+ isRestoreOwnership bool,
+ isRestorePrivileges bool,
+ token string,
+) {
+ request := restores_core.RestoreBackupRequest{
+ PostgresqlDatabase: &pgtypes.PostgresqlDatabase{
+ Host: host,
+ Port: port,
+ Username: username,
+ Password: password,
+ Database: &database,
+ IsRestoreOwnership: isRestoreOwnership,
+ IsRestorePrivileges: isRestorePrivileges,
+ CpuCount: 1,
+ },
+ }
+
+ test_utils.MakePostRequest(
+ t,
+ router,
+ fmt.Sprintf("/api/v1/restores/%s/restore", backupID.String()),
+ "Bearer "+token,
+ request,
+ http.StatusOK,
+ )
+}
+
func createDatabaseWithSchemasViaAPI(
t *testing.T,
router *gin.Engine,
diff --git a/frontend/src/entity/databases/model/postgresql/PostgresqlDatabase.ts b/frontend/src/entity/databases/model/postgresql/PostgresqlDatabase.ts
index 4a60e195..04db8d72 100644
--- a/frontend/src/entity/databases/model/postgresql/PostgresqlDatabase.ts
+++ b/frontend/src/entity/databases/model/postgresql/PostgresqlDatabase.ts
@@ -21,4 +21,6 @@ export interface PostgresqlDatabase {
// restore settings (not saved to DB)
isExcludeExtensions?: boolean;
+ isRestoreOwnership?: boolean;
+ isRestorePrivileges?: boolean;
}
diff --git a/frontend/src/features/databases/ui/edit/EditPostgreSqlSpecificDataComponent.tsx b/frontend/src/features/databases/ui/edit/EditPostgreSqlSpecificDataComponent.tsx
index bbb2a5fd..3d47a70e 100644
--- a/frontend/src/features/databases/ui/edit/EditPostgreSqlSpecificDataComponent.tsx
+++ b/frontend/src/features/databases/ui/edit/EditPostgreSqlSpecificDataComponent.tsx
@@ -50,10 +50,11 @@ export const EditPostgreSqlSpecificDataComponent = ({
const [isTestingConnection, setIsTestingConnection] = useState(false);
const [isConnectionFailed, setIsConnectionFailed] = useState(false);
- const hasAdvancedValues =
- !!database.postgresql?.includeSchemas?.length ||
- !!database.postgresql?.excludeTables?.length ||
- !!database.postgresql?.isExcludeExtensions;
+ const hasAdvancedValues = isRestoreMode
+ ? !!database.postgresql?.isExcludeExtensions ||
+ !!database.postgresql?.isRestoreOwnership ||
+ !!database.postgresql?.isRestorePrivileges
+ : !!database.postgresql?.includeSchemas?.length || !!database.postgresql?.excludeTables?.length;
const [isShowAdvanced, setShowAdvanced] = useState(hasAdvancedValues);
const [hasAutoAddedPublicSchema, setHasAutoAddedPublicSchema] = useState(false);
@@ -542,32 +543,85 @@ export const EditPostgreSqlSpecificDataComponent = ({
{isRestoreMode && (
<div className="mb-1 flex w-full items-center">
- <div className="min-w-[150px]">Exclude extensions</div>
- <div className="flex items-center">
- <Checkbox
- checked={editingDatabase.postgresql?.isExcludeExtensions || false}
- onChange={(e) => {
- if (!editingDatabase.postgresql) return;
-
- setEditingDatabase({
- ...editingDatabase,
- postgresql: {
- ...editingDatabase.postgresql,
- isExcludeExtensions: e.target.checked,
- },
- });
- }}
+ <div className="flex min-w-[150px] items-center">
+ <span>Exclude extensions</span>
+ <Tooltip
+ className="cursor-pointer"
+ title="Skip restoring extension definitions (CREATE EXTENSION statements). Enable this if you're restoring to a managed PostgreSQL service where extensions are managed by the provider."
>
- Skip extensions
- </Checkbox>
+ <InfoCircleOutlined className="ml-2" style={{ color: 'gray' }} />
+ </Tooltip>
+ </div>
+ <Checkbox
+ checked={editingDatabase.postgresql?.isExcludeExtensions || false}
+ onChange={(e) => {
+ if (!editingDatabase.postgresql) return;
+
+ setEditingDatabase({
+ ...editingDatabase,
+ postgresql: {
+ ...editingDatabase.postgresql,
+ isExcludeExtensions: e.target.checked,
+ },
+ });
+ }}
+ />
+ </div>
+ )}
+ {isRestoreMode && (
+ <div className="mb-1 flex w-full items-center">
+ <div className="flex min-w-[150px] items-center">
+ <span>Restore ownership</span>
<Tooltip
className="cursor-pointer"
- title="Skip restoring extension definitions (CREATE EXTENSION statements). Enable this if you're restoring to a managed PostgreSQL service where extensions are managed by the provider."
+ title="Apply ALTER OWNER statements from the dump so restored objects keep their original owner. The connection user must be able to assign these roles - typically a superuser."
>
<InfoCircleOutlined className="ml-2" style={{ color: 'gray' }} />
</Tooltip>
</div>
+ <Checkbox
+ checked={editingDatabase.postgresql?.isRestoreOwnership || false}
+ onChange={(e) => {
+ if (!editingDatabase.postgresql) return;
+
+ setEditingDatabase({
+ ...editingDatabase,
+ postgresql: {
+ ...editingDatabase.postgresql,
+ isRestoreOwnership: e.target.checked,
+ },
+ });
+ }}
+ />
+ </div>
+ )}
+
+ {isRestoreMode && (
+ <div className="mb-1 flex w-full items-center">
+ <div className="flex min-w-[150px] items-center">
+ <span>Restore privileges</span>
+ <Tooltip
+ className="cursor-pointer"
+ title="Apply GRANT and REVOKE statements from the dump so restored objects keep their original ACLs. The connection user must be able to grant to the referenced roles - typically a superuser."
+ >
+ <InfoCircleOutlined className="ml-2" style={{ color: 'gray' }} />
+ </Tooltip>
+ </div>
+ <Checkbox
+ checked={editingDatabase.postgresql?.isRestorePrivileges || false}
+ onChange={(e) => {
+ if (!editingDatabase.postgresql) return;
+
+ setEditingDatabase({
+ ...editingDatabase,
+ postgresql: {
+ ...editingDatabase.postgresql,
+ isRestorePrivileges: e.target.checked,
+ },
+ });
+ }}
+ />
</div>
)}
</>