Fully migrate to new update companions

This commit is contained in:
Simon Binder 2019-06-21 19:48:18 +02:00
parent eee11d53d3
commit 0abc3993f4
No known key found for this signature in database
GPG Key ID: 7891917E4147B8C0
12 changed files with 272 additions and 175 deletions

View File

@ -7,7 +7,7 @@ part of 'example.dart';
// ************************************************************************** // **************************************************************************
// ignore_for_file: unnecessary_brace_in_string_interps // ignore_for_file: unnecessary_brace_in_string_interps
class Category extends DataClass { class Category extends DataClass implements Insertable<Category> {
final int id; final int id;
final String description; final String description;
Category({this.id, this.description}); Category({this.id, this.description});
@ -39,13 +39,13 @@ class Category extends DataClass {
} }
@override @override
CategoriesCompanion createCompanion(bool nullToAbsent) { T createCompanion<T extends UpdateCompanion<Category>>(bool nullToAbsent) {
return CategoriesCompanion( return CategoriesCompanion(
id: id == null && nullToAbsent ? const Value.absent() : Value.use(id), id: id == null && nullToAbsent ? const Value.absent() : Value.use(id),
description: description == null && nullToAbsent description: description == null && nullToAbsent
? const Value.absent() ? const Value.absent()
: Value.use(description), : Value.use(description),
); ) as T;
} }
Category copyWith({int id, String description}) => Category( Category copyWith({int id, String description}) => Category(
@ -69,7 +69,7 @@ class Category extends DataClass {
(other is Category && other.id == id && other.description == description); (other is Category && other.id == id && other.description == description);
} }
class CategoriesCompanion implements UpdateCompanion<Category> { class CategoriesCompanion extends UpdateCompanion<Category> {
final Value<int> id; final Value<int> id;
final Value<String> description; final Value<String> description;
const CategoriesCompanion({ const CategoriesCompanion({
@ -147,13 +147,13 @@ class $CategoriesTable extends Categories
} }
@override @override
Map<String, Variable> entityToSql(Category d, {bool includeNulls = false}) { Map<String, Variable> entityToSql(CategoriesCompanion d) {
final map = <String, Variable>{}; final map = <String, Variable>{};
if (d.id != null || includeNulls) { if (d.id.present) {
map['id'] = Variable<int, IntType>(d.id); map['id'] = Variable<int, IntType>(d.id.value);
} }
if (d.description != null || includeNulls) { if (d.description.present) {
map['description'] = Variable<String, StringType>(d.description); map['description'] = Variable<String, StringType>(d.description.value);
} }
return map; return map;
} }
@ -164,7 +164,7 @@ class $CategoriesTable extends Categories
} }
} }
class Recipe extends DataClass { class Recipe extends DataClass implements Insertable<Recipe> {
final int id; final int id;
final String title; final String title;
final String instructions; final String instructions;
@ -206,7 +206,7 @@ class Recipe extends DataClass {
} }
@override @override
RecipesCompanion createCompanion(bool nullToAbsent) { T createCompanion<T extends UpdateCompanion<Recipe>>(bool nullToAbsent) {
return RecipesCompanion( return RecipesCompanion(
id: id == null && nullToAbsent ? const Value.absent() : Value.use(id), id: id == null && nullToAbsent ? const Value.absent() : Value.use(id),
title: title == null && nullToAbsent title: title == null && nullToAbsent
@ -218,7 +218,7 @@ class Recipe extends DataClass {
category: category == null && nullToAbsent category: category == null && nullToAbsent
? const Value.absent() ? const Value.absent()
: Value.use(category), : Value.use(category),
); ) as T;
} }
Recipe copyWith({int id, String title, String instructions, int category}) => Recipe copyWith({int id, String title, String instructions, int category}) =>
@ -254,7 +254,7 @@ class Recipe extends DataClass {
other.category == category); other.category == category);
} }
class RecipesCompanion implements UpdateCompanion<Recipe> { class RecipesCompanion extends UpdateCompanion<Recipe> {
final Value<int> id; final Value<int> id;
final Value<String> title; final Value<String> title;
final Value<String> instructions; final Value<String> instructions;
@ -369,19 +369,19 @@ class $RecipesTable extends Recipes with TableInfo<$RecipesTable, Recipe> {
} }
@override @override
Map<String, Variable> entityToSql(Recipe d, {bool includeNulls = false}) { Map<String, Variable> entityToSql(RecipesCompanion d) {
final map = <String, Variable>{}; final map = <String, Variable>{};
if (d.id != null || includeNulls) { if (d.id.present) {
map['id'] = Variable<int, IntType>(d.id); map['id'] = Variable<int, IntType>(d.id.value);
} }
if (d.title != null || includeNulls) { if (d.title.present) {
map['title'] = Variable<String, StringType>(d.title); map['title'] = Variable<String, StringType>(d.title.value);
} }
if (d.instructions != null || includeNulls) { if (d.instructions.present) {
map['instructions'] = Variable<String, StringType>(d.instructions); map['instructions'] = Variable<String, StringType>(d.instructions.value);
} }
if (d.category != null || includeNulls) { if (d.category.present) {
map['category'] = Variable<int, IntType>(d.category); map['category'] = Variable<int, IntType>(d.category.value);
} }
return map; return map;
} }
@ -392,7 +392,7 @@ class $RecipesTable extends Recipes with TableInfo<$RecipesTable, Recipe> {
} }
} }
class Ingredient extends DataClass { class Ingredient extends DataClass implements Insertable<Ingredient> {
final int id; final int id;
final String name; final String name;
final int caloriesPer100g; final int caloriesPer100g;
@ -428,7 +428,7 @@ class Ingredient extends DataClass {
} }
@override @override
IngredientsCompanion createCompanion(bool nullToAbsent) { T createCompanion<T extends UpdateCompanion<Ingredient>>(bool nullToAbsent) {
return IngredientsCompanion( return IngredientsCompanion(
id: id == null && nullToAbsent ? const Value.absent() : Value.use(id), id: id == null && nullToAbsent ? const Value.absent() : Value.use(id),
name: name:
@ -436,7 +436,7 @@ class Ingredient extends DataClass {
caloriesPer100g: caloriesPer100g == null && nullToAbsent caloriesPer100g: caloriesPer100g == null && nullToAbsent
? const Value.absent() ? const Value.absent()
: Value.use(caloriesPer100g), : Value.use(caloriesPer100g),
); ) as T;
} }
Ingredient copyWith({int id, String name, int caloriesPer100g}) => Ingredient( Ingredient copyWith({int id, String name, int caloriesPer100g}) => Ingredient(
@ -466,7 +466,7 @@ class Ingredient extends DataClass {
other.caloriesPer100g == caloriesPer100g); other.caloriesPer100g == caloriesPer100g);
} }
class IngredientsCompanion implements UpdateCompanion<Ingredient> { class IngredientsCompanion extends UpdateCompanion<Ingredient> {
final Value<int> id; final Value<int> id;
final Value<String> name; final Value<String> name;
final Value<int> caloriesPer100g; final Value<int> caloriesPer100g;
@ -566,16 +566,16 @@ class $IngredientsTable extends Ingredients
} }
@override @override
Map<String, Variable> entityToSql(Ingredient d, {bool includeNulls = false}) { Map<String, Variable> entityToSql(IngredientsCompanion d) {
final map = <String, Variable>{}; final map = <String, Variable>{};
if (d.id != null || includeNulls) { if (d.id.present) {
map['id'] = Variable<int, IntType>(d.id); map['id'] = Variable<int, IntType>(d.id.value);
} }
if (d.name != null || includeNulls) { if (d.name.present) {
map['name'] = Variable<String, StringType>(d.name); map['name'] = Variable<String, StringType>(d.name.value);
} }
if (d.caloriesPer100g != null || includeNulls) { if (d.caloriesPer100g.present) {
map['calories'] = Variable<int, IntType>(d.caloriesPer100g); map['calories'] = Variable<int, IntType>(d.caloriesPer100g.value);
} }
return map; return map;
} }
@ -586,7 +586,8 @@ class $IngredientsTable extends Ingredients
} }
} }
class IngredientInRecipe extends DataClass { class IngredientInRecipe extends DataClass
implements Insertable<IngredientInRecipe> {
final int recipe; final int recipe;
final int ingredient; final int ingredient;
final int amountInGrams; final int amountInGrams;
@ -623,7 +624,8 @@ class IngredientInRecipe extends DataClass {
} }
@override @override
IngredientInRecipesCompanion createCompanion(bool nullToAbsent) { T createCompanion<T extends UpdateCompanion<IngredientInRecipe>>(
bool nullToAbsent) {
return IngredientInRecipesCompanion( return IngredientInRecipesCompanion(
recipe: recipe == null && nullToAbsent recipe: recipe == null && nullToAbsent
? const Value.absent() ? const Value.absent()
@ -634,7 +636,7 @@ class IngredientInRecipe extends DataClass {
amountInGrams: amountInGrams == null && nullToAbsent amountInGrams: amountInGrams == null && nullToAbsent
? const Value.absent() ? const Value.absent()
: Value.use(amountInGrams), : Value.use(amountInGrams),
); ) as T;
} }
IngredientInRecipe copyWith( IngredientInRecipe copyWith(
@ -667,8 +669,7 @@ class IngredientInRecipe extends DataClass {
other.amountInGrams == amountInGrams); other.amountInGrams == amountInGrams);
} }
class IngredientInRecipesCompanion class IngredientInRecipesCompanion extends UpdateCompanion<IngredientInRecipe> {
implements UpdateCompanion<IngredientInRecipe> {
final Value<int> recipe; final Value<int> recipe;
final Value<int> ingredient; final Value<int> ingredient;
final Value<int> amountInGrams; final Value<int> amountInGrams;
@ -773,17 +774,16 @@ class $IngredientInRecipesTable extends IngredientInRecipes
} }
@override @override
Map<String, Variable> entityToSql(IngredientInRecipe d, Map<String, Variable> entityToSql(IngredientInRecipesCompanion d) {
{bool includeNulls = false}) {
final map = <String, Variable>{}; final map = <String, Variable>{};
if (d.recipe != null || includeNulls) { if (d.recipe.present) {
map['recipe'] = Variable<int, IntType>(d.recipe); map['recipe'] = Variable<int, IntType>(d.recipe.value);
} }
if (d.ingredient != null || includeNulls) { if (d.ingredient.present) {
map['ingredient'] = Variable<int, IntType>(d.ingredient); map['ingredient'] = Variable<int, IntType>(d.ingredient.value);
} }
if (d.amountInGrams != null || includeNulls) { if (d.amountInGrams.present) {
map['amount'] = Variable<int, IntType>(d.amountInGrams); map['amount'] = Variable<int, IntType>(d.amountInGrams.value);
} }
return map; return map;
} }

View File

@ -3,6 +3,14 @@ import 'dart:convert';
import 'package:meta/meta.dart'; import 'package:meta/meta.dart';
import 'package:moor/moor.dart'; import 'package:moor/moor.dart';
/// Common interface for objects which can be inserted or updated into a
/// database.
@optionalTypeArgs
abstract class Insertable<D extends DataClass> {
/// Used internally by moor.
T createCompanion<T extends UpdateCompanion<D>>(bool nullToAbsent);
}
/// A common supertype for all data classes generated by moor. Data classes are /// A common supertype for all data classes generated by moor. Data classes are
/// immutable structures that represent a single row in a database table. /// immutable structures that represent a single row in a database table.
abstract class DataClass { abstract class DataClass {
@ -26,9 +34,6 @@ abstract class DataClass {
static dynamic parseJson(String jsonString) { static dynamic parseJson(String jsonString) {
return json.decode(jsonString); return json.decode(jsonString);
} }
/// Used internally by moor.
UpdateCompanion createCompanion(bool nullToAbsent);
} }
/// An update companion for a [DataClass] which is used to write data into a /// An update companion for a [DataClass] which is used to write data into a
@ -36,7 +41,9 @@ abstract class DataClass {
/// ///
/// See also: /// See also:
/// - https://github.com/simolus3/moor/issues/25 /// - https://github.com/simolus3/moor/issues/25
abstract class UpdateCompanion<D extends DataClass> { abstract class UpdateCompanion<D extends DataClass> implements Insertable {
const UpdateCompanion();
/// Used internally by moor. /// Used internally by moor.
/// ///
/// Returns true if the column at the position [index] has been explicitly /// Returns true if the column at the position [index] has been explicitly
@ -44,6 +51,11 @@ abstract class UpdateCompanion<D extends DataClass> {
// todo this doesn't need to exist anymore, remove before release and adapt // todo this doesn't need to exist anymore, remove before release and adapt
// moor_generator // moor_generator
bool isValuePresent(int index); bool isValuePresent(int index);
@override
T createCompanion<T extends UpdateCompanion>(bool nullToAbsent) {
return this as T;
}
} }
/// A wrapper around arbitrary data [T] to indicate presence or absence /// A wrapper around arbitrary data [T] to indicate presence or absence

View File

@ -17,7 +17,7 @@ class DeleteStatement<T extends Table, D extends DataClass> extends Query<T, D>
} }
/// Deletes just this entity. May not be used together with [where]. /// Deletes just this entity. May not be used together with [where].
Future<int> delete(D entity) { Future<int> delete(Insertable<D> entity) {
assert( assert(
whereExpr == null, whereExpr == null,
'When deleting an entity, you may not use where(...)' 'When deleting an entity, you may not use where(...)'

View File

@ -26,7 +26,7 @@ class InsertStatement<D extends DataClass> {
/// ///
/// If the table contains an auto-increment column, the generated value will /// If the table contains an auto-increment column, the generated value will
/// be returned. /// be returned.
Future<int> insert(D entity, {bool orReplace = false}) async { Future<int> insert(Insertable<D> entity, {bool orReplace = false}) async {
_validateIntegrity(entity); _validateIntegrity(entity);
final ctx = _createContext(entity, orReplace); final ctx = _createContext(entity, orReplace);
@ -45,7 +45,8 @@ class InsertStatement<D extends DataClass> {
/// When a row with the same primary or unique key already exists in the /// When a row with the same primary or unique key already exists in the
/// database, the insert will fail. Use [orReplace] to replace rows that /// database, the insert will fail. Use [orReplace] to replace rows that
/// already exist. /// already exist.
Future<void> insertAll(List<D> rows, {bool orReplace = false}) async { Future<void> insertAll(List<Insertable<D>> rows,
{bool orReplace = false}) async {
final statements = <String, List<GenerationContext>>{}; final statements = <String, List<GenerationContext>>{};
// Not every insert has the same sql, as fields which are set to null are // Not every insert has the same sql, as fields which are set to null are
@ -78,12 +79,12 @@ class InsertStatement<D extends DataClass> {
/// ///
/// However, if no such row exists, a new row will be written instead. /// However, if no such row exists, a new row will be written instead.
@Deprecated('Use insert with orReplace: true instead') @Deprecated('Use insert with orReplace: true instead')
Future<void> insertOrReplace(D entity) async { Future<void> insertOrReplace(Insertable<D> entity) async {
return await insert(entity, orReplace: true); return await insert(entity, orReplace: true);
} }
GenerationContext _createContext(D entry, bool replace) { GenerationContext _createContext(Insertable<D> entry, bool replace) {
final map = table.entityToSql(entry) final map = table.entityToSql(entry.createCompanion(true))
..removeWhere((_, value) => value == null); ..removeWhere((_, value) => value == null);
final ctx = GenerationContext.fromDb(database); final ctx = GenerationContext.fromDb(database);
@ -111,13 +112,12 @@ class InsertStatement<D extends DataClass> {
return ctx; return ctx;
} }
void _validateIntegrity(D d) { void _validateIntegrity(Insertable<D> d) {
if (d == null) { if (d == null) {
throw InvalidDataException( throw InvalidDataException(
'Cannot writee null row into ${table.$tableName}'); 'Cannot writee null row into ${table.$tableName}');
} }
// todo needs to use d as update companion here table.validateIntegrity(d.createCompanion(true)).throwIfInvalid(d);
table.validateIntegrity(null).throwIfInvalid(d);
} }
} }

View File

@ -120,7 +120,7 @@ mixin SingleTableQueryMixin<T extends Table, D extends DataClass>
/// Applies a [where] statement so that the row with the same primary key as /// Applies a [where] statement so that the row with the same primary key as
/// [d] will be matched. /// [d] will be matched.
void whereSamePrimaryKey(D d) { void whereSamePrimaryKey(Insertable<D> d) {
assert( assert(
table.$primaryKey != null && table.$primaryKey.isNotEmpty, table.$primaryKey != null && table.$primaryKey.isNotEmpty,
'When using Query.whereSamePrimaryKey, which is also called from ' 'When using Query.whereSamePrimaryKey, which is also called from '
@ -136,7 +136,7 @@ mixin SingleTableQueryMixin<T extends Table, D extends DataClass>
final primaryKeys = table.$primaryKey.map((c) => c.$name); final primaryKeys = table.$primaryKey.map((c) => c.$name);
final updatedFields = table.entityToSql(d, includeNulls: true); final updatedFields = table.entityToSql(d.createCompanion(false));
// Extract values of the primary key as they are needed for the where clause // Extract values of the primary key as they are needed for the where clause
final primaryKeyValues = Map.fromEntries(updatedFields.entries final primaryKeyValues = Map.fromEntries(updatedFields.entries
.where((entry) => primaryKeys.contains(entry.key))); .where((entry) => primaryKeys.contains(entry.key)));

View File

@ -55,11 +55,11 @@ class UpdateStatement<T extends Table, D extends DataClass> extends Query<T, D>
/// ///
/// See also: [replace], which does not require [where] statements and /// See also: [replace], which does not require [where] statements and
/// supports setting fields back to null. /// supports setting fields back to null.
Future<int> write(D entity) async { Future<int> write(Insertable<D> entity) async {
// todo needs to use entity as update companion here // todo needs to use entity as update companion here
table.validateIntegrity(null).throwIfInvalid(entity); table.validateIntegrity(null).throwIfInvalid(entity);
_updatedFields = table.entityToSql(entity) _updatedFields = table.entityToSql(entity.createCompanion(true))
..remove((_, value) => value == null); ..remove((_, value) => value == null);
if (_updatedFields.isEmpty) { if (_updatedFields.isEmpty) {
@ -86,13 +86,11 @@ class UpdateStatement<T extends Table, D extends DataClass> extends Query<T, D>
/// null values in the entity. /// null values in the entity.
/// - [InsertStatement.insert] with the `orReplace` parameter, which behaves /// - [InsertStatement.insert] with the `orReplace` parameter, which behaves
/// similar to this method but creates a new row if none exists. /// similar to this method but creates a new row if none exists.
Future<bool> replace(D entity) async { Future<bool> replace(Insertable<D> entity) async {
// We set isInserting to true here although we're in an update. This is // We don't turn nulls to absent values here (as opposed to a regular
// because all the fields from the entity will be written (as opposed to a // update, where only non-null fields will be written).
// regular update, where only non-null fields will be written). If isInserted final companion = entity.createCompanion(false);
// was false, the null fields would not be validated. table.validateIntegrity(companion).throwIfInvalid(entity);
// todo needs to use entity as update companion here
table.validateIntegrity(null).throwIfInvalid(entity);
assert( assert(
whereExpr == null, whereExpr == null,
'When using replace on an update statement, you may not use where(...)' 'When using replace on an update statement, you may not use where(...)'
@ -100,7 +98,7 @@ class UpdateStatement<T extends Table, D extends DataClass> extends Query<T, D>
whereSamePrimaryKey(entity); whereSamePrimaryKey(entity);
_updatedFields = table.entityToSql(entity, includeNulls: true); _updatedFields = table.entityToSql(companion);
final primaryKeys = table.$primaryKey.map((c) => c.$name); final primaryKeys = table.$primaryKey.map((c) => c.$name);
// Don't update the primary key // Don't update the primary key

View File

@ -38,15 +38,11 @@ mixin TableInfo<TableDsl extends Table, D extends DataClass> {
/// that it respects all constraints (nullability, text length, etc.). /// that it respects all constraints (nullability, text length, etc.).
VerificationContext validateIntegrity(covariant UpdateCompanion<D> instance); VerificationContext validateIntegrity(covariant UpdateCompanion<D> instance);
/// Maps the given data class to a [Map] that can be inserted into sql. The /// Maps the given update companion to a [Map] that can be inserted into sql.
/// keys should represent the column name in sql, the values the corresponding /// The keys should represent the column name in sql, the values the
/// values of the field. /// corresponding values of the field. All fields of the [instance] which are
/// /// present will be written, absent fields will be omitted.
/// If [includeNulls] is true, fields of the [D] that are null will be Map<String, Variable> entityToSql(covariant UpdateCompanion<D> instance);
/// written as a [Variable] with a value of null. Otherwise, these fields will
/// not be written into the map at all.
// todo migrate to update companions
Map<String, Variable> entityToSql(D instance, {bool includeNulls = false});
/// Maps the given row returned by the database into the fitting data class. /// Maps the given row returned by the database into the fitting data class.
D map(Map<String, dynamic> data, {String tablePrefix}); D map(Map<String, dynamic> data, {String tablePrefix});

View File

@ -7,7 +7,7 @@ part of 'todos.dart';
// ************************************************************************** // **************************************************************************
// ignore_for_file: unnecessary_brace_in_string_interps // ignore_for_file: unnecessary_brace_in_string_interps
class TodoEntry extends DataClass { class TodoEntry extends DataClass implements Insertable<TodoEntry> {
final int id; final int id;
final String title; final String title;
final String content; final String content;
@ -56,7 +56,7 @@ class TodoEntry extends DataClass {
} }
@override @override
TodosTableCompanion createCompanion(bool nullToAbsent) { T createCompanion<T extends UpdateCompanion<TodoEntry>>(bool nullToAbsent) {
return TodosTableCompanion( return TodosTableCompanion(
id: id == null && nullToAbsent ? const Value.absent() : Value.use(id), id: id == null && nullToAbsent ? const Value.absent() : Value.use(id),
title: title == null && nullToAbsent title: title == null && nullToAbsent
@ -71,7 +71,7 @@ class TodoEntry extends DataClass {
category: category == null && nullToAbsent category: category == null && nullToAbsent
? const Value.absent() ? const Value.absent()
: Value.use(category), : Value.use(category),
); ) as T;
} }
TodoEntry copyWith( TodoEntry copyWith(
@ -116,7 +116,7 @@ class TodoEntry extends DataClass {
other.category == category); other.category == category);
} }
class TodosTableCompanion implements UpdateCompanion<TodoEntry> { class TodosTableCompanion extends UpdateCompanion<TodoEntry> {
final Value<int> id; final Value<int> id;
final Value<String> title; final Value<String> title;
final Value<String> content; final Value<String> content;
@ -251,22 +251,22 @@ class $TodosTableTable extends TodosTable
} }
@override @override
Map<String, Variable> entityToSql(TodoEntry d, {bool includeNulls = false}) { Map<String, Variable> entityToSql(TodosTableCompanion d) {
final map = <String, Variable>{}; final map = <String, Variable>{};
if (d.id != null || includeNulls) { if (d.id.present) {
map['id'] = Variable<int, IntType>(d.id); map['id'] = Variable<int, IntType>(d.id.value);
} }
if (d.title != null || includeNulls) { if (d.title.present) {
map['title'] = Variable<String, StringType>(d.title); map['title'] = Variable<String, StringType>(d.title.value);
} }
if (d.content != null || includeNulls) { if (d.content.present) {
map['content'] = Variable<String, StringType>(d.content); map['content'] = Variable<String, StringType>(d.content.value);
} }
if (d.targetDate != null || includeNulls) { if (d.targetDate.present) {
map['target_date'] = Variable<DateTime, DateTimeType>(d.targetDate); map['target_date'] = Variable<DateTime, DateTimeType>(d.targetDate.value);
} }
if (d.category != null || includeNulls) { if (d.category.present) {
map['category'] = Variable<int, IntType>(d.category); map['category'] = Variable<int, IntType>(d.category.value);
} }
return map; return map;
} }
@ -277,7 +277,7 @@ class $TodosTableTable extends TodosTable
} }
} }
class Category extends DataClass { class Category extends DataClass implements Insertable<Category> {
final int id; final int id;
final String description; final String description;
Category({this.id, this.description}); Category({this.id, this.description});
@ -309,13 +309,13 @@ class Category extends DataClass {
} }
@override @override
CategoriesCompanion createCompanion(bool nullToAbsent) { T createCompanion<T extends UpdateCompanion<Category>>(bool nullToAbsent) {
return CategoriesCompanion( return CategoriesCompanion(
id: id == null && nullToAbsent ? const Value.absent() : Value.use(id), id: id == null && nullToAbsent ? const Value.absent() : Value.use(id),
description: description == null && nullToAbsent description: description == null && nullToAbsent
? const Value.absent() ? const Value.absent()
: Value.use(description), : Value.use(description),
); ) as T;
} }
Category copyWith({int id, String description}) => Category( Category copyWith({int id, String description}) => Category(
@ -339,7 +339,7 @@ class Category extends DataClass {
(other is Category && other.id == id && other.description == description); (other is Category && other.id == id && other.description == description);
} }
class CategoriesCompanion implements UpdateCompanion<Category> { class CategoriesCompanion extends UpdateCompanion<Category> {
final Value<int> id; final Value<int> id;
final Value<String> description; final Value<String> description;
const CategoriesCompanion({ const CategoriesCompanion({
@ -414,13 +414,13 @@ class $CategoriesTable extends Categories
} }
@override @override
Map<String, Variable> entityToSql(Category d, {bool includeNulls = false}) { Map<String, Variable> entityToSql(CategoriesCompanion d) {
final map = <String, Variable>{}; final map = <String, Variable>{};
if (d.id != null || includeNulls) { if (d.id.present) {
map['id'] = Variable<int, IntType>(d.id); map['id'] = Variable<int, IntType>(d.id.value);
} }
if (d.description != null || includeNulls) { if (d.description.present) {
map['desc'] = Variable<String, StringType>(d.description); map['desc'] = Variable<String, StringType>(d.description.value);
} }
return map; return map;
} }
@ -431,7 +431,7 @@ class $CategoriesTable extends Categories
} }
} }
class User extends DataClass { class User extends DataClass implements Insertable<User> {
final int id; final int id;
final String name; final String name;
final bool isAwesome; final bool isAwesome;
@ -485,7 +485,7 @@ class User extends DataClass {
} }
@override @override
UsersCompanion createCompanion(bool nullToAbsent) { T createCompanion<T extends UpdateCompanion<User>>(bool nullToAbsent) {
return UsersCompanion( return UsersCompanion(
id: id == null && nullToAbsent ? const Value.absent() : Value.use(id), id: id == null && nullToAbsent ? const Value.absent() : Value.use(id),
name: name:
@ -499,7 +499,7 @@ class User extends DataClass {
creationTime: creationTime == null && nullToAbsent creationTime: creationTime == null && nullToAbsent
? const Value.absent() ? const Value.absent()
: Value.use(creationTime), : Value.use(creationTime),
); ) as T;
} }
User copyWith( User copyWith(
@ -545,7 +545,7 @@ class User extends DataClass {
other.creationTime == creationTime); other.creationTime == creationTime);
} }
class UsersCompanion implements UpdateCompanion<User> { class UsersCompanion extends UpdateCompanion<User> {
final Value<int> id; final Value<int> id;
final Value<String> name; final Value<String> name;
final Value<bool> isAwesome; final Value<bool> isAwesome;
@ -680,22 +680,24 @@ class $UsersTable extends Users with TableInfo<$UsersTable, User> {
} }
@override @override
Map<String, Variable> entityToSql(User d, {bool includeNulls = false}) { Map<String, Variable> entityToSql(UsersCompanion d) {
final map = <String, Variable>{}; final map = <String, Variable>{};
if (d.id != null || includeNulls) { if (d.id.present) {
map['id'] = Variable<int, IntType>(d.id); map['id'] = Variable<int, IntType>(d.id.value);
} }
if (d.name != null || includeNulls) { if (d.name.present) {
map['name'] = Variable<String, StringType>(d.name); map['name'] = Variable<String, StringType>(d.name.value);
} }
if (d.isAwesome != null || includeNulls) { if (d.isAwesome.present) {
map['is_awesome'] = Variable<bool, BoolType>(d.isAwesome); map['is_awesome'] = Variable<bool, BoolType>(d.isAwesome.value);
} }
if (d.profilePicture != null || includeNulls) { if (d.profilePicture.present) {
map['profile_picture'] = Variable<Uint8List, BlobType>(d.profilePicture); map['profile_picture'] =
Variable<Uint8List, BlobType>(d.profilePicture.value);
} }
if (d.creationTime != null || includeNulls) { if (d.creationTime.present) {
map['creation_time'] = Variable<DateTime, DateTimeType>(d.creationTime); map['creation_time'] =
Variable<DateTime, DateTimeType>(d.creationTime.value);
} }
return map; return map;
} }
@ -706,7 +708,7 @@ class $UsersTable extends Users with TableInfo<$UsersTable, User> {
} }
} }
class SharedTodo extends DataClass { class SharedTodo extends DataClass implements Insertable<SharedTodo> {
final int todo; final int todo;
final int user; final int user;
SharedTodo({this.todo, this.user}); SharedTodo({this.todo, this.user});
@ -736,13 +738,13 @@ class SharedTodo extends DataClass {
} }
@override @override
SharedTodosCompanion createCompanion(bool nullToAbsent) { T createCompanion<T extends UpdateCompanion<SharedTodo>>(bool nullToAbsent) {
return SharedTodosCompanion( return SharedTodosCompanion(
todo: todo:
todo == null && nullToAbsent ? const Value.absent() : Value.use(todo), todo == null && nullToAbsent ? const Value.absent() : Value.use(todo),
user: user:
user == null && nullToAbsent ? const Value.absent() : Value.use(user), user == null && nullToAbsent ? const Value.absent() : Value.use(user),
); ) as T;
} }
SharedTodo copyWith({int todo, int user}) => SharedTodo( SharedTodo copyWith({int todo, int user}) => SharedTodo(
@ -766,7 +768,7 @@ class SharedTodo extends DataClass {
(other is SharedTodo && other.todo == todo && other.user == user); (other is SharedTodo && other.todo == todo && other.user == user);
} }
class SharedTodosCompanion implements UpdateCompanion<SharedTodo> { class SharedTodosCompanion extends UpdateCompanion<SharedTodo> {
final Value<int> todo; final Value<int> todo;
final Value<int> user; final Value<int> user;
const SharedTodosCompanion({ const SharedTodosCompanion({
@ -847,13 +849,13 @@ class $SharedTodosTable extends SharedTodos
} }
@override @override
Map<String, Variable> entityToSql(SharedTodo d, {bool includeNulls = false}) { Map<String, Variable> entityToSql(SharedTodosCompanion d) {
final map = <String, Variable>{}; final map = <String, Variable>{};
if (d.todo != null || includeNulls) { if (d.todo.present) {
map['todo'] = Variable<int, IntType>(d.todo); map['todo'] = Variable<int, IntType>(d.todo.value);
} }
if (d.user != null || includeNulls) { if (d.user.present) {
map['user'] = Variable<int, IntType>(d.user); map['user'] = Variable<int, IntType>(d.user.value);
} }
return map; return map;
} }
@ -864,7 +866,8 @@ class $SharedTodosTable extends SharedTodos
} }
} }
class TableWithoutPKData extends DataClass { class TableWithoutPKData extends DataClass
implements Insertable<TableWithoutPKData> {
final int notReallyAnId; final int notReallyAnId;
final double someFloat; final double someFloat;
TableWithoutPKData({this.notReallyAnId, this.someFloat}); TableWithoutPKData({this.notReallyAnId, this.someFloat});
@ -898,7 +901,8 @@ class TableWithoutPKData extends DataClass {
} }
@override @override
TableWithoutPKCompanion createCompanion(bool nullToAbsent) { T createCompanion<T extends UpdateCompanion<TableWithoutPKData>>(
bool nullToAbsent) {
return TableWithoutPKCompanion( return TableWithoutPKCompanion(
notReallyAnId: notReallyAnId == null && nullToAbsent notReallyAnId: notReallyAnId == null && nullToAbsent
? const Value.absent() ? const Value.absent()
@ -906,7 +910,7 @@ class TableWithoutPKData extends DataClass {
someFloat: someFloat == null && nullToAbsent someFloat: someFloat == null && nullToAbsent
? const Value.absent() ? const Value.absent()
: Value.use(someFloat), : Value.use(someFloat),
); ) as T;
} }
TableWithoutPKData copyWith({int notReallyAnId, double someFloat}) => TableWithoutPKData copyWith({int notReallyAnId, double someFloat}) =>
@ -934,7 +938,7 @@ class TableWithoutPKData extends DataClass {
other.someFloat == someFloat); other.someFloat == someFloat);
} }
class TableWithoutPKCompanion implements UpdateCompanion<TableWithoutPKData> { class TableWithoutPKCompanion extends UpdateCompanion<TableWithoutPKData> {
final Value<int> notReallyAnId; final Value<int> notReallyAnId;
final Value<double> someFloat; final Value<double> someFloat;
const TableWithoutPKCompanion({ const TableWithoutPKCompanion({
@ -1019,14 +1023,13 @@ class $TableWithoutPKTable extends TableWithoutPK
} }
@override @override
Map<String, Variable> entityToSql(TableWithoutPKData d, Map<String, Variable> entityToSql(TableWithoutPKCompanion d) {
{bool includeNulls = false}) {
final map = <String, Variable>{}; final map = <String, Variable>{};
if (d.notReallyAnId != null || includeNulls) { if (d.notReallyAnId.present) {
map['not_really_an_id'] = Variable<int, IntType>(d.notReallyAnId); map['not_really_an_id'] = Variable<int, IntType>(d.notReallyAnId.value);
} }
if (d.someFloat != null || includeNulls) { if (d.someFloat.present) {
map['some_float'] = Variable<double, RealType>(d.someFloat); map['some_float'] = Variable<double, RealType>(d.someFloat.value);
} }
return map; return map;
} }

View File

@ -7,7 +7,7 @@ part of 'database.dart';
// ************************************************************************** // **************************************************************************
// ignore_for_file: unnecessary_brace_in_string_interps // ignore_for_file: unnecessary_brace_in_string_interps
class TodoEntry extends DataClass { class TodoEntry extends DataClass implements Insertable<TodoEntry> {
final int id; final int id;
final String content; final String content;
final DateTime targetDate; final DateTime targetDate;
@ -49,6 +49,22 @@ class TodoEntry extends DataClass {
}; };
} }
@override
T createCompanion<T extends UpdateCompanion<TodoEntry>>(bool nullToAbsent) {
return TodosCompanion(
id: id == null && nullToAbsent ? const Value.absent() : Value.use(id),
content: content == null && nullToAbsent
? const Value.absent()
: Value.use(content),
targetDate: targetDate == null && nullToAbsent
? const Value.absent()
: Value.use(targetDate),
category: category == null && nullToAbsent
? const Value.absent()
: Value.use(category),
) as T;
}
TodoEntry copyWith( TodoEntry copyWith(
{int id, String content, DateTime targetDate, int category}) => {int id, String content, DateTime targetDate, int category}) =>
TodoEntry( TodoEntry(
@ -83,6 +99,35 @@ class TodoEntry extends DataClass {
other.category == category); other.category == category);
} }
class TodosCompanion extends UpdateCompanion<TodoEntry> {
final Value<int> id;
final Value<String> content;
final Value<DateTime> targetDate;
final Value<int> category;
const TodosCompanion({
this.id = const Value.absent(),
this.content = const Value.absent(),
this.targetDate = const Value.absent(),
this.category = const Value.absent(),
});
@override
bool isValuePresent(int index) {
switch (index) {
case 0:
return id.present;
case 1:
return content.present;
case 2:
return targetDate.present;
case 3:
return category.present;
default:
throw ArgumentError(
'Hit an invalid state while serializing data. Did you run the build step?');
}
}
}
class $TodosTable extends Todos with TableInfo<$TodosTable, TodoEntry> { class $TodosTable extends Todos with TableInfo<$TodosTable, TodoEntry> {
final GeneratedDatabase _db; final GeneratedDatabase _db;
final String _alias; final String _alias;
@ -138,22 +183,26 @@ class $TodosTable extends Todos with TableInfo<$TodosTable, TodoEntry> {
@override @override
final String actualTableName = 'todos'; final String actualTableName = 'todos';
@override @override
VerificationContext validateIntegrity(TodoEntry instance, bool isInserting) => VerificationContext validateIntegrity(TodosCompanion d) {
VerificationContext() final context = VerificationContext();
..handle( if (d.isValuePresent(0)) {
_idMeta, id.isAcceptableValue(instance.id, isInserting, _idMeta)) context.handle(_idMeta, id.isAcceptableValue(d.id.value, _idMeta));
..handle( }
_contentMeta, if (d.isValuePresent(1)) {
content.isAcceptableValue( context.handle(_contentMeta,
instance.content, isInserting, _contentMeta)) content.isAcceptableValue(d.content.value, _contentMeta));
..handle( }
_targetDateMeta, if (d.isValuePresent(2)) {
targetDate.isAcceptableValue( context.handle(_targetDateMeta,
instance.targetDate, isInserting, _targetDateMeta)) targetDate.isAcceptableValue(d.targetDate.value, _targetDateMeta));
..handle( }
_categoryMeta, if (d.isValuePresent(3)) {
category.isAcceptableValue( context.handle(_categoryMeta,
instance.category, isInserting, _categoryMeta)); category.isAcceptableValue(d.category.value, _categoryMeta));
}
return context;
}
@override @override
Set<GeneratedColumn> get $primaryKey => {id}; Set<GeneratedColumn> get $primaryKey => {id};
@override @override
@ -186,7 +235,7 @@ class $TodosTable extends Todos with TableInfo<$TodosTable, TodoEntry> {
} }
} }
class Category extends DataClass { class Category extends DataClass implements Insertable<Category> {
final int id; final int id;
final String description; final String description;
Category({this.id, this.description}); Category({this.id, this.description});
@ -217,6 +266,16 @@ class Category extends DataClass {
}; };
} }
@override
T createCompanion<T extends UpdateCompanion<Category>>(bool nullToAbsent) {
return CategoriesCompanion(
id: id == null && nullToAbsent ? const Value.absent() : Value.use(id),
description: description == null && nullToAbsent
? const Value.absent()
: Value.use(description),
) as T;
}
Category copyWith({int id, String description}) => Category( Category copyWith({int id, String description}) => Category(
id: id ?? this.id, id: id ?? this.id,
description: description ?? this.description, description: description ?? this.description,
@ -238,6 +297,27 @@ class Category extends DataClass {
(other is Category && other.id == id && other.description == description); (other is Category && other.id == id && other.description == description);
} }
class CategoriesCompanion extends UpdateCompanion<Category> {
final Value<int> id;
final Value<String> description;
const CategoriesCompanion({
this.id = const Value.absent(),
this.description = const Value.absent(),
});
@override
bool isValuePresent(int index) {
switch (index) {
case 0:
return id.present;
case 1:
return description.present;
default:
throw ArgumentError(
'Hit an invalid state while serializing data. Did you run the build step?');
}
}
}
class $CategoriesTable extends Categories class $CategoriesTable extends Categories
with TableInfo<$CategoriesTable, Category> { with TableInfo<$CategoriesTable, Category> {
final GeneratedDatabase _db; final GeneratedDatabase _db;
@ -274,14 +354,18 @@ class $CategoriesTable extends Categories
@override @override
final String actualTableName = 'categories'; final String actualTableName = 'categories';
@override @override
VerificationContext validateIntegrity(Category instance, bool isInserting) => VerificationContext validateIntegrity(CategoriesCompanion d) {
VerificationContext() final context = VerificationContext();
..handle( if (d.isValuePresent(0)) {
_idMeta, id.isAcceptableValue(instance.id, isInserting, _idMeta)) context.handle(_idMeta, id.isAcceptableValue(d.id.value, _idMeta));
..handle( }
_descriptionMeta, if (d.isValuePresent(1)) {
description.isAcceptableValue( context.handle(_descriptionMeta,
instance.description, isInserting, _descriptionMeta)); description.isAcceptableValue(d.description.value, _descriptionMeta));
}
return context;
}
@override @override
Set<GeneratedColumn> get $primaryKey => {id}; Set<GeneratedColumn> get $primaryKey => {id};
@override @override

View File

@ -12,7 +12,8 @@ class DataClassWriter {
DataClassWriter(this.table, this.options); DataClassWriter(this.table, this.options);
void writeInto(StringBuffer buffer) { void writeInto(StringBuffer buffer) {
buffer.write('class ${table.dartTypeName} extends DataClass {\n'); buffer.write(
'class ${table.dartTypeName} extends DataClass implements Insertable<${table.dartTypeName}> {\n');
// write individual fields // write individual fields
for (var column in table.columns) { for (var column in table.columns) {
@ -218,18 +219,19 @@ class DataClassWriter {
} }
void _writeCompanionOverride(StringBuffer buffer) { void _writeCompanionOverride(StringBuffer buffer) {
// UpdateCompanion<D> createCompanion(bool nullToAbsent); // T createCompanion<T extends UpdateCompanion>(bool nullToAbsent)
final companionClass = table.updateCompanionName; final companionClass = table.updateCompanionName;
buffer.write('@override\n$companionClass ' buffer.write('@override\nT createCompanion<T extends UpdateCompanion'
'createCompanion(bool nullToAbsent) {\n' '<${table.dartTypeName}>>('
'return $companionClass('); 'bool nullToAbsent) {\n return $companionClass(');
for (var column in table.columns) { for (var column in table.columns) {
final getter = column.dartGetterName; final getter = column.dartGetterName;
buffer.write('$getter: $getter == null && nullToAbsent ? ' buffer.write('$getter: $getter == null && nullToAbsent ? '
'const Value.absent() : Value.use($getter),'); 'const Value.absent() : Value.use($getter),');
} }
buffer.write(');}\n'); buffer.write(') as T;}\n');
} }
/// Recursively creates the implementation for hashCode of the data class, /// Recursively creates the implementation for hashCode of the data class,

View File

@ -79,16 +79,18 @@ class TableWriter {
} }
void _writeReverseMappingMethod(StringBuffer buffer) { void _writeReverseMappingMethod(StringBuffer buffer) {
// Map<String, Variable> entityToSql(User d, {bool includeNulls = false) { // Map<String, Variable> entityToSql(covariant UpdateCompanion<D> instance)
buffer buffer
..write('@override\nMap<String, Variable> entityToSql(' ..write('@override\nMap<String, Variable> entityToSql('
'${table.dartTypeName} d, {bool includeNulls = false}) {\n') '${table.updateCompanionName} d) {\n')
..write('final map = <String, Variable> {};'); ..write('final map = <String, Variable> {};');
for (var column in table.columns) { for (var column in table.columns) {
buffer.write(''' buffer.write('''
if (d.${column.dartGetterName} != null || includeNulls) { if (d.${column.dartGetterName}.present) {
map['${column.name.name}'] = Variable<${column.dartTypeName}, ${column.sqlTypeName}>(d.${column.dartGetterName}); map['${column.name.name}'] =
Variable<${column.dartTypeName}, ${column.sqlTypeName}>(
d.${column.dartGetterName}.value);
} }
'''); ''');
} }

View File

@ -9,7 +9,7 @@ class UpdateCompanionWriter {
void writeInto(StringBuffer buffer) { void writeInto(StringBuffer buffer) {
buffer.write('class ${table.updateCompanionName} ' buffer.write('class ${table.updateCompanionName} '
'implements UpdateCompanion<${table.dartTypeName}> {\n'); 'extends UpdateCompanion<${table.dartTypeName}> {\n');
_writeFields(buffer); _writeFields(buffer);
_writeConstructor(buffer); _writeConstructor(buffer);
_writeIsPresentOverride(buffer); _writeIsPresentOverride(buffer);