Skip to content

Commit 31bddd2

Browse files
committed
feat(data): implement seeding for admin user and app config
Adds the `seedInitialAdminAndConfig` method to `DatabaseSeedingService`. This method inserts the default `AppConfig` and the initial admin `User` from the shared fixtures into the database. The operation is idempotent, using `ON CONFLICT DO NOTHING` to prevent overwriting existing data on subsequent server starts.
1 parent 04189f3 commit 31bddd2

File tree

1 file changed

+58
-0
lines changed

1 file changed

+58
-0
lines changed

lib/src/services/database_seeding_service.dart

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -230,4 +230,62 @@ class DatabaseSeedingService {
230230
);
231231
}
232232
}
233+
234+
/// Seeds the database with the initial AppConfig and the default admin user.
235+
///
236+
/// This method is idempotent, using `ON CONFLICT DO NOTHING` to prevent
237+
/// errors if the data already exists. It runs within a single transaction.
238+
Future<void> seedInitialAdminAndConfig() async {
239+
_log.info('Seeding initial AppConfig and admin user...');
240+
try {
241+
await _connection.execute('BEGIN');
242+
try {
243+
// Seed AppConfig
244+
_log.fine('Seeding AppConfig...');
245+
final appConfig = AppConfig.fromJson(appConfigFixtureData);
246+
await _connection.execute(
247+
Sql.named(
248+
'INSERT INTO app_config (id, user_preference_limits) '
249+
'VALUES (@id, @user_preference_limits) '
250+
'ON CONFLICT (id) DO NOTHING',
251+
),
252+
parameters: appConfig.toJson(),
253+
);
254+
255+
// Seed Admin User
256+
_log.fine('Seeding admin user...');
257+
// Find the admin user in the fixture data.
258+
final adminUserData = usersFixturesData.firstWhere(
259+
(user) => (user['roles'] as List).contains(UserRoles.admin),
260+
orElse: () => throw StateError('Admin user not found in fixtures.'),
261+
);
262+
final adminUser = User.fromJson(adminUserData);
263+
await _connection.execute(
264+
Sql.named(
265+
'INSERT INTO users (id, email, roles) '
266+
'VALUES (@id, @email, @roles) '
267+
'ON CONFLICT (id) DO NOTHING',
268+
),
269+
parameters: adminUser.toJson(),
270+
);
271+
272+
await _connection.execute('COMMIT');
273+
_log.info(
274+
'Initial AppConfig and admin user seeding completed successfully.',
275+
);
276+
} catch (e) {
277+
await _connection.execute('ROLLBACK');
278+
rethrow;
279+
}
280+
} on Object catch (e, st) {
281+
_log.severe(
282+
'An error occurred during initial admin/config seeding.',
283+
e,
284+
st,
285+
);
286+
throw OperationFailedException(
287+
'Failed to seed initial admin/config data: $e',
288+
);
289+
}
290+
}
233291
}

0 commit comments

Comments
 (0)