Skip to content

Commit 7111335

Browse files
authored
Remove database on schema creation failure (#837)
UDENG-6482
2 parents 93ae648 + 7f8f24b commit 7111335

File tree

3 files changed

+35
-0
lines changed

3 files changed

+35
-0
lines changed

internal/users/db/db.go

+5
Original file line numberDiff line numberDiff line change
@@ -73,6 +73,11 @@ func New(dbDir string) (*Manager, error) {
7373
log.Debugf(context.Background(), "Creating new SQLite database at %v", dbPath)
7474
_, err = db.Exec(createSchema)
7575
if err != nil {
76+
// Remove the database file if we failed to create the schema, to avoid that authd tries to use a broken
77+
// database on the next start.
78+
if removeErr := os.Remove(dbPath); removeErr != nil {
79+
log.Warningf(context.Background(), "Failed to remove database file after failed schema creation: %v", removeErr)
80+
}
7681
return nil, fmt.Errorf("failed to create schema: %w", err)
7782
}
7883
}

internal/users/db/db_test.go

+20
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ import (
99
"testing"
1010

1111
"github.com/stretchr/testify/require"
12+
"github.com/ubuntu/authd/internal/fileutils"
1213
"github.com/ubuntu/authd/internal/testutils/golden"
1314
"github.com/ubuntu/authd/internal/users/db"
1415
"github.com/ubuntu/authd/log"
@@ -91,6 +92,25 @@ func TestNew(t *testing.T) {
9192
}
9293
}
9394

95+
func TestDatabaseRemovedWhenSchemaCreationFails(t *testing.T) {
96+
// Don't run this test in parallel because it writes a global variable (via db.SetCreateSchemaQuery)
97+
origQuery := db.GetCreateSchemaQuery()
98+
db.SetCreateSchemaQuery("invalid query")
99+
t.Cleanup(func() {
100+
db.SetCreateSchemaQuery(origQuery)
101+
})
102+
103+
dbDir := t.TempDir()
104+
dbDestPath := filepath.Join(dbDir, db.Z_ForTests_DBName())
105+
106+
_, err := db.New(dbDir)
107+
require.Error(t, err, "New should return an error when schema creation fails")
108+
109+
exists, err := fileutils.FileExists(dbDestPath)
110+
require.NoError(t, err, "Failed to check if database file exists")
111+
require.False(t, exists, "Database file should not exist after failed schema creation")
112+
}
113+
94114
func TestUpdateUserEntry(t *testing.T) {
95115
t.Parallel()
96116

internal/users/db/export_test.go

+10
Original file line numberDiff line numberDiff line change
@@ -4,3 +4,13 @@ package db
44
func (m *Manager) Path() string {
55
return m.path
66
}
7+
8+
// GetCreateSchemaQuery exposes the query to create the schema for testing.
9+
func GetCreateSchemaQuery() string {
10+
return createSchema
11+
}
12+
13+
// SetCreateSchemaQuery sets the query to create the schema for testing.
14+
func SetCreateSchemaQuery(query string) {
15+
createSchema = query
16+
}

0 commit comments

Comments
 (0)