Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Warn when no definition is found for a specified primary key #790

Open
wants to merge 12 commits into
base: develop
Choose a base branch
from
11 changes: 8 additions & 3 deletions floor_generator/lib/processor/entity_processor.dart
Original file line number Diff line number Diff line change
Expand Up @@ -221,22 +221,27 @@ class EntityProcessor extends QueryableProcessor<Entity> {
.getAnnotation(annotations.Entity)
?.getField(AnnotationField.entityPrimaryKeys)
?.toListValue()
?.map((object) => object.toStringValue());
?.map((object) => object.toStringValue())
.toSet();

if (compoundPrimaryKeyColumnNames == null ||
compoundPrimaryKeyColumnNames.isEmpty) {
return null;
}

final compoundPrimaryKeyFields = fields.where((field) {
return compoundPrimaryKeyColumnNames.any(
(primaryKeyColumnName) => field.columnName == primaryKeyColumnName);
return compoundPrimaryKeyColumnNames.contains(field.columnName);
}).toList();

if (compoundPrimaryKeyFields.isEmpty) {
throw _processorError.missingPrimaryKey;
}

if (compoundPrimaryKeyFields.length !=
compoundPrimaryKeyColumnNames.length) {
throw _processorError.primaryKeyNotFound;
}

return PrimaryKey(compoundPrimaryKeyFields, false);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,14 @@ class EntityProcessorError {
);
}

InvalidGenerationSourceError get primaryKeyNotFound {
return InvalidGenerationSourceError(
'Primary key not found for ${_classElement.displayName}.',
todo: 'Make sure that all the primary keys you defined exist as columns.',
element: _classElement,
);
}

InvalidGenerationSourceError get missingParentColumns {
return InvalidGenerationSourceError(
'No parent columns defined for foreign key.',
Expand Down
15 changes: 15 additions & 0 deletions floor_generator/test/processor/entity_processor_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -482,6 +482,21 @@ void main() {
throwsInvalidGenerationSourceError(
EntityProcessorError(classElements).missingPrimaryKey));
});
test('one primary key missing in compound primary key', () async {
stephanmantel marked this conversation as resolved.
Show resolved Hide resolved
final classElements = await createClassElement('''
@Entity(primaryKeys: ['ID', 'email'])
class Example {
final int id;
final String email;
}
''');

final processor = EntityProcessor(classElements, {});
expect(
processor.process,
throwsInvalidGenerationSourceError(
EntityProcessorError(classElements).primaryKeyNotFound));
});
test('compound primary key mismatch', () async {
final classElements = await createClassElement('''
@Entity(
Expand Down