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

feat: v0.0.2 release #76

Merged
merged 7 commits into from
Jun 27, 2024
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
2 changes: 0 additions & 2 deletions _tests_/lib/test_data.dart
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
import 'package:yaroorm_tests/src/models.dart';

typedef UserData = ({String firstname, String lastname, int age, String homeAddress});

final usersList = <NewUser>[
/// Ghana Users - [6]
NewUser(
Expand Down
10 changes: 4 additions & 6 deletions _tests_/test/integration/e2e_basic.dart
Original file line number Diff line number Diff line change
Expand Up @@ -164,14 +164,12 @@ void runBasicE2ETest(String connectionName) {
});

test('should get all users where age is 30 or 52', () async {
final users = await UserQuery.driver(driver)
.where((user) => or([
user.age(30),
user.age(52),
]))
.findMany();
final users = await UserQuery.driver(driver).where((user) => or([user.age(30), user.age(52)])).findMany();

final users2 = await UserQuery.driver(driver).where((user) => user.age(30) | user.age(52)).findMany();

expect(users.every((e) => [30, 52].contains(e.age)), isTrue);
expect(users2.every((e) => [30, 52].contains(e.age)), isTrue);
});

test('should delete user', () async {
Expand Down
66 changes: 22 additions & 44 deletions lib/src/builder/generator.dart
Original file line number Diff line number Diff line change
Expand Up @@ -75,8 +75,13 @@ class EntityGenerator extends GeneratorForAnnotation<entity.Table> {
"${parsedEntity.table}",
timestampsEnabled: ${parsedEntity.timestampsEnabled},
columns: ${fields.map((field) => generateCodeForField(parsedEntity, field)).toList()},
mirror: _\$${className}EntityMirror.new,
build: (args) => ${_generateConstructorCode(className, primaryConstructor)},
mirror: (instance, field) => switch(field) {
${fields.map((e) => '''
#${e.name} => instance.${e.name}
''').join(',')},
_ => throw Exception('Unknown property \$field'),
},
builder: (args) => ${_generateConstructorCode(className, primaryConstructor)},
${bindings.isEmpty ? '' : 'bindings: { ${bindings.entries.map(
(e) => _generateCodeForBinding(
className,
Expand All @@ -89,39 +94,6 @@ class EntityGenerator extends GeneratorForAnnotation<entity.Table> {
${converters.isEmpty ? '' : 'converters: ${converters.map(processAnnotation).toList()},'})''',
)),

/// Generate Entity Mirror for Reflection
Class(
(b) => b
..name = '_\$${className}EntityMirror'
..extend = refer('EntityMirror<$className>')
..constructors.add(Constructor(
(b) => b
..constant = true
..requiredParameters.add(Parameter((p) => p
..toSuper = true
..name = 'instance')),
))
..methods.addAll([
Method(
(m) => m
..name = 'get'
..annotations.add(CodeExpression(Code('override')))
..requiredParameters.add(Parameter((p) => p
..name = 'field'
..type = refer('Symbol')))
..returns = refer('Object?')
..body = Code('''
return switch(field) {
${fields.map((e) => '''
#${e.name} => instance.${e.name}
''').join(',')},
_ => throw Exception('Unknown property \$field'),
};
'''),
),
]),
),

/// Generate Typed OrderBy's
Class((b) => b
..name = 'Order${className}By'
Expand Down Expand Up @@ -194,7 +166,7 @@ return switch(field) {
..fields.addAll(relatedEntityCreateFields.map(
(f) => Field((fb) => fb
..name = f.name
..type = refer(f.type.getDisplayString(withNullability: true))
..type = refer(f.type.withNullability)
..modifier = FieldModifier.final$),
))
..constructors.add(
Expand Down Expand Up @@ -247,7 +219,7 @@ return switch(field) {
..fields.addAll(fieldsRequiredForCreate.map(
(f) => Field((fb) => fb
..name = f.name
..type = refer(f.type.getDisplayString(withNullability: true))
..type = refer(f.type.withNullability)
..modifier = FieldModifier.final$),
))
..constructors.add(
Expand Down Expand Up @@ -281,7 +253,7 @@ return switch(field) {
..fields.addAll(fieldsRequiredForCreate.map((f) => Field(
(fb) => fb
..name = f.name
..type = refer('value<${f.type.getDisplayString(withNullability: true)}>')
..type = refer('value<${f.type.withNullability}>')
..modifier = FieldModifier.final$,
)))
..constructors.add(
Expand Down Expand Up @@ -333,7 +305,7 @@ return switch(field) {
/// This generates WHERE-EQUAL clause value for a field
Method _generateFieldWhereClause(FieldElement field, String className) {
final dbColumnName = getFieldDbName(field);
final fieldType = field.type.getDisplayString(withNullability: true);
final fieldType = field.type.withNullability;

return Method(
(m) {
Expand Down Expand Up @@ -376,7 +348,7 @@ return switch(field) {
/// This generates GetByProperty for a field
Method _generateGetByPropertyMethod(FieldElement field, String className) {
final fieldName = field.name;
final fieldType = field.type.getDisplayString(withNullability: true);
final fieldType = field.type.withNullability;

return Method(
(m) {
Expand Down Expand Up @@ -426,8 +398,8 @@ return switch(field) {

final requiredOpts = '''
"$columnName",
${field.type.getDisplayString(withNullability: false)},
$symbol,
${field.type.withoutNullability},
$symbol
''';

if (field == createdAtField) {
Expand All @@ -440,8 +412,8 @@ return switch(field) {

if (field == primaryKey.field) {
return '''DBEntityField.primaryKey(
$requiredOpts
${parsedClass.hasAutoIncrementingPrimaryKey ? 'autoIncrement: true, ' : ''}
$requiredOpts,
${parsedClass.hasAutoIncrementingPrimaryKey ? 'autoIncrement: true' : ''}
)''';
}

Expand Down Expand Up @@ -580,3 +552,9 @@ return switch(field) {
].join(', ')} ,)''';
}
}

extension on DartType {
String get withNullability => getDisplayString(withNullability: true);

String get withoutNullability => getDisplayString(withNullability: false);
}
23 changes: 11 additions & 12 deletions lib/src/builder/utils.dart
Original file line number Diff line number Diff line change
Expand Up @@ -241,7 +241,8 @@ final class ParsedEntityClass {
factory ParsedEntityClass.parse(ClassElement element, {ConstantReader? reader}) {
final className = element.name;
final tableName = getTableName(element);
final fields = element.fields.where(_allowedTypes).toList();
final fields = element.fields.where(_allowedTypes).toList(growable: false);

final primaryKey = _getFieldAnnotationByType(fields, entity.PrimaryKey);
final createdAt = _getFieldAnnotationByType(fields, entity.CreatedAtColumn);
final updatedAt = _getFieldAnnotationByType(fields, entity.UpdatedAtColumn);
Expand Down Expand Up @@ -269,8 +270,9 @@ final class ParsedEntityClass {
);
}

final normalFields =
fields.where((e) => ![primaryKey.field, createdAt?.field, updatedAt?.field].contains(e)).toList();
final normalFields = fields
.where((e) => ![primaryKey.field, createdAt?.field, updatedAt?.field].contains(e))
.toList(growable: false);

final fieldsWithBindings = _getFieldsAndReaders(normalFields, entity.bindTo);

Expand Down Expand Up @@ -330,15 +332,12 @@ final class ParsedEntityClass {
return null;
}

static List<FieldElementAndReader> _getFieldsAndReaders(List<FieldElement> fields, Type type) {
return fields
.map((field) {
final result = typeChecker(type).firstAnnotationOf(field, throwOnUnresolved: false);
if (result == null) return null;
return (field: field, reader: ConstantReader(result));
})
.whereNotNull()
.toList();
static Iterable<FieldElementAndReader> _getFieldsAndReaders(List<FieldElement> fields, Type type) sync* {
for (final field in fields) {
final result = typeChecker(type).firstAnnotationOf(field, throwOnUnresolved: false);
if (result == null) continue;
yield (field: field, reader: ConstantReader(result));
}
}
}

Expand Down
23 changes: 7 additions & 16 deletions lib/src/cli/model/migration.g.dart

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

21 changes: 9 additions & 12 deletions lib/src/database/entity/converter.dart
Original file line number Diff line number Diff line change
Expand Up @@ -19,26 +19,23 @@ Map<Type, EntityTypeConverter> combineConverters(
};
}

UnmodifiableMapView<String, dynamic> entityToDbData<Model extends Entity<Model>>(Model value) {
final entity = Query.getEntity<Model>(type: value.runtimeType);
final typeConverters = combineConverters(entity.converters, value._driver.typeconverters);
final mirror = entity.mirror(value);
Map<String, dynamic> entityToDbData<Model extends Entity<Model>>(Model entity) {
final typeInfo = Query.getEntity<Model>(type: entity.runtimeType);
final typeConverters = combineConverters(typeInfo.converters, entity._driver.typeconverters);

Object? getValue(DBEntityField field) {
final value = mirror.get(field.dartName);
final value = typeInfo.mirror(entity, field.dartName);
final typeConverter = typeConverters[field.type];
return typeConverter == null ? value : typeConverter.toDbType(value);
}

final data = {
for (final entry in entity.editableColumns) entry.columnName: getValue(entry),
return {
for (final entry in typeInfo.editableColumns) entry.columnName: getValue(entry),
};

return UnmodifiableMapView(data);
}

@internal
UnmodifiableMapView<String, dynamic> entityMapToDbData<T extends Entity<T>>(
Map<String, dynamic> entityMapToDbData<T extends Entity<T>>(
Map<Symbol, dynamic> values,
Map<Type, EntityTypeConverter> typeConverters, {
bool onlyPropertiesPassed = false,
Expand All @@ -64,7 +61,7 @@ UnmodifiableMapView<String, dynamic> entityMapToDbData<T extends Entity<T>>(
resultsMap[field.columnName] = value;
}

return UnmodifiableMapView(resultsMap);
return resultsMap;
}

@internal
Expand All @@ -80,5 +77,5 @@ Model dbDataToEntity<Model extends Entity<Model>>(
resultsMap[entry.dartName] = typeConverter == null ? value : typeConverter.fromDbType(value);
}

return entity.build(resultsMap);
return entity.builder(resultsMap);
}
5 changes: 2 additions & 3 deletions lib/src/database/entity/entity.dart
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
// ignore_for_file: camel_case_types

import 'dart:async';
import 'dart:collection';

import 'package:meta/meta.dart';

Expand Down Expand Up @@ -78,7 +77,7 @@ abstract class Entity<Parent extends Entity<Parent>> {
final typeData = Query.getEntity<Parent>();

foreignKey ??= typeData.bindings.entries.firstWhere((e) => e.value.type == RelatedModel).key;
final referenceFieldValue = typeData.mirror(this as Parent).get(foreignKey);
final referenceFieldValue = typeData.mirror(this as Parent, foreignKey);

return HasOne<Parent, RelatedModel>._(
relatedPrimaryKey,
Expand All @@ -95,7 +94,7 @@ abstract class Entity<Parent extends Entity<Parent>> {
}) {
final parentFieldName = Query.getEntity<RelatedModel>().primaryKey.columnName;
foreignKey ??= _typeDef.bindings.entries.firstWhere((e) => e.value.type == RelatedModel).key;
final referenceFieldValue = _typeDef.mirror(this as Parent).get(foreignKey);
final referenceFieldValue = _typeDef.mirror(this as Parent, foreignKey);

return BelongsTo<Parent, RelatedModel>._(
parentFieldName,
Expand Down
2 changes: 1 addition & 1 deletion lib/src/database/entity/relations.dart
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ abstract class EntityRelation<Parent extends Entity<Parent>, RelatedModel extend

Object get parentId {
final typeInfo = parent._typeDef;
return typeInfo.mirror.call(parent).get(typeInfo.primaryKey.dartName)!;
return typeInfo.mirror.call(parent, typeInfo.primaryKey.dartName)!;
}

DriverContract get _driver => parent._driver;
Expand Down
13 changes: 7 additions & 6 deletions lib/src/migration.dart
Original file line number Diff line number Diff line change
Expand Up @@ -215,18 +215,19 @@ abstract class Schema {
table = make(table, prop);
}

for (final binding in entity.bindings.entries) {
final prop = entity.columns.firstWhere((e) => e.dartName == binding.key);
final referenceTypeData = binding.value.referenceTypeDef;
final referenceColumn = binding.value.reference;
for (final key in entity.bindings.keys) {
final binding = entity.bindings[key]!;
final prop = entity.columns.firstWhere((e) => e.dartName == key);
final referenceTypeData = binding.referenceTypeDef;
final referenceColumn = binding.reference;

final foreignKey = ForeignKey(
entity.tableName,
prop.columnName,
foreignTable: referenceTypeData.tableName,
foreignTableColumn: referenceColumn.columnName,
onUpdate: binding.value.onUpdate,
onDelete: binding.value.onDelete,
onUpdate: binding.onUpdate,
onDelete: binding.onDelete,
);

table.foreign(foreignKey);
Expand Down
4 changes: 4 additions & 0 deletions lib/src/primitives/where.dart
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,10 @@ class WhereClauseValue<ValueType> extends WhereClause {
}
}

WhereClause operator &(WhereClauseValue other) => and([this, other]);

WhereClause operator |(WhereClauseValue other) => or([this, other]);

@override
void _withConverters(Map<Type, EntityTypeConverter> converters) {
_converters
Expand Down
4 changes: 1 addition & 3 deletions lib/src/query/query.dart
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
import 'dart:collection';

import 'package:meta/meta.dart';

import '../database/driver/driver.dart';
Expand Down Expand Up @@ -155,7 +153,7 @@ final class Query<T extends Entity<T>>
return ReadQuery<T>._(this, whereClause: whereClause);
}

UnmodifiableMapView<String, dynamic> _prepareCreate(CreateEntity<T> data) {
Map<String, dynamic> _prepareCreate(CreateEntity<T> data) {
final dataMap = data.toMap;
if (entity.timestampsEnabled) {
final now = DateTime.now();
Expand Down
Loading
Loading