Skip to content

Refactoring #23

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

Merged
merged 7 commits into from
Sep 16, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -10,3 +10,4 @@ lib/*.dll
lib/*.dylib
lib/*.so
lib/*.a
.vscode/
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,10 @@ To try out the demo code in this repository, follow these steps:
3. Execute `pub run build_runner build`. This regenerates the ObjectBox model to make it usable in Dart (i.e. the file `test/test.g.dart`) and is necessary each time you add or change a class annotated with `@Entity(...)`.
4. Finally run `pub run test test/test.dart` to run the unit tests.

Contribution guide
------------------
Please make sure that all code submitted via Pull Request needs to be formatted using `dartfmt -l 120`. You can configure your IDE to do this automatically, e.g. VS Code needs the project-specific settings `"editor.defaultFormatter": "Dart-Code.dart-code"` and `"dart.lineLength": 120`.

Dart integration
----------------
In general, Dart class annotations are used to mark classes as ObjectBox entities and provide meta information.
Expand Down
3 changes: 1 addition & 2 deletions bin/objectbox_model_generator/lib/builder.dart
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,4 @@ import "package:build/build.dart";
import "package:source_gen/source_gen.dart";
import "package:objectbox_model_generator/src/generator.dart";

Builder objectboxModelFactory(BuilderOptions options) =>
SharedPartBuilder([EntityGenerator()], "objectbox_model");
Builder objectboxModelFactory(BuilderOptions options) => SharedPartBuilder([EntityGenerator()], "objectbox_model");
201 changes: 102 additions & 99 deletions bin/objectbox_model_generator/lib/src/generator.dart
Original file line number Diff line number Diff line change
Expand Up @@ -7,116 +7,119 @@ import "package:objectbox/objectbox.dart";
import "package:objectbox/src/bindings/constants.dart";

class EntityGenerator extends GeneratorForAnnotation<Entity> {
@override
FutureOr<String> generateForAnnotatedElement(Element elementBare, ConstantReader annotation, BuildStep buildStep) {
if(elementBare is! ClassElement)
throw InvalidGenerationSourceError("in target ${elementBare.name}: annotated element isn't a class");
@override
FutureOr<String> generateForAnnotatedElement(Element elementBare, ConstantReader annotation, BuildStep buildStep) {
if (elementBare is! ClassElement)
throw InvalidGenerationSourceError("in target ${elementBare.name}: annotated element isn't a class");

// get basic entity info
var entity = Entity(id: annotation.read('id').intValue, uid: annotation.read('uid').intValue);
var element = elementBare as ClassElement;
var ret = """
const _${element.name}_OBXModel = {
"entity": {
"name": "${element.name}",
"id": ${entity.id},
"uid": ${entity.uid}
},
"properties": [
""";

// read all suitable annotated properties
var props = [];
String idPropertyName;
for(var f in element.fields) {
if(f.metadata == null || f.metadata.length != 1) // skip unannotated fields
continue;
var annotElmt = f.metadata[0].element as ConstructorElement;
var annotType = annotElmt.returnType.toString();
var annotVal = f.metadata[0].computeConstantValue();
var fieldTypeObj = annotVal.getField("type");
int fieldType = fieldTypeObj == null ? null : fieldTypeObj.toIntValue();
// get basic entity info
var entity = Entity(id: annotation.read('id').intValue, uid: annotation.read('uid').intValue);
var element = elementBare as ClassElement;
var ret = """
const _${element.name}_OBXModel = {
"entity": {
"name": "${element.name}",
"id": ${entity.id},
"uid": ${entity.uid}
},
"properties": [
""";

var prop = {
"name": f.name,
"id": annotVal.getField("id").toIntValue(),
"uid": annotVal.getField("uid").toIntValue(),
"flags": 0,
};
// read all suitable annotated properties
var props = [];
String idPropertyName;
for (var f in element.fields) {
if (f.metadata == null || f.metadata.length != 1) // skip unannotated fields
continue;
var annotElmt = f.metadata[0].element as ConstructorElement;
var annotType = annotElmt.returnType.toString();
var annotVal = f.metadata[0].computeConstantValue();
var fieldTypeObj = annotVal.getField("type");
int fieldType = fieldTypeObj == null ? null : fieldTypeObj.toIntValue();

if(annotType == "Id") {
if(idPropertyName != null)
throw InvalidGenerationSourceError("in target ${elementBare.name}: has more than one properties annotated with @Id");
if(fieldType != null)
throw InvalidGenerationSourceError("in target ${elementBare.name}: programming error: @Id property may not specify a type");
if(f.type.toString() != "int")
throw InvalidGenerationSourceError("in target ${elementBare.name}: field with @Id property has type '${f.type.toString()}', but it must be 'int'");
var prop = {
"name": f.name,
"id": annotVal.getField("id").toIntValue(),
"uid": annotVal.getField("uid").toIntValue(),
"flags": 0,
};

fieldType = OBXPropertyType.Long;
prop["flags"] = OBXPropertyFlag.ID;
idPropertyName = f.name;
} else if(annotType == "Property") {
// nothing special here
} else {
// skip unknown annotations
continue;
}
if (annotType == "Id") {
if (idPropertyName != null)
throw InvalidGenerationSourceError(
"in target ${elementBare.name}: has more than one properties annotated with @Id");
if (fieldType != null)
throw InvalidGenerationSourceError(
"in target ${elementBare.name}: programming error: @Id property may not specify a type");
if (f.type.toString() != "int")
throw InvalidGenerationSourceError(
"in target ${elementBare.name}: field with @Id property has type '${f.type.toString()}', but it must be 'int'");

if(fieldType == null) {
var fieldTypeStr = f.type.toString();
if(fieldTypeStr == "int")
fieldType = OBXPropertyType.Int;
else if(fieldTypeStr == "String")
fieldType = OBXPropertyType.String;
else {
print("warning: skipping field '${f.name}' in entity '${element.name}', as it has the unsupported type '$fieldTypeStr'");
continue;
}
}
fieldType = OBXPropertyType.Long;
prop["flags"] = OBXPropertyFlag.ID;
idPropertyName = f.name;
} else if (annotType == "Property") {
// nothing special here
} else {
// skip unknown annotations
continue;
}

prop["type"] = fieldType;
props.add(prop);
ret += """
{
"name": "${prop['name']}",
"id": ${prop['id']},
"uid": ${prop['uid']},
"type": ${prop['type']},
"flags": ${prop['flags']},
"flatbuffers_id": ${(prop['id'] as int) - 1},
},
""";
if (fieldType == null) {
var fieldTypeStr = f.type.toString();
if (fieldTypeStr == "int")
fieldType = OBXPropertyType.Int;
else if (fieldTypeStr == "String")
fieldType = OBXPropertyType.String;
else {
print(
"warning: skipping field '${f.name}' in entity '${element.name}', as it has the unsupported type '$fieldTypeStr'");
continue;
}
}

// some checks on the entity's integrity
if(idPropertyName == null)
throw InvalidGenerationSourceError("in target ${elementBare.name}: has no properties annotated with @Id");
prop["type"] = fieldType;
props.add(prop);
ret += """
{
"name": "${prop['name']}",
"id": ${prop['id']},
"uid": ${prop['uid']},
"type": ${prop['type']},
"flags": ${prop['flags']},
},
""";
}

// main code for instance builders and readers
ret += """
],
"idPropertyName": "${idPropertyName}",
};
// some checks on the entity's integrity
if (idPropertyName == null)
throw InvalidGenerationSourceError("in target ${elementBare.name}: has no properties annotated with @Id");

${element.name} _${element.name}_OBXBuilder(Map<String, dynamic> members) {
${element.name} r = new ${element.name}();
${props.map((p) => "r.${p['name']} = members[\"${p['name']}\"];").join()}
return r;
}
// main code for instance builders and readers
ret += """
],
"idPropertyName": "${idPropertyName}",
};

Map<String, dynamic> _${element.name}_OBXReader(${element.name} inst) {
Map<String, dynamic> r = {};
${props.map((p) => "r[\"${p['name']}\"] = inst.${p['name']};").join()}
return r;
}
${element.name} _${element.name}_OBXBuilder(Map<String, dynamic> members) {
${element.name} r = new ${element.name}();
${props.map((p) => "r.${p['name']} = members[\"${p['name']}\"];").join()}
return r;
}

const ${element.name}_OBXDefs = {
"model": _${element.name}_OBXModel,
"builder": _${element.name}_OBXBuilder,
"reader": _${element.name}_OBXReader,
};
""";
Map<String, dynamic> _${element.name}_OBXReader(${element.name} inst) {
Map<String, dynamic> r = {};
${props.map((p) => "r[\"${p['name']}\"] = inst.${p['name']};").join()}
return r;
}

return ret;
}
const ${element.name}_OBXDefs = {
"model": _${element.name}_OBXModel,
"builder": _${element.name}_OBXBuilder,
"reader": _${element.name}_OBXReader,
};
""";

return ret;
}
}
Loading