Option to use the column name as json key in moor files

Closes #176
This commit is contained in:
Simon Binder 2019-10-17 21:44:20 +02:00
parent 95f37575f8
commit 263004fe7b
No known key found for this signature in database
GPG Key ID: 7891917E4147B8C0
10 changed files with 45 additions and 14 deletions

View File

@ -43,12 +43,17 @@ At the moment, moor supports these options:
is based on the table name (e.g. a `@DataClassName('Users') class UsersTable extends Table` would generate
a `UsersTableCompanion`). With this option, the name is based on the data class (so `UsersCompanion` in
this case).
* `use_column_name_as_json_key_when_defined_in_moor_file`: When serializing columns declared inside a
`.moor` file from and to json, use their sql name instead of the generated Dart getter name
(so a column named `user_name` would also use `user_name` as a json key instead of `userName`).
This will be the only option in moor 3.0. You can always override the json key by using a `JSON KEY`
column constraint (e.g. `user_name VARCHAR NOT NULL JSON KEY userName`)
## Recommended options
In general, we recommend not enabling these options unless you need to. There are two exceptions though:
In general, we recommend not enabling these options unless you need to. There are some exceptions though:
- `compact_query_methods`: We recommend enabling this flag because it generates less code and it will
be the only option in the next breaking upgrade.
- `compact_query_methods` and `use_column_name_as_json_key_when_defined_in_moor_file`: We recommend enabling
both flags for new projects because they'll be the only option in the next breaking release.
- `skip_verification_code`: You can remove a significant portion of generated code with this option. The
downside is that error messages when inserting invalid data will be less specific.
downside is that error messages when inserting invalid data will be less specific.

View File

@ -4,3 +4,4 @@ targets:
moor_generator:
options:
override_hash_and_equals_in_result_sets: true
use_column_name_as_json_key_when_defined_in_moor_file: true

View File

@ -25,7 +25,7 @@ class InsertStatement<D extends DataClass> {
/// thrown.
///
/// If [orReplace] is true and a row with the same primary key already exists,
/// the columns of that row will be updated and now new row will be written.
/// the columns of that row will be updated and no new row will be written.
/// Otherwise, an exception will be thrown.
///
/// If the table contains an auto-increment column, the generated value will

View File

@ -495,16 +495,16 @@ class Config extends DataClass implements Insertable<Config> {
factory Config.fromJson(Map<String, dynamic> json,
{ValueSerializer serializer = const ValueSerializer.defaults()}) {
return Config(
configKey: serializer.fromJson<String>(json['configKey']),
configValue: serializer.fromJson<String>(json['configValue']),
configKey: serializer.fromJson<String>(json['config_key']),
configValue: serializer.fromJson<String>(json['config_value']),
);
}
@override
Map<String, dynamic> toJson(
{ValueSerializer serializer = const ValueSerializer.defaults()}) {
return {
'configKey': serializer.toJson<String>(configKey),
'configValue': serializer.toJson<String>(configValue),
'config_key': serializer.toJson<String>(configKey),
'config_value': serializer.toJson<String>(configValue),
};
}

View File

@ -4,6 +4,8 @@
tables inheriting from that class will also have a `foo` column)
- New `use_data_class_name_for_companions` option that will make the name of the companion
based on the data class name (uses table name by default).
- New `use_column_name_as_json_key_when_defined_in_moor_file` option to use the column name
instead of the Dart getter name as json key for columns declared in moor files
## 2.0.1

View File

@ -26,6 +26,10 @@ class ColumnDeclaration extends BaseDeclaration {
/// The moor version of the declared column.
final SpecifiedColumn column;
/// Whether this declaration is from a moor file (e.g. inside a `CREATE TABLE`
/// statement).
bool get isDefinedInMoorFile => moorDeclaration != null;
ColumnDeclaration(this.column, FoundFile declarationFile,
Element dartDeclaration, AstNode moorDeclaration)
: super(declarationFile, dartDeclaration, moorDeclaration);

View File

@ -6,13 +6,15 @@ class MoorOptions {
final bool compactQueryMethods;
final bool skipVerificationCode;
final bool useDataClassNameForCompanions;
final bool useColumnNameAsJsonKeyWhenDefinedInMoorFile;
const MoorOptions(
{this.generateFromJsonStringConstructor = false,
this.overrideHashAndEqualsInResultSets = false,
this.compactQueryMethods = false,
this.skipVerificationCode = false,
this.useDataClassNameForCompanions = false});
this.useDataClassNameForCompanions = false,
this.useColumnNameAsJsonKeyWhenDefinedInMoorFile = false});
factory MoorOptions.fromBuilder(Map<String, dynamic> config) {
final writeFromString =
@ -30,12 +32,19 @@ class MoorOptions {
final dataClassNamesForCompanions =
config['use_data_class_name_for_companions'] as bool ?? false;
final useColumnNameAsJsonKeyForMoor =
config['use_column_name_as_json_key_when_defined_in_moor_file']
as bool ??
false;
return MoorOptions(
generateFromJsonStringConstructor: writeFromString,
overrideHashAndEqualsInResultSets: overrideInResultSets,
compactQueryMethods: compactQueryMethods,
skipVerificationCode: skipVerificationCode,
useDataClassNameForCompanions: dataClassNamesForCompanions,
useColumnNameAsJsonKeyWhenDefinedInMoorFile:
useColumnNameAsJsonKeyForMoor,
);
}
}

View File

@ -1,5 +1,6 @@
import 'package:built_value/built_value.dart';
import 'package:moor_generator/src/analyzer/sql_queries/meta/declarations.dart';
import 'package:moor_generator/src/backends/build/moor_builder.dart';
import 'package:moor_generator/src/model/used_type_converter.dart';
part 'specified_column.g.dart';
@ -81,6 +82,9 @@ class SpecifiedColumn {
/// column was created in source code.
ColumnDeclaration declaration;
/// Whether this column was declared inside a moor file.
bool get declaredInMoorFile => declaration?.isDefinedInMoorFile ?? false;
/// The sql type of this column
final ColumnType type;
@ -89,7 +93,13 @@ class SpecifiedColumn {
/// An (optional) name to use as a json key instead of the [dartGetterName].
final String overriddenJsonName;
String get jsonKey => overriddenJsonName ?? dartGetterName;
String getJsonKey([MoorOptions options = const MoorOptions()]) {
if (overriddenJsonName != null) return overriddenJsonName;
final useColumnName = options.useColumnNameAsJsonKeyWhenDefinedInMoorFile &&
declaredInMoorFile;
return useColumnName ? name.name : dartGetterName;
}
/// Whether the user has explicitly declared this column to be nullable, the
/// default is false

View File

@ -117,7 +117,7 @@ class DataClassWriter {
for (var column in table.columns) {
final getter = column.dartGetterName;
final jsonKey = column.jsonKey;
final jsonKey = column.getJsonKey(scope.options);
final type = column.dartTypeName;
_buffer.write("$getter: serializer.fromJson<$type>(json['$jsonKey']),");
@ -141,7 +141,7 @@ class DataClassWriter {
'\n return {');
for (var column in table.columns) {
final name = column.jsonKey;
final name = column.getJsonKey(scope.options);
final getter = column.dartGetterName;
final needsThis = getter == 'serializer';
final value = needsThis ? 'this.$getter' : getter;

View File

@ -31,7 +31,7 @@ usersWithLongName: SELECT * FROM users WHERE LENGTH(name) > 25
['id', 'name', 'field', 'another', 'differentJson']);
expect(table.columns.map((c) => c.dartTypeName),
['int', 'String', 'bool', 'DateTime', 'int']);
expect(table.columns.map((c) => c.jsonKey),
expect(table.columns.map((c) => c.getJsonKey()),
['id', 'name', 'field', 'another', 'myJsonKey']);
});
}