2019-03-09 07:37:22 -08:00
|
|
|
import 'package:moor/moor.dart';
|
2019-03-06 11:26:04 -08:00
|
|
|
|
2019-03-06 12:43:16 -08:00
|
|
|
part 'example.g.dart';
|
|
|
|
|
2019-03-06 11:26:04 -08:00
|
|
|
// Define tables that can model a database of recipes.
|
|
|
|
|
|
|
|
@DataClassName('Category')
|
|
|
|
class Categories extends Table {
|
|
|
|
IntColumn get id => integer().autoIncrement()();
|
|
|
|
TextColumn get description => text().nullable()();
|
|
|
|
}
|
|
|
|
|
|
|
|
class Recipes extends Table {
|
|
|
|
IntColumn get id => integer().autoIncrement()();
|
|
|
|
TextColumn get title => text().withLength(max: 16)();
|
|
|
|
TextColumn get instructions => text()();
|
|
|
|
IntColumn get category => integer().nullable()();
|
|
|
|
}
|
|
|
|
|
|
|
|
class Ingredients extends Table {
|
|
|
|
IntColumn get id => integer().autoIncrement()();
|
|
|
|
TextColumn get name => text()();
|
|
|
|
IntColumn get caloriesPer100g => integer().named('calories')();
|
|
|
|
}
|
|
|
|
|
|
|
|
class IngredientInRecipes extends Table {
|
|
|
|
@override
|
|
|
|
String get tableName => 'recipe_ingredients';
|
|
|
|
|
|
|
|
// We can also specify custom primary keys
|
|
|
|
@override
|
|
|
|
Set<Column> get primaryKey => {recipe, ingredient};
|
|
|
|
|
2019-03-06 12:43:16 -08:00
|
|
|
IntColumn get recipe => integer()();
|
|
|
|
IntColumn get ingredient => integer()();
|
2019-03-06 11:26:04 -08:00
|
|
|
|
|
|
|
IntColumn get amountInGrams => integer().named('amount')();
|
|
|
|
}
|
2019-03-06 12:43:16 -08:00
|
|
|
|
2019-08-19 10:04:15 -07:00
|
|
|
@UseMoor(
|
|
|
|
tables: [Categories, Recipes, Ingredients, IngredientInRecipes],
|
|
|
|
queries: {
|
|
|
|
// query to load the total weight for each recipe by loading all ingredients
|
|
|
|
// and taking the sum of their amountInGrams.
|
|
|
|
'_totalWeight': '''
|
|
|
|
SELECT r.title, SUM(ir.amount) AS total_weight
|
|
|
|
FROM recipes r
|
|
|
|
INNER JOIN recipe_ingredients ir ON ir.recipe = r.id
|
|
|
|
GROUP BY r.id
|
|
|
|
'''
|
|
|
|
},
|
|
|
|
)
|
2019-03-06 12:43:16 -08:00
|
|
|
class Database extends _$Database {
|
|
|
|
Database(QueryExecutor e) : super(e);
|
|
|
|
|
|
|
|
@override
|
|
|
|
int get schemaVersion => 1;
|
|
|
|
|
|
|
|
@override
|
2019-06-22 10:02:25 -07:00
|
|
|
MigrationStrategy get migration {
|
|
|
|
return MigrationStrategy(
|
|
|
|
beforeOpen: (engine, details) async {
|
2019-03-06 12:43:16 -08:00
|
|
|
// populate data
|
2019-06-22 10:02:25 -07:00
|
|
|
await engine
|
|
|
|
.into(categories)
|
2019-06-21 11:29:42 -07:00
|
|
|
.insert(const CategoriesCompanion(description: Value('Sweets')));
|
2019-06-22 10:02:25 -07:00
|
|
|
},
|
|
|
|
);
|
|
|
|
}
|
2019-03-06 12:43:16 -08:00
|
|
|
}
|