Disallow zero as a schema version (#2469)

This commit is contained in:
Simon Binder 2023-06-08 11:53:21 +02:00
parent dd6d7bfd70
commit 657ee5133f
No known key found for this signature in database
GPG Key ID: 7891917E4147B8C0
3 changed files with 26 additions and 0 deletions

View File

@ -1,3 +1,7 @@
## 2.8.3-dev
- Forbid `schemaVersion` returning `0`, as this causes issues in the migrator.
## 2.8.2
- Fix prepared statements leaking when the statement cache is disabled.

View File

@ -20,6 +20,9 @@ abstract class GeneratedDatabase extends DatabaseConnectionUser
/// Specify the schema version of your database. Whenever you change or add
/// tables, you should bump this field and provide a [migration] strategy.
///
/// The [schemaVersion] must be positive. Typically, one starts with a value
/// of `1` and increments the value for each modification to the schema.
@override
int get schemaVersion;
@ -110,6 +113,14 @@ abstract class GeneratedDatabase extends DatabaseConnectionUser
@nonVirtual
Future<void> beforeOpen(QueryExecutor executor, OpeningDetails details) {
return _runConnectionZoned(BeforeOpenRunner(this, executor), () async {
if (schemaVersion <= 0) {
throw StateError(
'The schemaVersion of your database must be positive. \n'
"A value of zero can't be distinguished from an uninitialized "
'database, which causes issues in the migrator',
);
}
if (details.wasCreated) {
final migrator = createMigrator();
await _resolvedMigration.onCreate(migrator);

View File

@ -110,4 +110,15 @@ void main() {
verify(ex2.runSelect('SELECT 1', []));
verifyNever(ex2.runSelect(any, any));
});
test('disallows zero as a schema version', () async {
var db = TodoDb(MockExecutor(OpeningDetails(null, 0)))..schemaVersion = 0;
await expectLater(db.customSelect('SELECT 1').get(), throwsStateError);
db = TodoDb(MockExecutor(OpeningDetails(null, 0)))..schemaVersion = -1;
await expectLater(db.customSelect('SELECT 1').get(), throwsStateError);
db = TodoDb(MockExecutor(OpeningDetails(null, 0)))..schemaVersion = 1;
await expectLater(db.customSelect('SELECT 1').get(), completes);
});
}