add 'select(List<String> fields)' function to orm_generator.

This commit is contained in:
debuggerx01 2022-01-04 19:52:12 +08:00
parent 262043861d
commit 2c76702e44
2 changed files with 96 additions and 50 deletions

View file

@ -11,13 +11,13 @@ class EmployeeMigration extends Migration {
void up(Schema schema) { void up(Schema schema) {
schema.create('employees', (table) { schema.create('employees', (table) {
table.serial('id').primaryKey(); table.serial('id').primaryKey();
table.varChar('error', length: 256);
table.timeStamp('created_at'); table.timeStamp('created_at');
table.timeStamp('updated_at'); table.timeStamp('updated_at');
table.varChar('unique_id', length: 256).unique(); table.varChar('unique_id', length: 255).unique();
table.varChar('first_name', length: 256); table.varChar('first_name', length: 255);
table.varChar('last_name', length: 256); table.varChar('last_name', length: 255);
table.declareColumn('salary', Column(type: ColumnType('decimal'))); table.declareColumn(
'salary', Column(type: ColumnType('decimal'), length: 255));
}); });
} }
@ -42,6 +42,8 @@ class EmployeeQuery extends Query<Employee, EmployeeQueryWhere> {
@override @override
final EmployeeQueryValues values = EmployeeQueryValues(); final EmployeeQueryValues values = EmployeeQueryValues();
List<String> _selectedFields = [];
EmployeeQueryWhere? _where; EmployeeQueryWhere? _where;
@override @override
@ -56,9 +58,8 @@ class EmployeeQuery extends Query<Employee, EmployeeQueryWhere> {
@override @override
List<String> get fields { List<String> get fields {
return const [ const _fields = [
'id', 'id',
'error',
'created_at', 'created_at',
'updated_at', 'updated_at',
'unique_id', 'unique_id',
@ -66,6 +67,14 @@ class EmployeeQuery extends Query<Employee, EmployeeQueryWhere> {
'last_name', 'last_name',
'salary' 'salary'
]; ];
return _selectedFields.isEmpty
? _fields
: _fields.where((field) => _selectedFields.contains(field)).toList();
}
EmployeeQuery select(List<String> selectedFields) {
_selectedFields = selectedFields;
return this;
} }
@override @override
@ -78,29 +87,38 @@ class EmployeeQuery extends Query<Employee, EmployeeQueryWhere> {
return EmployeeQueryWhere(this); return EmployeeQueryWhere(this);
} }
static Employee? parseRow(List row) { Optional<Employee> parseRow(List row) {
if (row.every((x) => x == null)) return null; if (row.every((x) => x == null)) {
return Optional.empty();
}
var _index = 0;
var model = Employee( var model = Employee(
id: row[0].toString(), id: fields.contains('id') ? row[_index++].toString() : null,
createdAt: (row[2] as DateTime?), createdAt:
updatedAt: (row[3] as DateTime?), fields.contains('created_at') ? (row[_index++] as DateTime?) : null,
uniqueId: (row[4] as String?), updatedAt:
firstName: (row[5] as String?), fields.contains('updated_at') ? (row[_index++] as DateTime?) : null,
lastName: (row[6] as String?), uniqueId:
salary: double.tryParse(row[7].toString())); fields.contains('unique_id') ? (row[_index++] as String?) : null,
return model; firstName:
fields.contains('first_name') ? (row[_index++] as String?) : null,
lastName:
fields.contains('last_name') ? (row[_index++] as String?) : null,
salary: fields.contains('salary')
? double.tryParse(row[_index++].toString())
: null);
return Optional.of(model);
} }
@override @override
Optional<Employee> deserialize(List row) { Optional<Employee> deserialize(List row) {
return Optional.ofNullable(parseRow(row)); return parseRow(row);
} }
} }
class EmployeeQueryWhere extends QueryWhere { class EmployeeQueryWhere extends QueryWhere {
EmployeeQueryWhere(EmployeeQuery query) EmployeeQueryWhere(EmployeeQuery query)
: id = NumericSqlExpressionBuilder<int>(query, 'id'), : id = NumericSqlExpressionBuilder<int>(query, 'id'),
error = StringSqlExpressionBuilder(query, 'error'),
createdAt = DateTimeSqlExpressionBuilder(query, 'created_at'), createdAt = DateTimeSqlExpressionBuilder(query, 'created_at'),
updatedAt = DateTimeSqlExpressionBuilder(query, 'updated_at'), updatedAt = DateTimeSqlExpressionBuilder(query, 'updated_at'),
uniqueId = StringSqlExpressionBuilder(query, 'unique_id'), uniqueId = StringSqlExpressionBuilder(query, 'unique_id'),
@ -110,8 +128,6 @@ class EmployeeQueryWhere extends QueryWhere {
final NumericSqlExpressionBuilder<int> id; final NumericSqlExpressionBuilder<int> id;
final StringSqlExpressionBuilder error;
final DateTimeSqlExpressionBuilder createdAt; final DateTimeSqlExpressionBuilder createdAt;
final DateTimeSqlExpressionBuilder updatedAt; final DateTimeSqlExpressionBuilder updatedAt;
@ -126,16 +142,7 @@ class EmployeeQueryWhere extends QueryWhere {
@override @override
List<SqlExpressionBuilder> get expressionBuilders { List<SqlExpressionBuilder> get expressionBuilders {
return [ return [id, createdAt, updatedAt, uniqueId, firstName, lastName, salary];
id,
error,
createdAt,
updatedAt,
uniqueId,
firstName,
lastName,
salary
];
} }
} }
@ -150,11 +157,6 @@ class EmployeeQueryValues extends MapQueryValues {
} }
set id(String? value) => values['id'] = value; set id(String? value) => values['id'] = value;
String? get error {
return (values['error'] as String?);
}
set error(String? value) => values['error'] = value;
DateTime? get createdAt { DateTime? get createdAt {
return (values['created_at'] as DateTime?); return (values['created_at'] as DateTime?);
} }
@ -236,7 +238,6 @@ class Employee extends _Employee {
Employee copyWith( Employee copyWith(
{String? id, {String? id,
String? error,
DateTime? createdAt, DateTime? createdAt,
DateTime? updatedAt, DateTime? updatedAt,
String? uniqueId, String? uniqueId,
@ -310,7 +311,7 @@ class EmployeeSerializer extends Codec<Employee, Map> {
EmployeeDecoder get decoder => const EmployeeDecoder(); EmployeeDecoder get decoder => const EmployeeDecoder();
static Employee fromMap(Map map) { static Employee fromMap(Map map) {
return Employee( return Employee(
id: map['id'] as String, id: map['id'] as String?,
createdAt: map['created_at'] != null createdAt: map['created_at'] != null
? (map['created_at'] is DateTime ? (map['created_at'] is DateTime
? (map['created_at'] as DateTime) ? (map['created_at'] as DateTime)
@ -321,13 +322,16 @@ class EmployeeSerializer extends Codec<Employee, Map> {
? (map['updated_at'] as DateTime) ? (map['updated_at'] as DateTime)
: DateTime.parse(map['updated_at'].toString())) : DateTime.parse(map['updated_at'].toString()))
: null, : null,
uniqueId: map['unique_id'] as String, uniqueId: map['unique_id'] as String?,
firstName: map['first_name'] as String, firstName: map['first_name'] as String?,
lastName: map['last_name'] as String, lastName: map['last_name'] as String?,
salary: map['salary'] as double); salary: map['salary'] as double?);
} }
static Map<String, dynamic> toMap(_Employee model) { static Map<String, dynamic> toMap(_Employee? model) {
if (model == null) {
return {};
}
return { return {
'id': model.id, 'id': model.id,
'created_at': model.createdAt?.toIso8601String(), 'created_at': model.createdAt?.toIso8601String(),
@ -343,7 +347,6 @@ class EmployeeSerializer extends Codec<Employee, Map> {
abstract class EmployeeFields { abstract class EmployeeFields {
static const List<String> allFields = <String>[ static const List<String> allFields = <String>[
id, id,
error,
createdAt, createdAt,
updatedAt, updatedAt,
uniqueId, uniqueId,
@ -354,8 +357,6 @@ abstract class EmployeeFields {
static const String id = 'id'; static const String id = 'id';
static const String error = 'error';
static const String createdAt = 'created_at'; static const String createdAt = 'created_at';
static const String updatedAt = 'updated_at'; static const String updatedAt = 'updated_at';

View file

@ -156,7 +156,49 @@ class OrmGenerator extends GeneratorForAnnotation<Orm> {
.map((f) => .map((f) =>
literalString(ctx.buildContext.resolveFieldName(f.name)!)) literalString(ctx.buildContext.resolveFieldName(f.name)!))
.toList(); .toList();
b.addExpression(literalConstList(names).returned); b.addExpression(literalConstList(names).assignConst('_fields'));
b.addExpression(refer('_selectedFields')
.property('isEmpty')
.conditional(
refer('_fields'),
refer('_fields')
.property('where')
.call([
CodeExpression(
Code('(field) => _selectedFields.contains(field)'))
])
.property('toList')
.call([]),
)
.returned);
});
}));
// Add _selectedFields member
clazz.fields.add(Field((b) {
b
..name = '_selectedFields'
..type = TypeReference((t) => t
..symbol = 'List'
..types.add(TypeReference((b) => b..symbol = 'String')))
..assignment = Code('[]');
}));
// Add select(List<String> fields)
clazz.methods.add(Method((m) {
m
..name = 'select'
..returns = refer('${rc.pascalCase}Query')
..requiredParameters.add(Parameter((b) => b
..name = 'selectedFields'
..type = TypeReference((t) => t
..symbol = 'List'
..types.add(TypeReference((b) => b..symbol = 'String')))))
..body = Block((b) {
b.addExpression(
refer('_selectedFields').assign(refer('selectedFields')),
);
b.addExpression(refer('this').returned);
}); });
})); }));
@ -191,7 +233,6 @@ class OrmGenerator extends GeneratorForAnnotation<Orm> {
clazz.methods.add(Method((m) { clazz.methods.add(Method((m) {
m m
..name = 'parseRow' ..name = 'parseRow'
..static = true
..returns = refer('Optional<${rc.pascalCase}>') ..returns = refer('Optional<${rc.pascalCase}>')
..requiredParameters.add(Parameter((b) => b ..requiredParameters.add(Parameter((b) => b
..name = 'row' ..name = 'row'
@ -207,7 +248,8 @@ class OrmGenerator extends GeneratorForAnnotation<Orm> {
type = refer('int'); type = refer('int');
} }
var expr = (refer('row').index(literalNum(i++))); literalNum(i++);
var expr = (refer('row').index(CodeExpression(Code('_index++'))));
if (isSpecialId(ctx, field)) { if (isSpecialId(ctx, field)) {
expr = expr.property('toString').call([]); expr = expr.property('toString').call([]);
} else if (field is RelationFieldImpl) { } else if (field is RelationFieldImpl) {
@ -227,12 +269,15 @@ class OrmGenerator extends GeneratorForAnnotation<Orm> {
} else { } else {
expr = expr.asA(type); expr = expr.asA(type);
} }
expr = refer('fields').property('contains').call([
literalString(ctx.buildContext.resolveFieldName(field.name)!)
]).conditional(expr, refer('null'));
args[field.name] = expr; args[field.name] = expr;
} }
b.statements.add(Code( b.statements.add(Code(
'if (row.every((x) => x == null)) { return Optional.empty(); }')); 'if (row.every((x) => x == null)) { return Optional.empty(); }'));
b.addExpression(refer('0').assignVar('_index'));
b.addExpression(ctx.buildContext.modelClassType b.addExpression(ctx.buildContext.modelClassType
.newInstance([], args).assignVar('model')); .newInstance([], args).assignVar('model'));