Skip to content

Commit

Permalink
Warn on duplicate autoIncrement columns (#3130)
Browse files Browse the repository at this point in the history
  • Loading branch information
simolus3 committed Aug 4, 2024
1 parent ceeae72 commit 24905dc
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 2 deletions.
14 changes: 12 additions & 2 deletions drift_dev/lib/src/analysis/resolver/dart/table.dart
Original file line number Diff line number Diff line change
Expand Up @@ -73,14 +73,24 @@ class DartTableResolver extends LocalElementResolver<DiscoveredDartTable> {
],
);

if (primaryKey != null &&
columns.any((c) => c.constraints.any((e) => e is PrimaryKeyColumn))) {
final columnsWithPrimaryKeyConstraint = columns
.where((c) => c.constraints.any((e) => e is PrimaryKeyColumn))
.length;
if (primaryKey != null && columnsWithPrimaryKeyConstraint > 0) {
reportError(DriftAnalysisError.forDartElement(
element,
"Tables can't override primaryKey and use autoIncrement()",
));
}

if (columnsWithPrimaryKeyConstraint > 1) {
reportError(DriftAnalysisError.forDartElement(
element,
'More than one column uses autoIncrement(). This would require '
'multiple primary keys, which is not supported.',
));
}

if (primaryKey != null &&
primaryKey.length == 1 &&
primaryKey.first.constraints.contains(const UniqueColumn())) {
Expand Down
20 changes: 20 additions & 0 deletions drift_dev/test/analysis/resolver/dart/table_parser_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -325,4 +325,24 @@ void main() {
]),
);
});

test('warns about tables with two autoIncrement columns', () async {
final backend = await TestBackend.inTest({
'a|lib/a.dart': '''
import 'package:drift/drift.dart';
class MyAwesomeTable extends Table {
IntColumn get id => integer().autoIncrement()();
TextColumn get title => text().withLength(min: 1, max: 32)();
TextColumn get description => text()();
IntColumn get sortOrder => integer().autoIncrement()();
}
'''
});

final file = await backend.analyze('package:a/a.dart');

expect(file.allErrors,
[isDriftError(contains('More than one column uses autoIncrement()'))]);
});
}

0 comments on commit 24905dc

Please sign in to comment.