create many to many

This commit is contained in:
Tobe O 2018-12-08 17:51:27 -05:00
parent 19c87d7f2b
commit 43501c80b8
21 changed files with 662 additions and 296 deletions

View file

@ -8,8 +8,14 @@ builders:
build_extensions:
.dart:
- ".angel_orm.g.part"
required_inputs:
- angel_serialize.g.part
- angel_serialize_serializer.g.part
applies_builders:
["source_gen|combining_builder", "source_gen|part_cleanup"]
- angel_serialize_generator|angel_serialize
- source_gen|combining_builder
- source_gen|part_cleanup"
targets:
_standalone:
sources:

View file

@ -23,7 +23,7 @@ bool isBelongsRelation(Relationship r) =>
r.type == RelationshipType.belongsTo ||
r.type == RelationshipType.belongsToMany;
final Map<Uri, OrmBuildContext> _cache = {};
final Map<String, OrmBuildContext> _cache = {};
Future<OrmBuildContext> buildOrmContext(
ClassElement clazz,
@ -44,9 +44,9 @@ Future<OrmBuildContext> buildOrmContext(
clazz = clazz.supertype.element;
}
var uri = clazz.source.uri;
if (_cache.containsKey(uri)) {
return _cache[uri];
var id = clazz.location.components.join('-');
if (_cache.containsKey(id)) {
return _cache[id];
}
var buildCtx = await buildContext(clazz, annotation, buildStep, resolver,
autoSnakeCaseNames, autoIdAndDateFields,
@ -58,7 +58,7 @@ Future<OrmBuildContext> buildOrmContext(
(ormAnnotation.tableName?.isNotEmpty == true)
? ormAnnotation.tableName
: pluralize(new ReCase(clazz.name).snakeCase));
_cache[uri] = ctx;
_cache[id] = ctx;
// Read all fields
for (var field in buildCtx.fields) {
@ -95,7 +95,9 @@ Future<OrmBuildContext> buildOrmContext(
}
// Try to find a relationship
var ann = relationshipTypeChecker.firstAnnotationOf(field);
var el = field.setter == null ? field.getter : field;
el ??= field;
var ann = relationshipTypeChecker.firstAnnotationOf(el);
if (ann != null) {
var cr = new ConstantReader(ann);
@ -108,16 +110,22 @@ Future<OrmBuildContext> buildOrmContext(
OrmBuildContext foreign;
if (foreignTable == null) {
if (!isModelClass(field.type) &&
!(field.type is InterfaceType &&
isListOfModelType(field.type as InterfaceType))) {
// if (!isModelClass(field.type) &&
// !(field.type is InterfaceType &&
// isListOfModelType(field.type as InterfaceType))) {
if (!(field.type is InterfaceType &&
isListOfModelType(field.type as InterfaceType)) &&
!isModelClass(field.type)) {
throw new UnsupportedError(
'Cannot apply relationship to field "${field.name}" - ${field.type.name} is not assignable to Model.');
'Cannot apply relationship to field "${field.name}" - ${field.type} is not assignable to Model.');
} else {
try {
var refType = field.type;
if (refType is InterfaceType && isListOfModelType(refType)) {
if (refType is InterfaceType &&
const TypeChecker.fromRuntime(List)
.isAssignableFromType(refType) &&
refType.typeArguments.length == 1) {
refType = (refType as InterfaceType).typeArguments[0];
}
@ -131,6 +139,7 @@ Future<OrmBuildContext> buildOrmContext(
resolver,
autoSnakeCaseNames,
autoIdAndDateFields);
var ormAnn = const TypeChecker.fromRuntime(Orm)
.firstAnnotationOf(modelType.element);
@ -184,7 +193,7 @@ Future<OrmBuildContext> buildOrmContext(
ctx.relationTypes[relation] = foreign;
} else {
if (column?.type == null)
throw 'Cannot infer SQL column type for field "${field.name}" with type "${field.type.name}".';
throw 'Cannot infer SQL column type for field "${ctx.buildContext.originalClassName}.${field.name}" with type "${field.type.displayName}".';
ctx.columns[field.name] = column;
if (!ctx.effectiveFields.any((f) => f.name == field.name))
@ -265,10 +274,13 @@ class RelationFieldImpl extends ShimFieldImpl {
InterfaceType firstModelAncestor(DartType type) {
if (type is InterfaceType) {
if (const TypeChecker.fromRuntime(Model).isExactlyType(type.superclass)) {
if (type.superclass != null &&
const TypeChecker.fromRuntime(Model).isExactlyType(type.superclass)) {
return type;
} else {
return firstModelAncestor(type.superclass);
return type.superclass == null
? null
: firstModelAncestor(type.superclass);
}
} else {
return null;

View file

@ -2,6 +2,7 @@ import 'dart:async';
import 'package:analyzer/dart/element/element.dart';
import 'package:angel_orm/angel_orm.dart';
import 'package:angel_serialize_generator/angel_serialize_generator.dart';
import 'package:angel_serialize_generator/build_context.dart';
import 'package:build/build.dart';
import 'package:code_builder/code_builder.dart' hide LibraryBuilder;
import 'package:source_gen/source_gen.dart';
@ -53,8 +54,6 @@ class OrmGenerator extends GeneratorForAnnotation<Orm> {
}
Class buildQueryClass(OrmBuildContext ctx) {
// TODO: Handle relations
return new Class((clazz) {
var rc = ctx.buildContext.modelClassNameRecase;
var queryWhereType = refer('${rc.pascalCase}QueryWhere');
@ -224,52 +223,62 @@ class OrmGenerator extends GeneratorForAnnotation<Orm> {
});
});
}));
if (ctx.relations.isNotEmpty) {
clazz.methods.add(new Method((b) {
b
..name = 'insert'
..annotations.add(refer('override'))
..requiredParameters
.add(new Parameter((b) => b..name = 'executor'))
..body = new Block((b) {
var inTransaction = new Method((b) {
b
..modifier = MethodModifier.async
..body = new Block((b) {
b.addExpression(refer('super')
.property('insert')
.call([refer('executor')])
.awaited
.assignVar('result'));
clazz.methods.add(new Method((b) {
b
..name = 'insert'
..annotations.add(refer('override'))
..requiredParameters.add(new Parameter((b) => b..name = 'executor'))
..body = new Block((b) {
var inTransaction = new Method((b) {
b
..modifier = MethodModifier.async
..body = new Block((b) {
b.addExpression(refer('super')
.property('insert')
.call([refer('executor')])
.awaited
.assignVar('result'));
// Just call getOne() again
if (ctx.effectiveFields.any((f) =>
isSpecialId(f) ||
(ctx.columns[f.name]?.indexType ==
IndexType.primaryKey))) {
b.addExpression(refer('where')
.property('id')
.property('equals')
.call([
(refer('int')
.property('parse')
.call([refer('result').property('id')]))
]));
// Just call get() again
b.addExpression(
refer('where').property('id').property('equals').call([
(refer('int')
.property('parse')
.call([refer('result').property('id')]))
]));
b.addExpression(refer('result').assign(
refer('getOne').call([refer('executor')]).awaited));
// Fetch the results of @hasMany
ctx.relations.forEach((name, relation) {
if (relation.type == RelationshipType.hasMany) {
// Call fetchLinked();
var fetchLinked = refer('fetchLinked')
.call([refer('result'), refer('executor')]).awaited;
b.addExpression(refer('result').assign(fetchLinked));
b.addExpression(refer('result').assign(
refer('getOne').call([refer('executor')]).awaited));
}
// Fetch the results of @hasMany
ctx.relations.forEach((name, relation) {
if (relation.type == RelationshipType.hasMany) {
// Call fetchLinked();
var fetchLinked = refer('fetchLinked').call(
[refer('result'), refer('executor')]).awaited;
b.addExpression(refer('result').assign(fetchLinked));
}
});
b.addExpression(refer('result').returned);
});
});
b.addExpression(refer('result').returned);
});
b.addExpression(refer('executor')
.property('transaction')
.call([inTransaction.closure]).returned);
});
b.addExpression(refer('executor')
.property('transaction')
.call([inTransaction.closure]).returned);
});
}));
}));
}
}
// Create a Future<T> fetchLinked(T model, QueryExecutor), if necessary.
@ -304,7 +313,7 @@ class OrmGenerator extends GeneratorForAnnotation<Orm> {
var queryInstance = queryType.newInstance([]);
// Next, we need to apply a cascade that sets the correct query value.
var localField = ctx.buildContext.fields.firstWhere(
var localField = ctx.effectiveFields.firstWhere(
(f) =>
ctx.buildContext.resolveFieldName(f.name) ==
relation.localKey, orElse: () {
@ -312,7 +321,7 @@ class OrmGenerator extends GeneratorForAnnotation<Orm> {
'but it has a @HasMany() relation that expects such a field.';
});
var foreignField = foreign.buildContext.fields.firstWhere(
var foreignField = foreign.effectiveFields.firstWhere(
(f) =>
foreign.buildContext.resolveFieldName(f.name) ==
relation.foreignKey, orElse: () {
@ -320,10 +329,9 @@ class OrmGenerator extends GeneratorForAnnotation<Orm> {
'but ${ctx.buildContext.clazz.name} has a @HasMany() relation that expects such a field.';
});
var queryValue =
(localField.name == 'id' && autoIdAndDateFields)
? 'int.parse(model.id)'
: 'model.${localField.name}';
var queryValue = (isSpecialId(localField))
? 'int.parse(model.id)'
: 'model.${localField.name}';
var cascadeText =
'..where.${foreignField.name}.equals($queryValue)';
var queryText = queryInstance.accept(new DartEmitter());
@ -358,14 +366,17 @@ class OrmGenerator extends GeneratorForAnnotation<Orm> {
..type = refer('QueryExecutor')))
..body = new Block((b) {
var inTransaction = new Method((b) {
b..modifier = MethodModifier.async
..body = new Block((b) {
var mapped = new CodeExpression(new Code('await Future.wait(result.map((m) => fetchLinked(m, executor)))'));
b.addExpression(new CodeExpression(new Code('var result = await super.$methodName(executor)')));
b.addExpression(mapped.returned);
});
b
..modifier = MethodModifier.async
..body = new Block((b) {
var mapped = new CodeExpression(new Code(
'await Future.wait(result.map((m) => fetchLinked(m, executor)))'));
b.addExpression(new CodeExpression(new Code(
'var result = await super.$methodName(executor)')));
b.addExpression(mapped.returned);
});
});
b.addExpression(refer('executor')
.property('transaction')
.call([inTransaction.closure]).returned);
@ -377,7 +388,9 @@ class OrmGenerator extends GeneratorForAnnotation<Orm> {
}
bool isSpecialId(FieldElement field) {
return (field.name == 'id' && autoIdAndDateFields);
return field is ShimFieldImpl &&
field is! RelationFieldImpl &&
(field.name == 'id' && autoIdAndDateFields);
}
Class buildWhereClass(OrmBuildContext ctx) {
@ -401,7 +414,6 @@ class OrmGenerator extends GeneratorForAnnotation<Orm> {
// Add builders for each field
for (var field in ctx.effectiveFields) {
// TODO: Handle fields with relations
var name = field.name;
Reference builderType;

View file

@ -0,0 +1,14 @@
library angel_orm_generator.test;
import 'package:angel_orm/angel_orm.dart';
import 'package:test/test.dart';
import 'models/user.dart';
import 'common.dart';
main() {
QueryExecutor executor;
setUp(() async {
executor = await connectToPostgres(['user', 'role', 'user_role']);
});
}

View file

@ -0,0 +1,6 @@
CREATE TEMPORARY TABLE "roles" (
"id" serial PRIMARY KEY,
"name" varchar(255),
"created_at" timestamp,
"updated_at" timestamp
);

View file

@ -0,0 +1,8 @@
CREATE TEMPORARY TABLE "users" (
"id" serial PRIMARY KEY,
"username" varchar(255),
"password" varchar(255),
"email" varchar(255),
"created_at" timestamp,
"updated_at" timestamp
);

View file

@ -0,0 +1,7 @@
CREATE TEMPORARY TABLE "user_roles" (
"id" serial PRIMARY KEY,
"user_id" int NOT NULL,
"role_id" int NOT NULL,
"created_at" timestamp,
"updated_at" timestamp
);

View file

@ -7,7 +7,7 @@ part 'author.g.dart';
@serializable
@orm
class _Author extends Model {
abstract class _Author extends Model {
@Column(length: 255, indexType: IndexType.unique, defaultValue: 'Tobe Osakwe')
String name;
String get name;
}

View file

@ -161,7 +161,7 @@ abstract class AuthorSerializer {
: null);
}
static Map<String, dynamic> toMap(Author model) {
static Map<String, dynamic> toMap(_Author model) {
if (model == null) {
return null;
}

View file

@ -242,7 +242,7 @@ abstract class BookSerializer {
: null);
}
static Map<String, dynamic> toMap(Book model) {
static Map<String, dynamic> toMap(_Book model) {
if (model == null) {
return null;
}

View file

@ -250,7 +250,7 @@ abstract class CarSerializer {
: null);
}
static Map<String, dynamic> toMap(Car model) {
static Map<String, dynamic> toMap(_Car model) {
if (model == null) {
return null;
}

View file

@ -142,7 +142,7 @@ abstract class CustomerSerializer {
: null);
}
static Map<String, dynamic> toMap(Customer model) {
static Map<String, dynamic> toMap(_Customer model) {
if (model == null) {
return null;
}

View file

@ -181,7 +181,7 @@ abstract class FootSerializer {
: null);
}
static Map<String, dynamic> toMap(Foot model) {
static Map<String, dynamic> toMap(_Foot model) {
if (model == null) {
return null;
}

View file

@ -182,7 +182,7 @@ abstract class FruitSerializer {
: null);
}
static Map<String, dynamic> toMap(Fruit model) {
static Map<String, dynamic> toMap(_Fruit model) {
if (model == null) {
return null;
}

View file

@ -195,7 +195,7 @@ abstract class LegSerializer {
: null);
}
static Map<String, dynamic> toMap(Leg model) {
static Map<String, dynamic> toMap(_Leg model) {
if (model == null) {
return null;
}

View file

@ -250,7 +250,7 @@ abstract class OrderSerializer {
: null);
}
static Map<String, dynamic> toMap(Order model) {
static Map<String, dynamic> toMap(_Order model) {
if (model == null) {
return null;
}

View file

@ -1,11 +0,0 @@
library angel_orm_generator.test.models.role;
import 'package:angel_model/angel_model.dart';
import 'package:angel_orm/angel_orm.dart';
import 'package:angel_serialize/angel_serialize.dart';
part 'role.g.dart';
@serializable
@orm
class _Role extends Model {
String name;
}

View file

@ -1,192 +0,0 @@
// GENERATED CODE - DO NOT MODIFY BY HAND
part of angel_orm_generator.test.models.role;
// **************************************************************************
// OrmGenerator
// **************************************************************************
class RoleQuery extends Query<Role, RoleQueryWhere> {
@override
final RoleQueryValues values = new RoleQueryValues();
@override
final RoleQueryWhere where = new RoleQueryWhere();
@override
get tableName {
return 'roles';
}
@override
get fields {
return const ['id', 'name', 'created_at', 'updated_at'];
}
@override
RoleQueryWhere newWhereClause() {
return new RoleQueryWhere();
}
static Role parseRow(List row) {
if (row.every((x) => x == null)) return null;
var model = new Role(
id: row[0].toString(),
name: (row[1] as String),
createdAt: (row[2] as DateTime),
updatedAt: (row[3] as DateTime));
return model;
}
@override
deserialize(List row) {
return parseRow(row);
}
}
class RoleQueryWhere extends QueryWhere {
final NumericSqlExpressionBuilder<int> id =
new NumericSqlExpressionBuilder<int>('id');
final StringSqlExpressionBuilder name =
new StringSqlExpressionBuilder('name');
final DateTimeSqlExpressionBuilder createdAt =
new DateTimeSqlExpressionBuilder('created_at');
final DateTimeSqlExpressionBuilder updatedAt =
new DateTimeSqlExpressionBuilder('updated_at');
@override
get expressionBuilders {
return [id, name, createdAt, updatedAt];
}
}
class RoleQueryValues extends MapQueryValues {
int get id {
return (values['id'] as int);
}
void set id(int value) => values['id'] = value;
String get name {
return (values['name'] as String);
}
void set name(String value) => values['name'] = value;
DateTime get createdAt {
return (values['created_at'] as DateTime);
}
void set createdAt(DateTime value) => values['created_at'] = value;
DateTime get updatedAt {
return (values['updated_at'] as DateTime);
}
void set updatedAt(DateTime value) => values['updated_at'] = value;
void copyFrom(Role model) {
values.addAll({
'name': model.name,
'created_at': model.createdAt,
'updated_at': model.updatedAt
});
}
}
// **************************************************************************
// JsonModelGenerator
// **************************************************************************
@generatedSerializable
class Role extends _Role {
Role({this.id, this.name, this.createdAt, this.updatedAt});
@override
final String id;
@override
final String name;
@override
final DateTime createdAt;
@override
final DateTime updatedAt;
Role copyWith(
{String id, String name, DateTime createdAt, DateTime updatedAt}) {
return new Role(
id: id ?? this.id,
name: name ?? this.name,
createdAt: createdAt ?? this.createdAt,
updatedAt: updatedAt ?? this.updatedAt);
}
bool operator ==(other) {
return other is _Role &&
other.id == id &&
other.name == name &&
other.createdAt == createdAt &&
other.updatedAt == updatedAt;
}
@override
int get hashCode {
return hashObjects([id, name, createdAt, updatedAt]);
}
Map<String, dynamic> toJson() {
return RoleSerializer.toMap(this);
}
}
// **************************************************************************
// SerializerGenerator
// **************************************************************************
abstract class RoleSerializer {
static Role fromMap(Map map) {
return new Role(
id: map['id'] as String,
name: map['name'] as String,
createdAt: map['created_at'] != null
? (map['created_at'] is DateTime
? (map['created_at'] as DateTime)
: DateTime.parse(map['created_at'].toString()))
: null,
updatedAt: map['updated_at'] != null
? (map['updated_at'] is DateTime
? (map['updated_at'] as DateTime)
: DateTime.parse(map['updated_at'].toString()))
: null);
}
static Map<String, dynamic> toMap(Role model) {
if (model == null) {
return null;
}
return {
'id': model.id,
'name': model.name,
'created_at': model.createdAt?.toIso8601String(),
'updated_at': model.updatedAt?.toIso8601String()
};
}
}
abstract class RoleFields {
static const List<String> allFields = const <String>[
id,
name,
createdAt,
updatedAt
];
static const String id = 'id';
static const String name = 'name';
static const String createdAt = 'created_at';
static const String updatedAt = 'updated_at';
}

View file

@ -222,14 +222,14 @@ abstract class TreeSerializer {
: null);
}
static Map<String, dynamic> toMap(Tree model) {
static Map<String, dynamic> toMap(_Tree model) {
if (model == null) {
return null;
}
return {
'id': model.id,
'rings': model.rings,
'fruits': model.fruits?.map((m) => m.toJson())?.toList(),
'fruits': model.fruits?.map((m) => FruitSerializer.toMap(m))?.toList(),
'created_at': model.createdAt?.toIso8601String(),
'updated_at': model.updatedAt?.toIso8601String()
};

View file

@ -4,15 +4,36 @@ import 'package:angel_model/angel_model.dart';
import 'package:angel_orm/angel_orm.dart';
import 'package:angel_serialize/angel_serialize.dart';
import 'package:collection/collection.dart';
import 'role.dart';
part 'user.g.dart';
@serializable
@orm
class _User extends Model {
String username, password, email;
abstract class _User extends Model {
String get username;
String get password;
String get email;
// TODO: Belongs to many
//@belongsToMany
//List<Role> roles;
@hasMany
List<_UserRole> get userRoles;
}
@serializable
@orm
abstract class _Role extends Model {
String name;
@hasMany
List<_UserRole> get userRoles;
}
@Serializable(autoIdAndDateFields: false)
@orm
abstract class _UserRole {
int get id;
@belongsTo
_User get user;
@belongsTo
_Role get role;
}

View file

@ -7,6 +7,8 @@ part of angel_orm_generator.test.models.user;
// **************************************************************************
class UserQuery extends Query<User, UserQueryWhere> {
UserQuery() {}
@override
final UserQueryValues values = new UserQueryValues();
@ -51,6 +53,48 @@ class UserQuery extends Query<User, UserQueryWhere> {
deserialize(List row) {
return parseRow(row);
}
@override
insert(executor) {
return executor.transaction(() async {
var result = await super.insert(executor);
where.id.equals(int.parse(result.id));
result = await getOne(executor);
result = await fetchLinked(result, executor);
return result;
});
}
Future<User> fetchLinked(User model, QueryExecutor executor) async {
return model.copyWith(
userRoles: await (new UserRoleQuery()
..where.userId.equals(int.parse(model.id)))
.get(executor));
}
@override
get(QueryExecutor executor) {
return executor.transaction(() async {
var result = await super.get(executor);
return await Future.wait(result.map((m) => fetchLinked(m, executor)));
});
}
@override
update(QueryExecutor executor) {
return executor.transaction(() async {
var result = await super.update(executor);
return await Future.wait(result.map((m) => fetchLinked(m, executor)));
});
}
@override
delete(QueryExecutor executor) {
return executor.transaction(() async {
var result = await super.delete(executor);
return await Future.wait(result.map((m) => fetchLinked(m, executor)));
});
}
}
class UserQueryWhere extends QueryWhere {
@ -120,6 +164,240 @@ class UserQueryValues extends MapQueryValues {
}
}
class RoleQuery extends Query<Role, RoleQueryWhere> {
RoleQuery() {}
@override
final RoleQueryValues values = new RoleQueryValues();
@override
final RoleQueryWhere where = new RoleQueryWhere();
@override
get tableName {
return 'roles';
}
@override
get fields {
return const ['id', 'name', 'created_at', 'updated_at'];
}
@override
RoleQueryWhere newWhereClause() {
return new RoleQueryWhere();
}
static Role parseRow(List row) {
if (row.every((x) => x == null)) return null;
var model = new Role(
id: row[0].toString(),
name: (row[1] as String),
createdAt: (row[2] as DateTime),
updatedAt: (row[3] as DateTime));
return model;
}
@override
deserialize(List row) {
return parseRow(row);
}
@override
insert(executor) {
return executor.transaction(() async {
var result = await super.insert(executor);
where.id.equals(int.parse(result.id));
result = await getOne(executor);
result = await fetchLinked(result, executor);
return result;
});
}
Future<Role> fetchLinked(Role model, QueryExecutor executor) async {
return model.copyWith(
userRoles: await (new UserRoleQuery()
..where.roleId.equals(int.parse(model.id)))
.get(executor));
}
@override
get(QueryExecutor executor) {
return executor.transaction(() async {
var result = await super.get(executor);
return await Future.wait(result.map((m) => fetchLinked(m, executor)));
});
}
@override
update(QueryExecutor executor) {
return executor.transaction(() async {
var result = await super.update(executor);
return await Future.wait(result.map((m) => fetchLinked(m, executor)));
});
}
@override
delete(QueryExecutor executor) {
return executor.transaction(() async {
var result = await super.delete(executor);
return await Future.wait(result.map((m) => fetchLinked(m, executor)));
});
}
}
class RoleQueryWhere extends QueryWhere {
final NumericSqlExpressionBuilder<int> id =
new NumericSqlExpressionBuilder<int>('id');
final StringSqlExpressionBuilder name =
new StringSqlExpressionBuilder('name');
final DateTimeSqlExpressionBuilder createdAt =
new DateTimeSqlExpressionBuilder('created_at');
final DateTimeSqlExpressionBuilder updatedAt =
new DateTimeSqlExpressionBuilder('updated_at');
@override
get expressionBuilders {
return [id, name, createdAt, updatedAt];
}
}
class RoleQueryValues extends MapQueryValues {
int get id {
return (values['id'] as int);
}
void set id(int value) => values['id'] = value;
String get name {
return (values['name'] as String);
}
void set name(String value) => values['name'] = value;
DateTime get createdAt {
return (values['created_at'] as DateTime);
}
void set createdAt(DateTime value) => values['created_at'] = value;
DateTime get updatedAt {
return (values['updated_at'] as DateTime);
}
void set updatedAt(DateTime value) => values['updated_at'] = value;
void copyFrom(Role model) {
values.addAll({
'name': model.name,
'created_at': model.createdAt,
'updated_at': model.updatedAt
});
}
}
class UserRoleQuery extends Query<UserRole, UserRoleQueryWhere> {
UserRoleQuery() {
leftJoin('users', 'user_id', 'id', additionalFields: const [
'username',
'password',
'email',
'created_at',
'updated_at'
]);
leftJoin('roles', 'role_id', 'id',
additionalFields: const ['name', 'created_at', 'updated_at']);
}
@override
final UserRoleQueryValues values = new UserRoleQueryValues();
@override
final UserRoleQueryWhere where = new UserRoleQueryWhere();
@override
get tableName {
return 'user_roles';
}
@override
get fields {
return const ['id', 'user_id', 'role_id'];
}
@override
UserRoleQueryWhere newWhereClause() {
return new UserRoleQueryWhere();
}
static UserRole parseRow(List row) {
if (row.every((x) => x == null)) return null;
var model = new UserRole(id: (row[0] as int));
if (row.length > 3) {
model = model.copyWith(user: UserQuery.parseRow(row.skip(3).toList()));
}
if (row.length > 9) {
model = model.copyWith(role: RoleQuery.parseRow(row.skip(9).toList()));
}
return model;
}
@override
deserialize(List row) {
return parseRow(row);
}
@override
insert(executor) {
return executor.transaction(() async {
var result = await super.insert(executor);
return result;
});
}
}
class UserRoleQueryWhere extends QueryWhere {
final NumericSqlExpressionBuilder<int> id =
new NumericSqlExpressionBuilder<int>('id');
final NumericSqlExpressionBuilder<int> userId =
new NumericSqlExpressionBuilder<int>('user_id');
final NumericSqlExpressionBuilder<int> roleId =
new NumericSqlExpressionBuilder<int>('role_id');
@override
get expressionBuilders {
return [id, userId, roleId];
}
}
class UserRoleQueryValues extends MapQueryValues {
int get id {
return (values['id'] as int);
}
void set id(int value) => values['id'] = value;
int get userId {
return (values['user_id'] as int);
}
void set userId(int value) => values['user_id'] = value;
int get roleId {
return (values['role_id'] as int);
}
void set roleId(int value) => values['role_id'] = value;
void copyFrom(UserRole model) {
values.addAll({'id': model.id});
if (model.user != null) {
values['user_id'] = int.parse(model.user.id);
}
if (model.role != null) {
values['role_id'] = int.parse(model.role.id);
}
}
}
// **************************************************************************
// JsonModelGenerator
// **************************************************************************
@ -131,8 +409,10 @@ class User extends _User {
this.username,
this.password,
this.email,
List<_UserRole> userRoles,
this.createdAt,
this.updatedAt});
this.updatedAt})
: this.userRoles = new List.unmodifiable(userRoles ?? []);
@override
final String id;
@ -146,6 +426,9 @@ class User extends _User {
@override
final String email;
@override
final List<_UserRole> userRoles;
@override
final DateTime createdAt;
@ -157,6 +440,7 @@ class User extends _User {
String username,
String password,
String email,
List<_UserRole> userRoles,
DateTime createdAt,
DateTime updatedAt}) {
return new User(
@ -164,6 +448,7 @@ class User extends _User {
username: username ?? this.username,
password: password ?? this.password,
email: email ?? this.email,
userRoles: userRoles ?? this.userRoles,
createdAt: createdAt ?? this.createdAt,
updatedAt: updatedAt ?? this.updatedAt);
}
@ -174,13 +459,16 @@ class User extends _User {
other.username == username &&
other.password == password &&
other.email == email &&
const ListEquality<_UserRole>(const DefaultEquality<_UserRole>())
.equals(other.userRoles, userRoles) &&
other.createdAt == createdAt &&
other.updatedAt == updatedAt;
}
@override
int get hashCode {
return hashObjects([id, username, password, email, createdAt, updatedAt]);
return hashObjects(
[id, username, password, email, userRoles, createdAt, updatedAt]);
}
Map<String, dynamic> toJson() {
@ -188,6 +476,100 @@ class User extends _User {
}
}
@generatedSerializable
class Role extends _Role {
Role(
{this.id,
this.name,
List<_UserRole> userRoles,
this.createdAt,
this.updatedAt})
: this.userRoles = new List.unmodifiable(userRoles ?? []);
@override
final String id;
@override
final String name;
@override
final List<_UserRole> userRoles;
@override
final DateTime createdAt;
@override
final DateTime updatedAt;
Role copyWith(
{String id,
String name,
List<_UserRole> userRoles,
DateTime createdAt,
DateTime updatedAt}) {
return new Role(
id: id ?? this.id,
name: name ?? this.name,
userRoles: userRoles ?? this.userRoles,
createdAt: createdAt ?? this.createdAt,
updatedAt: updatedAt ?? this.updatedAt);
}
bool operator ==(other) {
return other is _Role &&
other.id == id &&
other.name == name &&
const ListEquality<_UserRole>(const DefaultEquality<_UserRole>())
.equals(other.userRoles, userRoles) &&
other.createdAt == createdAt &&
other.updatedAt == updatedAt;
}
@override
int get hashCode {
return hashObjects([id, name, userRoles, createdAt, updatedAt]);
}
Map<String, dynamic> toJson() {
return RoleSerializer.toMap(this);
}
}
@generatedSerializable
class UserRole implements _UserRole {
const UserRole({this.id, this.user, this.role});
@override
final int id;
@override
final _User user;
@override
final _Role role;
UserRole copyWith({int id, _User user, _Role role}) {
return new UserRole(
id: id ?? this.id, user: user ?? this.user, role: role ?? this.role);
}
bool operator ==(other) {
return other is _UserRole &&
other.id == id &&
other.user == user &&
other.role == role;
}
@override
int get hashCode {
return hashObjects([id, user, role]);
}
Map<String, dynamic> toJson() {
return UserRoleSerializer.toMap(this);
}
}
// **************************************************************************
// SerializerGenerator
// **************************************************************************
@ -199,6 +581,11 @@ abstract class UserSerializer {
username: map['username'] as String,
password: map['password'] as String,
email: map['email'] as String,
userRoles: map['user_roles'] is Iterable
? new List.unmodifiable(((map['user_roles'] as Iterable)
.where((x) => x is Map) as Iterable<Map>)
.map(UserRoleSerializer.fromMap))
: null,
createdAt: map['created_at'] != null
? (map['created_at'] is DateTime
? (map['created_at'] as DateTime)
@ -211,7 +598,7 @@ abstract class UserSerializer {
: null);
}
static Map<String, dynamic> toMap(User model) {
static Map<String, dynamic> toMap(_User model) {
if (model == null) {
return null;
}
@ -220,6 +607,8 @@ abstract class UserSerializer {
'username': model.username,
'password': model.password,
'email': model.email,
'user_roles':
model.userRoles?.map((m) => UserRoleSerializer.toMap(m))?.toList(),
'created_at': model.createdAt?.toIso8601String(),
'updated_at': model.updatedAt?.toIso8601String()
};
@ -232,6 +621,7 @@ abstract class UserFields {
username,
password,
email,
userRoles,
createdAt,
updatedAt
];
@ -244,7 +634,100 @@ abstract class UserFields {
static const String email = 'email';
static const String userRoles = 'user_roles';
static const String createdAt = 'created_at';
static const String updatedAt = 'updated_at';
}
abstract class RoleSerializer {
static Role fromMap(Map map) {
return new Role(
id: map['id'] as String,
name: map['name'] as String,
userRoles: map['user_roles'] is Iterable
? new List.unmodifiable(((map['user_roles'] as Iterable)
.where((x) => x is Map) as Iterable<Map>)
.map(UserRoleSerializer.fromMap))
: null,
createdAt: map['created_at'] != null
? (map['created_at'] is DateTime
? (map['created_at'] as DateTime)
: DateTime.parse(map['created_at'].toString()))
: null,
updatedAt: map['updated_at'] != null
? (map['updated_at'] is DateTime
? (map['updated_at'] as DateTime)
: DateTime.parse(map['updated_at'].toString()))
: null);
}
static Map<String, dynamic> toMap(_Role model) {
if (model == null) {
return null;
}
return {
'id': model.id,
'name': model.name,
'user_roles':
model.userRoles?.map((m) => UserRoleSerializer.toMap(m))?.toList(),
'created_at': model.createdAt?.toIso8601String(),
'updated_at': model.updatedAt?.toIso8601String()
};
}
}
abstract class RoleFields {
static const List<String> allFields = const <String>[
id,
name,
userRoles,
createdAt,
updatedAt
];
static const String id = 'id';
static const String name = 'name';
static const String userRoles = 'user_roles';
static const String createdAt = 'created_at';
static const String updatedAt = 'updated_at';
}
abstract class UserRoleSerializer {
static UserRole fromMap(Map map) {
return new UserRole(
id: map['id'] as int,
user: map['user'] != null
? UserSerializer.fromMap(map['user'] as Map)
: null,
role: map['role'] != null
? RoleSerializer.fromMap(map['role'] as Map)
: null);
}
static Map<String, dynamic> toMap(_UserRole model) {
if (model == null) {
return null;
}
return {
'id': model.id,
'user': UserSerializer.toMap(model.user),
'role': RoleSerializer.toMap(model.role)
};
}
}
abstract class UserRoleFields {
static const List<String> allFields = const <String>[id, user, role];
static const String id = 'id';
static const String user = 'user';
static const String role = 'role';
}