objectbox / objectbox-dart

Flutter database for super-fast Dart object persistence
https://docs.objectbox.io/getting-started
Apache License 2.0
927 stars 115 forks source link

Allowing a different Constructor as the one used by ObjectBox #570

Open FabrizioG202 opened 6 months ago

FabrizioG202 commented 6 months ago

When I am creating Entities which have custom types, ObjectBox tries to use the default constructor or the first with parameter names matching the Entity's property names (https://docs.objectbox.io/entity-annotations#objectbox-database-persistence-with-entity-annotations).

If I understood correctly, this would enforce the creation of a custom constructor for use by the user while the default would be reserved for ObjectBox.

For example, the following does not build using the generator:

@Entity()
final class Person {
  Person.ob({
    required this.uid,
    required this.name,
    required this.id,
    required this.metadataBytes,
  }) : metadata = PersonMetadata.fromBytes(metadataBytes);

  Person({
    required this.uid,
    required this.name,
    required this.metadata,
    this.id = 0,
  });

  int id;

  @Index()
  final String uid;
  final String name;

  @Transient()
  final PersonMetadata metadata;

  @Property(type: PropertyType.byteVector)
  final ByteData metadataBytes;
}

class PersonMetadata {
  PersonMetadata.fromBytes(ByteData data);
  ByteData toBytes() => ByteData(0);
}

as ObjectBox is using the default Person constructor to deserialize the object.

Describe the solution you'd like

I though of four possible ways this could possibly be achieved:

greenrobot-team commented 6 months ago

Thanks for this! It's correct that the generator currently only looks for an unnamed constructor. After a quick look, I don't see any reason on why it was restricted that way other than simplicity. So maybe the generator can support looking at all constructors. The docs also kind of imply this is how it should work (this is also how it works for Java).

FabrizioG202 commented 6 months ago

No problem! So, the best solution would be the third one, as it would not require the addition of a new annotation class and would not modify current classes?

If that is the case I could open a pull request to fix this

greenrobot-team commented 6 months ago

@FabrizioG202 Yes, that's probably the best way to go.

You can submit a pull request for this! But note that depending on the magnitude of the changes we may require you to sign a contributors license agreement (CLA).