-
Notifications
You must be signed in to change notification settings - Fork 135
Automatically generate IDs and UIDs for entities and properties #25
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
Changes from all commits
Commits
Show all changes
42 commits
Select commit
Hold shift + click to select a range
59486e5
Update gitignore to include generated files
nalenz-objectbox 33f93fa
Adjust library for new generator output format
nalenz-objectbox 3772fa3
Adjust model generator to load separate JSON file
nalenz-objectbox 8593d0e
Use global objectbox_models.json
nalenz-objectbox 233650b
Remove explicit ID and UID annotations from model definitions
nalenz-objectbox 14185d0
Rename objectbox_models.json to objectbox-models.json
nalenz-objectbox 4dfb7e0
Add full support for new JSON structure for models
nalenz-objectbox 3090ec0
Refactor generator modelinfo
nalenz-objectbox b95f1d6
Implement remaining generator modelinfo functions
nalenz-objectbox 2f19f8e
Fix 63 bit random number generation
nalenz-objectbox dddaa2e
Move long generated code chunks to separate file
nalenz-objectbox 980be8a
Make generator be based fully on modelinfo classes
nalenz-objectbox bc02ced
Add possibility to manually specify UIDs for entities and properties
nalenz-objectbox b78909b
Add merge functionality for new entities
nalenz-objectbox a9af161
Fix handling of duplicate entity or property names
nalenz-objectbox 021ba63
Implement entity merging involving added or removed properties
nalenz-objectbox 315e468
Correctly merge properties in generator
nalenz-objectbox 77f10dd
Remove Note class from test.dart
nalenz-objectbox 3fde1b2
Edit generated model version to be 1
nalenz-objectbox 00ac886
Adjust generator to treat unannotated fields as normal properties
nalenz-objectbox 92c824c
Add test field TestEntity.number
nalenz-objectbox 4cdfec0
Remove .g.dart files
nalenz-objectbox f7cf7c4
Add generated .g.dart files to gitignore
nalenz-objectbox 05cdfac
Upgrade Flutter demo and adjust it to work with automatic ID generation
nalenz-objectbox 7a2dead
Rename objectbox-models.json to objectbox-model.json
nalenz-objectbox f96d051
Edit generated model version to be 5
nalenz-objectbox d7195f2
Add all fields to generator ModelInfo
nalenz-objectbox 6dbd200
Omit entity property flags when none are present
nalenz-objectbox 11e26e8
Remove option to have custom property types
nalenz-objectbox 3d2f294
Move class annotation definitions to separate file
nalenz-objectbox 931c0d0
Move generator modelinfo to objectbox package
nalenz-objectbox 169c3dc
Refactor to use as few maps as possible
nalenz-objectbox 8d043d7
Move id property name search to ModelEntity
nalenz-objectbox 6fa4333
move model validation from box to store
vaind d0cce26
make OBXDefs typeful and simplify usage
vaind ff5a3bf
Rename test.dart to box_test.dart
nalenz-objectbox 77dedd0
Add tests for objectbox_model_generator
nalenz-objectbox 7f58f65
Divide main tests into separate files
nalenz-objectbox ebf1e6c
Update Flutter demo to use new models
nalenz-objectbox e07ee2e
Remove database directory from Flutter demo
nalenz-objectbox 7f14318
Merge branch 'dev' into 18-automatic-id-generation
vaind 956f5a8
execute generator tests in CI
vaind File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -4,10 +4,10 @@ | |
**/pubspec.lock | ||
misc/ | ||
.idea/ | ||
**/*.g.dart | ||
download/ | ||
lib/*.dll | ||
lib/*.dylib | ||
lib/*.so | ||
lib/*.a | ||
.vscode/ | ||
**/*.g.dart | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,46 @@ | ||
import "package:objectbox/src/modelinfo/index.dart"; | ||
|
||
class CodeChunks { | ||
static String modelInfoLoader(String allModelsJsonFilename) => """ | ||
Map<int, ModelEntity> _allOBXModelEntities = null; | ||
|
||
void _loadOBXModelEntities() { | ||
if (FileSystemEntity.typeSync("objectbox-model.json") == FileSystemEntityType.notFound) | ||
throw Exception("objectbox-model.json not found"); | ||
|
||
_allOBXModelEntities = {}; | ||
ModelInfo modelInfo = ModelInfo.fromMap(json.decode(new File("objectbox-model.json").readAsStringSync())); | ||
modelInfo.entities.forEach((e) => _allOBXModelEntities[e.id.uid] = e); | ||
} | ||
|
||
ModelEntity _getOBXModelEntity(int entityUid) { | ||
if (_allOBXModelEntities == null) _loadOBXModelEntities(); | ||
if (!_allOBXModelEntities.containsKey(entityUid)) | ||
throw Exception("entity uid missing in objectbox-model.json: \$entityUid"); | ||
return _allOBXModelEntities[entityUid]; | ||
} | ||
"""; | ||
|
||
static String instanceBuildersReaders(ModelEntity readEntity) { | ||
String name = readEntity.name; | ||
return """ | ||
ModelEntity _${name}_OBXModelGetter() { | ||
return _getOBXModelEntity(${readEntity.id.uid}); | ||
} | ||
|
||
$name _${name}_OBXBuilder(Map<String, dynamic> members) { | ||
$name r = new $name(); | ||
${readEntity.properties.map((p) => "r.${p.name} = members[\"${p.name}\"];").join()} | ||
return r; | ||
} | ||
|
||
Map<String, dynamic> _${name}_OBXReader($name inst) { | ||
Map<String, dynamic> r = {}; | ||
${readEntity.properties.map((p) => "r[\"${p.name}\"] = inst.${p.name};").join()} | ||
return r; | ||
} | ||
|
||
const ${name}_OBXDefs = EntityDefinition<${name}>(_${name}_OBXModelGetter, _${name}_OBXReader, _${name}_OBXBuilder); | ||
"""; | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,125 +1,128 @@ | ||
import "dart:async"; | ||
import "dart:convert"; | ||
import "dart:io"; | ||
import "package:analyzer/dart/element/element.dart"; | ||
import "package:build/src/builder/build_step.dart"; | ||
import "package:source_gen/source_gen.dart"; | ||
|
||
import "package:objectbox/objectbox.dart"; | ||
import "package:objectbox/objectbox.dart" as obx; | ||
import "package:objectbox/src/bindings/constants.dart"; | ||
|
||
class EntityGenerator extends GeneratorForAnnotation<Entity> { | ||
import "code_chunks.dart"; | ||
import "merge.dart"; | ||
import "package:objectbox/src/modelinfo/index.dart"; | ||
|
||
class EntityGenerator extends GeneratorForAnnotation<obx.Entity> { | ||
static const ALL_MODELS_JSON = "objectbox-model.json"; | ||
|
||
// each .g.dart file needs to get a header with functions to load the ALL_MODELS_JSON file exactly once. Store the input .dart file ids this has already been done for here | ||
List<String> entityHeaderDone = []; | ||
|
||
Future<ModelInfo> _loadModelInfo() async { | ||
if ((await FileSystemEntity.type(ALL_MODELS_JSON)) == FileSystemEntityType.notFound) | ||
return ModelInfo.createDefault(); | ||
return ModelInfo.fromMap(json.decode(await (new File(ALL_MODELS_JSON).readAsString()))); | ||
} | ||
|
||
@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(); | ||
|
||
var prop = { | ||
"name": f.name, | ||
"id": annotVal.getField("id").toIntValue(), | ||
"uid": annotVal.getField("uid").toIntValue(), | ||
"flags": 0, | ||
}; | ||
|
||
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'"); | ||
|
||
fieldType = OBXPropertyType.Long; | ||
prop["flags"] = OBXPropertyFlag.ID; | ||
idPropertyName = f.name; | ||
} else if (annotType == "Property") { | ||
// nothing special here | ||
} else { | ||
// skip unknown annotations | ||
continue; | ||
} | ||
Future<String> generateForAnnotatedElement( | ||
Element elementBare, ConstantReader annotation, BuildStep buildStep) async { | ||
try { | ||
if (elementBare is! ClassElement) | ||
throw InvalidGenerationSourceError("in target ${elementBare.name}: annotated element isn't a class"); | ||
var element = elementBare as ClassElement; | ||
|
||
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; | ||
} | ||
// load existing model from JSON file if possible | ||
String inputFileId = buildStep.inputId.toString(); | ||
ModelInfo allModels = await _loadModelInfo(); | ||
|
||
// optionally add header for loading the .g.json file | ||
var ret = ""; | ||
if (entityHeaderDone.indexOf(inputFileId) == -1) { | ||
ret += CodeChunks.modelInfoLoader(ALL_MODELS_JSON); | ||
entityHeaderDone.add(inputFileId); | ||
} | ||
|
||
prop["type"] = fieldType; | ||
props.add(prop); | ||
ret += """ | ||
{ | ||
"name": "${prop['name']}", | ||
"id": ${prop['id']}, | ||
"uid": ${prop['uid']}, | ||
"type": ${prop['type']}, | ||
"flags": ${prop['flags']}, | ||
}, | ||
"""; | ||
} | ||
// process basic entity (note that allModels.createEntity is not used, as the entity will be merged) | ||
ModelEntity readEntity = new ModelEntity(IdUid.empty(), null, element.name, [], allModels); | ||
var entityUid = annotation.read("uid"); | ||
if (entityUid != null && !entityUid.isNull) readEntity.id.uid = entityUid.intValue; | ||
|
||
// read all suitable annotated properties | ||
bool hasIdProperty = false; | ||
for (var f in element.fields) { | ||
int fieldType, flags = 0; | ||
int propUid; | ||
|
||
// some checks on the entity's integrity | ||
if (idPropertyName == null) | ||
throw InvalidGenerationSourceError("in target ${elementBare.name}: has no properties annotated with @Id"); | ||
if (f.metadata != null && f.metadata.length == 1) { | ||
var annotElmt = f.metadata[0].element as ConstructorElement; | ||
var annotType = annotElmt.returnType.toString(); | ||
var annotVal = f.metadata[0].computeConstantValue(); | ||
var fieldTypeAnnot = null; // for the future, with custom type sizes allowed: annotVal.getField("type"); | ||
fieldType = fieldTypeAnnot == null ? null : fieldTypeAnnot.toIntValue(); | ||
propUid = annotVal.getField("uid").toIntValue(); | ||
|
||
// main code for instance builders and readers | ||
ret += """ | ||
], | ||
"idPropertyName": "${idPropertyName}", | ||
}; | ||
// find property flags | ||
if (annotType == "Id") { | ||
if (hasIdProperty) | ||
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'"); | ||
|
||
${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; | ||
fieldType = OBXPropertyType.Long; | ||
flags |= OBXPropertyFlag.ID; | ||
hasIdProperty = true; | ||
} else if (annotType == "Property") { | ||
// nothing special | ||
} else { | ||
// skip unknown annotations | ||
print( | ||
"warning: skipping field '${f.name}' in entity '${element.name}', as it has the unknown annotation type '$annotType'"); | ||
continue; | ||
} | ||
} | ||
|
||
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; | ||
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; | ||
} | ||
} | ||
|
||
const ${element.name}_OBXDefs = { | ||
"model": _${element.name}_OBXModel, | ||
"builder": _${element.name}_OBXBuilder, | ||
"reader": _${element.name}_OBXReader, | ||
}; | ||
"""; | ||
// create property (do not use readEntity.createProperty in order to avoid generating new ids) | ||
ModelProperty prop = new ModelProperty(IdUid.empty(), f.name, fieldType, flags, readEntity); | ||
if (propUid != null) prop.id.uid = propUid; | ||
readEntity.properties.add(prop); | ||
} | ||
|
||
// some checks on the entity's integrity | ||
if (!hasIdProperty) | ||
throw InvalidGenerationSourceError("in target ${elementBare.name}: has no properties annotated with @Id"); | ||
|
||
return ret; | ||
// merge existing model and annotated model that was just read, then write new final model to file | ||
mergeEntity(allModels, readEntity); | ||
new File(ALL_MODELS_JSON).writeAsString(new JsonEncoder.withIndent(" ").convert(allModels.toMap())); | ||
readEntity = allModels.findEntityByName(element.name); | ||
if (readEntity == null) return ret; | ||
|
||
// main code for instance builders and readers | ||
ret += CodeChunks.instanceBuildersReaders(readEntity); | ||
|
||
return ret; | ||
} catch (e, s) { | ||
print(s); | ||
rethrow; | ||
} | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,30 @@ | ||
import "package:objectbox/src/modelinfo/index.dart"; | ||
|
||
void _mergeProperty(ModelEntity entity, ModelProperty prop) { | ||
ModelProperty propInModel = entity.findSameProperty(prop); | ||
if (propInModel == null) { | ||
entity.createCopiedProperty(prop); | ||
} else { | ||
propInModel.type = prop.type; | ||
propInModel.flags = prop.flags; | ||
} | ||
} | ||
|
||
void mergeEntity(ModelInfo modelInfo, ModelEntity readEntity) { | ||
// "readEntity" only contains the entity info directly read from the annotations and Dart source (i.e. with missing ID, lastPropertyId etc.) | ||
// "entityInModel" is the entity from the model with all correct id/uid, lastPropertyId etc. | ||
ModelEntity entityInModel = modelInfo.findSameEntity(readEntity); | ||
|
||
if (entityInModel == null) { | ||
// in case the entity is created (i.e. when its given UID or name that does not yet exist), we are done, as nothing needs to be merged | ||
modelInfo.createCopiedEntity(readEntity); | ||
} else { | ||
// here, the entity was found already and entityInModel and readEntity might differ, i.e. conflicts need to be resolved, so merge all properties first | ||
readEntity.properties.forEach((p) => _mergeProperty(entityInModel, p)); | ||
|
||
// them remove all properties not present anymore in readEntity | ||
entityInModel.properties | ||
.where((p) => readEntity.findSameProperty(p) == null) | ||
.forEach((p) => entityInModel.removeProperty(p)); | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.