Always use a lambda for select mapping

This commit is contained in:
Simon Binder 2020-05-21 19:37:54 +02:00
parent 6c18eb22fa
commit 513881b13f
No known key found for this signature in database
GPG Key ID: 7891917E4147B8C0
6 changed files with 134 additions and 151 deletions

View File

@ -967,18 +967,16 @@ abstract class _$Database extends GeneratedDatabase {
$IngredientInRecipesTable _ingredientInRecipes;
$IngredientInRecipesTable get ingredientInRecipes =>
_ingredientInRecipes ??= $IngredientInRecipesTable(this);
TotalWeightResult _rowToTotalWeightResult(QueryRow row) {
return TotalWeightResult(
title: row.readString('title'),
totalWeight: row.readInt('total_weight'),
);
}
Selectable<TotalWeightResult> totalWeight() {
return customSelect(
'SELECT r.title, SUM(ir.amount) AS total_weight\n FROM recipes r\n INNER JOIN recipe_ingredients ir ON ir.recipe = r.id\n GROUP BY r.id',
variables: [],
readsFrom: {recipes, ingredientInRecipes}).map(_rowToTotalWeightResult);
readsFrom: {recipes, ingredientInRecipes}).map((QueryRow row) {
return TotalWeightResult(
title: row.readString('title'),
totalWeight: row.readInt('total_weight'),
);
});
}
@override

View File

@ -1349,20 +1349,18 @@ abstract class _$CustomTablesDb extends GeneratedDatabase {
Mytable get mytable => _mytable ??= Mytable(this);
Email _email;
Email get email => _email ??= Email(this);
Config _rowToConfig(QueryRow row) {
return Config(
configKey: row.readString('config_key'),
configValue: row.readString('config_value'),
syncState: ConfigTable.$converter0.mapToDart(row.readInt('sync_state')),
syncStateImplicit:
ConfigTable.$converter1.mapToDart(row.readInt('sync_state_implicit')),
);
}
Selectable<Config> readConfig(String var1) {
return customSelect('SELECT * FROM config WHERE config_key = ?',
variables: [Variable.withString(var1)],
readsFrom: {config}).map(_rowToConfig);
readsFrom: {config}).map((QueryRow row) {
return Config(
configKey: row.readString('config_key'),
configValue: row.readString('config_value'),
syncState: ConfigTable.$converter0.mapToDart(row.readInt('sync_state')),
syncStateImplicit: ConfigTable.$converter1
.mapToDart(row.readInt('sync_state_implicit')),
);
});
}
Selectable<Config> readMultiple(List<String> var1, OrderBy clause) {
@ -1379,36 +1377,42 @@ abstract class _$CustomTablesDb extends GeneratedDatabase {
],
readsFrom: {
config
}).map(_rowToConfig);
}).map((QueryRow row) {
return Config(
configKey: row.readString('config_key'),
configValue: row.readString('config_value'),
syncState: ConfigTable.$converter0.mapToDart(row.readInt('sync_state')),
syncStateImplicit: ConfigTable.$converter1
.mapToDart(row.readInt('sync_state_implicit')),
);
});
}
Selectable<Config> readDynamic(Expression<bool> predicate) {
final generatedpredicate = $write(predicate);
return customSelect('SELECT * FROM config WHERE ${generatedpredicate.sql}',
variables: [...generatedpredicate.introducedVariables],
readsFrom: {config}).map(_rowToConfig);
}
TableValuedResult _rowToTableValuedResult(QueryRow row) {
return TableValuedResult(
key: row.readString('key'),
value: row.readString('value'),
);
readsFrom: {config}).map((QueryRow row) {
return Config(
configKey: row.readString('config_key'),
configValue: row.readString('config_value'),
syncState: ConfigTable.$converter0.mapToDart(row.readInt('sync_state')),
syncStateImplicit: ConfigTable.$converter1
.mapToDart(row.readInt('sync_state_implicit')),
);
});
}
Selectable<TableValuedResult> tableValued() {
return customSelect(
'SELECT "key", "value"\n FROM config, json_each(config.config_value)\n WHERE json_valid(config_value)',
variables: [],
readsFrom: {config}).map(_rowToTableValuedResult);
}
MultipleResult _rowToMultipleResult(QueryRow row) {
return MultipleResult(
a: row.readString('a'),
b: row.readInt('b'),
c: withConstraints.mapFromRowOrNull(row, tablePrefix: 'nested_0'),
);
readsFrom: {config}).map((QueryRow row) {
return TableValuedResult(
key: row.readString('key'),
value: row.readString('value'),
);
});
}
Selectable<MultipleResult> multiple(Expression<bool> predicate) {
@ -1416,33 +1420,26 @@ abstract class _$CustomTablesDb extends GeneratedDatabase {
return customSelect(
'SELECT d.*, "c"."a" AS "nested_0.a", "c"."b" AS "nested_0.b", "c"."c" AS "nested_0.c" FROM with_constraints c\n INNER JOIN with_defaults d\n ON d.a = c.a AND d.b = c.b\n WHERE ${generatedpredicate.sql}',
variables: [...generatedpredicate.introducedVariables],
readsFrom: {withConstraints, withDefaults}).map(_rowToMultipleResult);
}
EMail _rowToEMail(QueryRow row) {
return EMail(
sender: row.readString('sender'),
title: row.readString('title'),
body: row.readString('body'),
);
readsFrom: {withConstraints, withDefaults}).map((QueryRow row) {
return MultipleResult(
a: row.readString('a'),
b: row.readInt('b'),
c: withConstraints.mapFromRowOrNull(row, tablePrefix: 'nested_0'),
);
});
}
Selectable<EMail> searchEmails(String term) {
return customSelect(
'SELECT * FROM email WHERE email MATCH :term ORDER BY rank',
variables: [Variable.withString(term)],
readsFrom: {email}).map(_rowToEMail);
}
ReadRowIdResult _rowToReadRowIdResult(QueryRow row) {
return ReadRowIdResult(
rowid: row.readInt('rowid'),
configKey: row.readString('config_key'),
configValue: row.readString('config_value'),
syncState: ConfigTable.$converter0.mapToDart(row.readInt('sync_state')),
syncStateImplicit:
ConfigTable.$converter1.mapToDart(row.readInt('sync_state_implicit')),
);
readsFrom: {email}).map((QueryRow row) {
return EMail(
sender: row.readString('sender'),
title: row.readString('title'),
body: row.readString('body'),
);
});
}
Selectable<ReadRowIdResult> readRowId(Expression<int> expr) {
@ -1450,7 +1447,16 @@ abstract class _$CustomTablesDb extends GeneratedDatabase {
return customSelect(
'SELECT oid, * FROM config WHERE _rowid_ = ${generatedexpr.sql}',
variables: [...generatedexpr.introducedVariables],
readsFrom: {config}).map(_rowToReadRowIdResult);
readsFrom: {config}).map((QueryRow row) {
return ReadRowIdResult(
rowid: row.readInt('rowid'),
configKey: row.readString('config_key'),
configValue: row.readString('config_value'),
syncState: ConfigTable.$converter0.mapToDart(row.readInt('sync_state')),
syncStateImplicit: ConfigTable.$converter1
.mapToDart(row.readInt('sync_state_implicit')),
);
});
}
Selectable<int> cfeTest() {

View File

@ -1531,26 +1531,21 @@ abstract class _$TodoDb extends GeneratedDatabase {
_pureDefaults ??= $PureDefaultsTable(this);
SomeDao _someDao;
SomeDao get someDao => _someDao ??= SomeDao(this as TodoDb);
AllTodosWithCategoryResult _rowToAllTodosWithCategoryResult(QueryRow row) {
return AllTodosWithCategoryResult(
id: row.readInt('id'),
title: row.readString('title'),
content: row.readString('content'),
targetDate: row.readDateTime('target_date'),
category: row.readInt('category'),
catId: row.readInt('catId'),
catDesc: row.readString('catDesc'),
);
}
Selectable<AllTodosWithCategoryResult> allTodosWithCategory() {
return customSelect(
'SELECT t.*, c.id as catId, c."desc" as catDesc FROM todos t INNER JOIN categories c ON c.id = t.category',
variables: [],
readsFrom: {
categories,
todosTable
}).map(_rowToAllTodosWithCategoryResult);
readsFrom: {categories, todosTable}).map((QueryRow row) {
return AllTodosWithCategoryResult(
id: row.readInt('id'),
title: row.readString('title'),
content: row.readString('content'),
targetDate: row.readDateTime('target_date'),
category: row.readInt('category'),
catId: row.readInt('catId'),
catDesc: row.readString('catDesc'),
);
});
}
Future<int> deleteTodoById(int var1) {
@ -1562,16 +1557,6 @@ abstract class _$TodoDb extends GeneratedDatabase {
);
}
TodoEntry _rowToTodoEntry(QueryRow row) {
return TodoEntry(
id: row.readInt('id'),
title: row.readString('title'),
content: row.readString('content'),
targetDate: row.readDateTime('target_date'),
category: row.readInt('category'),
);
}
Selectable<TodoEntry> withIn(String var1, String var2, List<int> var3) {
var $arrayStartIndex = 3;
final expandedvar3 = $expandVar($arrayStartIndex, var3.length);
@ -1585,14 +1570,30 @@ abstract class _$TodoDb extends GeneratedDatabase {
],
readsFrom: {
todosTable
}).map(_rowToTodoEntry);
}).map((QueryRow row) {
return TodoEntry(
id: row.readInt('id'),
title: row.readString('title'),
content: row.readString('content'),
targetDate: row.readDateTime('target_date'),
category: row.readInt('category'),
);
});
}
Selectable<TodoEntry> search(int id) {
return customSelect(
'SELECT * FROM todos WHERE CASE WHEN -1 = :id THEN 1 ELSE id = :id END',
variables: [Variable.withInt(id)],
readsFrom: {todosTable}).map(_rowToTodoEntry);
readsFrom: {todosTable}).map((QueryRow row) {
return TodoEntry(
id: row.readInt('id'),
title: row.readString('title'),
content: row.readString('content'),
targetDate: row.readDateTime('target_date'),
category: row.readInt('category'),
);
});
}
Selectable<MyCustomObject> findCustom() {
@ -1666,20 +1667,18 @@ mixin _$SomeDaoMixin on DatabaseAccessor<TodoDb> {
$UsersTable get users => attachedDatabase.users;
$SharedTodosTable get sharedTodos => attachedDatabase.sharedTodos;
$TodosTableTable get todosTable => attachedDatabase.todosTable;
TodoEntry _rowToTodoEntry(QueryRow row) {
return TodoEntry(
id: row.readInt('id'),
title: row.readString('title'),
content: row.readString('content'),
targetDate: row.readDateTime('target_date'),
category: row.readInt('category'),
);
}
Selectable<TodoEntry> todosForUser(int user) {
return customSelect(
'SELECT t.* FROM todos t INNER JOIN shared_todos st ON st.todo = t.id INNER JOIN users u ON u.id = st.user WHERE u.id = :user',
variables: [Variable.withInt(user)],
readsFrom: {todosTable, sharedTodos, users}).map(_rowToTodoEntry);
readsFrom: {todosTable, sharedTodos, users}).map((QueryRow row) {
return TodoEntry(
id: row.readInt('id'),
title: row.readString('title'),
content: row.readString('content'),
targetDate: row.readDateTime('target_date'),
category: row.readInt('category'),
);
});
}
}

View File

@ -28,9 +28,8 @@ class DaoGenerator extends Generator implements BaseGenerator {
'$infoType get $getterName => attachedDatabase.$getterName;\n');
}
final writtenMappingMethods = <String>{};
for (final query in dao.queries) {
QueryWriter(query, classScope.child(), writtenMappingMethods).write();
QueryWriter(query, classScope.child()).write();
}
classScope.leaf().write('}');

View File

@ -86,9 +86,8 @@ class DatabaseWriter {
}
// Write implementation for query methods
final writtenMappingMethods = <String>{};
for (final query in db.queries) {
QueryWriter(query, dbScope.child(), writtenMappingMethods).write();
QueryWriter(query, dbScope.child()).write();
}
// Write List of tables

View File

@ -30,9 +30,7 @@ class QueryWriter {
bool get _newSelectableMode =>
query.declaredInMoorFile || options.compactQueryMethods;
final Set<String> _writtenMappingMethods;
QueryWriter(this.query, this.scope, this._writtenMappingMethods) {
QueryWriter(this.query, this.scope) {
_buffer = scope.leaf();
}
@ -67,9 +65,6 @@ class QueryWriter {
void _writeSelect() {
_createNamesForNestedResults();
if (!_select.resultSet.singleColumn) {
_writeMapping();
}
_writeSelectStatementCreator();
@ -79,10 +74,6 @@ class QueryWriter {
}
}
String _nameOfMappingMethod() {
return '_rowTo${_select.resultClassName}';
}
String _nameOfCreationMethod() {
if (_newSelectableMode) {
return query.name;
@ -99,38 +90,36 @@ class QueryWriter {
}
}
/// Writes a mapping method that turns a "QueryRow" into the desired custom
/// return type.
void _writeMapping() {
// avoid writing mapping methods twice if the same result class is written
// more than once.
if (!_writtenMappingMethods.contains(_nameOfMappingMethod())) {
_buffer
..write('${_select.resultClassName} ${_nameOfMappingMethod()}')
..write('(QueryRow row) {\n');
// note that, even if the result set has a matching table, we can't just
// use the mapFromRow() function of that table - the column names might
// be different!
_buffer.write('return ${_select.resultClassName}(');
for (final column in _select.resultSet.columns) {
final fieldName = _select.resultSet.dartNameFor(column);
_buffer.write('$fieldName: ${_readingCode(column)},');
}
for (final nested in _select.resultSet.nestedResults) {
final prefix = _expandedNestedPrefixes[nested];
if (prefix == null) continue;
final fieldName = nested.dartFieldName;
final tableGetter = nested.table.dbGetterName;
_buffer.write('$fieldName: $tableGetter.mapFromRowOrNull(row, '
'tablePrefix: ${asDartLiteral(prefix)}),');
}
_buffer.write(');\n}\n');
_writtenMappingMethods.add(_nameOfMappingMethod());
/// Writes the function literal that turns a "QueryRow" into the desired
/// custom return type of a select statement.
void _writeMappingLambda() {
if (_select.resultSet.singleColumn) {
final column = _select.resultSet.columns.single;
_buffer.write('(QueryRow row) => ${_readingCode(column)}');
return;
}
_buffer.write('(QueryRow row) {\n');
// note that, even if the result set has a matching table, we can't just
// use the mapFromRow() function of that table - the column names might
// be different!
_buffer.write('return ${_select.resultClassName}(');
for (final column in _select.resultSet.columns) {
final fieldName = _select.resultSet.dartNameFor(column);
_buffer.write('$fieldName: ${_readingCode(column)},');
}
for (final nested in _select.resultSet.nestedResults) {
final prefix = _expandedNestedPrefixes[nested];
if (prefix == null) continue;
final fieldName = nested.dartFieldName;
final tableGetter = nested.table.dbGetterName;
_buffer.write('$fieldName: $tableGetter.mapFromRowOrNull(row, '
'tablePrefix: ${asDartLiteral(prefix)}),');
}
_buffer.write(');\n}');
}
/// Returns Dart code that, given a variable of type `QueryRow` named `row`
@ -169,14 +158,7 @@ class QueryWriter {
_writeReadsFrom();
_buffer.write(').map(');
// for queries that only return one row, it makes more sense to inline the
// mapping code with a lambda
if (_select.resultSet.singleColumn) {
final column = _select.resultSet.columns.single;
_buffer.write('(QueryRow row) => ${_readingCode(column)}');
} else {
_buffer.write(_nameOfMappingMethod());
}
_writeMappingLambda();
_buffer.write(');\n}\n');
}