File tree 3 files changed +35
-0
lines changed
3 files changed +35
-0
lines changed Original file line number Diff line number Diff line change @@ -73,6 +73,11 @@ func New(dbDir string) (*Manager, error) {
73
73
log .Debugf (context .Background (), "Creating new SQLite database at %v" , dbPath )
74
74
_ , err = db .Exec (createSchema )
75
75
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
+ }
76
81
return nil , fmt .Errorf ("failed to create schema: %w" , err )
77
82
}
78
83
}
Original file line number Diff line number Diff line change 9
9
"testing"
10
10
11
11
"github.com/stretchr/testify/require"
12
+ "github.com/ubuntu/authd/internal/fileutils"
12
13
"github.com/ubuntu/authd/internal/testutils/golden"
13
14
"github.com/ubuntu/authd/internal/users/db"
14
15
"github.com/ubuntu/authd/log"
@@ -91,6 +92,25 @@ func TestNew(t *testing.T) {
91
92
}
92
93
}
93
94
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
+
94
114
func TestUpdateUserEntry (t * testing.T ) {
95
115
t .Parallel ()
96
116
Original file line number Diff line number Diff line change @@ -4,3 +4,13 @@ package db
4
4
func (m * Manager ) Path () string {
5
5
return m .path
6
6
}
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
+ }
You can’t perform that action at this time.
0 commit comments