Add real datatype for numeric values

This commit is contained in:
Simon Binder 2019-05-12 10:52:02 +02:00
parent f5a1bc7edd
commit b2345a9f28
No known key found for this signature in database
GPG Key ID: B807FDF954BA00CF
12 changed files with 93 additions and 73 deletions

View File

@ -65,8 +65,6 @@ class $CategoriesTable extends Categories
@override
GeneratedIntColumn get id => _id ??= _constructId();
GeneratedIntColumn _constructId() {
var cName = 'id';
if (_alias != null) cName = '$_alias.$cName';
return GeneratedIntColumn('id', $tableName, false, hasAutoIncrement: true);
}
@ -75,8 +73,6 @@ class $CategoriesTable extends Categories
GeneratedTextColumn get description =>
_description ??= _constructDescription();
GeneratedTextColumn _constructDescription() {
var cName = 'description';
if (_alias != null) cName = '$_alias.$cName';
return GeneratedTextColumn(
'description',
$tableName,
@ -201,8 +197,6 @@ class $RecipesTable extends Recipes with TableInfo<$RecipesTable, Recipe> {
@override
GeneratedIntColumn get id => _id ??= _constructId();
GeneratedIntColumn _constructId() {
var cName = 'id';
if (_alias != null) cName = '$_alias.$cName';
return GeneratedIntColumn('id', $tableName, false, hasAutoIncrement: true);
}
@ -210,8 +204,6 @@ class $RecipesTable extends Recipes with TableInfo<$RecipesTable, Recipe> {
@override
GeneratedTextColumn get title => _title ??= _constructTitle();
GeneratedTextColumn _constructTitle() {
var cName = 'title';
if (_alias != null) cName = '$_alias.$cName';
return GeneratedTextColumn('title', $tableName, false, maxTextLength: 16);
}
@ -220,8 +212,6 @@ class $RecipesTable extends Recipes with TableInfo<$RecipesTable, Recipe> {
GeneratedTextColumn get instructions =>
_instructions ??= _constructInstructions();
GeneratedTextColumn _constructInstructions() {
var cName = 'instructions';
if (_alias != null) cName = '$_alias.$cName';
return GeneratedTextColumn(
'instructions',
$tableName,
@ -233,8 +223,6 @@ class $RecipesTable extends Recipes with TableInfo<$RecipesTable, Recipe> {
@override
GeneratedIntColumn get category => _category ??= _constructCategory();
GeneratedIntColumn _constructCategory() {
var cName = 'category';
if (_alias != null) cName = '$_alias.$cName';
return GeneratedIntColumn(
'category',
$tableName,
@ -356,8 +344,6 @@ class $IngredientsTable extends Ingredients
@override
GeneratedIntColumn get id => _id ??= _constructId();
GeneratedIntColumn _constructId() {
var cName = 'id';
if (_alias != null) cName = '$_alias.$cName';
return GeneratedIntColumn('id', $tableName, false, hasAutoIncrement: true);
}
@ -365,8 +351,6 @@ class $IngredientsTable extends Ingredients
@override
GeneratedTextColumn get name => _name ??= _constructName();
GeneratedTextColumn _constructName() {
var cName = 'name';
if (_alias != null) cName = '$_alias.$cName';
return GeneratedTextColumn(
'name',
$tableName,
@ -379,8 +363,6 @@ class $IngredientsTable extends Ingredients
GeneratedIntColumn get caloriesPer100g =>
_caloriesPer100g ??= _constructCaloriesPer100g();
GeneratedIntColumn _constructCaloriesPer100g() {
var cName = 'calories';
if (_alias != null) cName = '$_alias.$cName';
return GeneratedIntColumn(
'calories',
$tableName,
@ -502,8 +484,6 @@ class $IngredientInRecipesTable extends IngredientInRecipes
@override
GeneratedIntColumn get recipe => _recipe ??= _constructRecipe();
GeneratedIntColumn _constructRecipe() {
var cName = 'recipe';
if (_alias != null) cName = '$_alias.$cName';
return GeneratedIntColumn(
'recipe',
$tableName,
@ -515,8 +495,6 @@ class $IngredientInRecipesTable extends IngredientInRecipes
@override
GeneratedIntColumn get ingredient => _ingredient ??= _constructIngredient();
GeneratedIntColumn _constructIngredient() {
var cName = 'ingredient';
if (_alias != null) cName = '$_alias.$cName';
return GeneratedIntColumn(
'ingredient',
$tableName,
@ -529,8 +507,6 @@ class $IngredientInRecipesTable extends IngredientInRecipes
GeneratedIntColumn get amountInGrams =>
_amountInGrams ??= _constructAmountInGrams();
GeneratedIntColumn _constructAmountInGrams() {
var cName = 'amount';
if (_alias != null) cName = '$_alias.$cName';
return GeneratedIntColumn(
'amount',
$tableName,

View File

@ -27,6 +27,9 @@ abstract class DateTimeColumn extends Column<DateTime, DateTimeType> {}
/// A column that stores arbitrary blobs of data as a [Uint8List].
abstract class BlobColumn extends Column<Uint8List, BlobType> {}
/// A column that stores floating point numeric values.
abstract class RealColumn extends Column<num, RealType> {}
/// A column builder is used to specify which columns should appear in a table.
/// All of the methods defined in this class and its subclasses are not meant to
/// be called at runtime. Instead, moor_generator will take a look at your
@ -111,6 +114,9 @@ class BoolColumnBuilder
class BlobColumnBuilder
extends ColumnBuilder<BlobColumnBuilder, BlobColumn, BlobType, Uint8List> {}
class RealColumnBuilder
extends ColumnBuilder<RealColumnBuilder, RealColumn, RealType, num> {}
class TextColumnBuilder
extends ColumnBuilder<TextColumnBuilder, TextColumn, StringType, String> {
/// Puts a constraint on the minimum and maximum length of text that can be

View File

@ -83,10 +83,19 @@ abstract class Table {
/// Use this as the body of a getter to declare a column that holds arbitrary
/// data blobs, stored as an [Uint8List]. Example:
/// ```
/// BlobColumnBuilder get payload => blob()();
/// BlobColumn get payload => blob()();
/// ```
@protected
BlobColumnBuilder blob() => null;
/// Use this as the body of a getter to declare a column that holds floating
/// point numbers. Example
/// ```
/// RealColumn get averageSpeed => real()();
/// ```
/// Note
@protected
RealColumnBuilder real() => null;
}
/// A class to to be used as an annotation on [Table] classes to customize the

View File

@ -36,6 +36,11 @@ class Variable<T, S extends SqlType<T>> extends Expression<T, S> {
return Variable(value);
}
/// Creates a variable that holds the specified floating point value.
static Variable<num, RealType> withReal(num value) {
return Variable(value);
}
/// Maps [value] to something that should be understood by the underlying
/// database engine. For instance, a [DateTime] will me mapped to its unix
/// timestamp.

View File

@ -200,3 +200,12 @@ class GeneratedBlobColumn extends GeneratedColumn<Uint8List, BlobType>
@override
final String typeName = 'BLOB';
}
class GeneratedRealColumn extends GeneratedColumn<num, RealType>
implements RealColumn {
GeneratedRealColumn(String $name, String tableName, bool $nullable)
: super($name, tableName, $nullable);
@override
String get typeName => 'REAL';
}

View File

@ -111,3 +111,14 @@ class BlobType extends SqlType<Uint8List> {
@override
mapToSqlVariable(content) => content;
}
class RealType extends SqlType<num> {
@override
num mapFromDatabaseResponse(response) => response as num;
@override
String mapToSqlConstant(num content) => content.toString();
@override
mapToSqlVariable(num content) => content;
}

View File

@ -48,6 +48,7 @@ class SharedTodos extends Table {
class TableWithoutPK extends Table {
IntColumn get notReallyAnId => integer()();
RealColumn get someFloat => real()();
}
@UseMoor(tables: [TodosTable, Categories, Users, SharedTodos, TableWithoutPK])

View File

@ -103,8 +103,6 @@ class $TodosTableTable extends TodosTable
@override
GeneratedIntColumn get id => _id ??= _constructId();
GeneratedIntColumn _constructId() {
var cName = 'id';
if (_alias != null) cName = '$_alias.$cName';
return GeneratedIntColumn('id', $tableName, false, hasAutoIncrement: true);
}
@ -112,8 +110,6 @@ class $TodosTableTable extends TodosTable
@override
GeneratedTextColumn get title => _title ??= _constructTitle();
GeneratedTextColumn _constructTitle() {
var cName = 'title';
if (_alias != null) cName = '$_alias.$cName';
return GeneratedTextColumn('title', $tableName, true,
minTextLength: 4, maxTextLength: 16);
}
@ -122,8 +118,6 @@ class $TodosTableTable extends TodosTable
@override
GeneratedTextColumn get content => _content ??= _constructContent();
GeneratedTextColumn _constructContent() {
var cName = 'content';
if (_alias != null) cName = '$_alias.$cName';
return GeneratedTextColumn(
'content',
$tableName,
@ -136,8 +130,6 @@ class $TodosTableTable extends TodosTable
GeneratedDateTimeColumn get targetDate =>
_targetDate ??= _constructTargetDate();
GeneratedDateTimeColumn _constructTargetDate() {
var cName = 'target_date';
if (_alias != null) cName = '$_alias.$cName';
return GeneratedDateTimeColumn(
'target_date',
$tableName,
@ -149,8 +141,6 @@ class $TodosTableTable extends TodosTable
@override
GeneratedIntColumn get category => _category ??= _constructCategory();
GeneratedIntColumn _constructCategory() {
var cName = 'category';
if (_alias != null) cName = '$_alias.$cName';
return GeneratedIntColumn(
'category',
$tableName,
@ -267,8 +257,6 @@ class $CategoriesTable extends Categories
@override
GeneratedIntColumn get id => _id ??= _constructId();
GeneratedIntColumn _constructId() {
var cName = 'id';
if (_alias != null) cName = '$_alias.$cName';
return GeneratedIntColumn('id', $tableName, false, hasAutoIncrement: true);
}
@ -277,8 +265,6 @@ class $CategoriesTable extends Categories
GeneratedTextColumn get description =>
_description ??= _constructDescription();
GeneratedTextColumn _constructDescription() {
var cName = 'desc';
if (_alias != null) cName = '$_alias.$cName';
return GeneratedTextColumn('desc', $tableName, false,
$customConstraints: 'NOT NULL UNIQUE');
}
@ -422,8 +408,6 @@ class $UsersTable extends Users with TableInfo<$UsersTable, User> {
@override
GeneratedIntColumn get id => _id ??= _constructId();
GeneratedIntColumn _constructId() {
var cName = 'id';
if (_alias != null) cName = '$_alias.$cName';
return GeneratedIntColumn('id', $tableName, false, hasAutoIncrement: true);
}
@ -431,8 +415,6 @@ class $UsersTable extends Users with TableInfo<$UsersTable, User> {
@override
GeneratedTextColumn get name => _name ??= _constructName();
GeneratedTextColumn _constructName() {
var cName = 'name';
if (_alias != null) cName = '$_alias.$cName';
return GeneratedTextColumn('name', $tableName, false,
minTextLength: 6, maxTextLength: 32);
}
@ -441,8 +423,6 @@ class $UsersTable extends Users with TableInfo<$UsersTable, User> {
@override
GeneratedBoolColumn get isAwesome => _isAwesome ??= _constructIsAwesome();
GeneratedBoolColumn _constructIsAwesome() {
var cName = 'is_awesome';
if (_alias != null) cName = '$_alias.$cName';
return GeneratedBoolColumn('is_awesome', $tableName, false,
defaultValue: const Constant(true));
}
@ -452,8 +432,6 @@ class $UsersTable extends Users with TableInfo<$UsersTable, User> {
GeneratedBlobColumn get profilePicture =>
_profilePicture ??= _constructProfilePicture();
GeneratedBlobColumn _constructProfilePicture() {
var cName = 'profile_picture';
if (_alias != null) cName = '$_alias.$cName';
return GeneratedBlobColumn(
'profile_picture',
$tableName,
@ -466,8 +444,6 @@ class $UsersTable extends Users with TableInfo<$UsersTable, User> {
GeneratedDateTimeColumn get creationTime =>
_creationTime ??= _constructCreationTime();
GeneratedDateTimeColumn _constructCreationTime() {
var cName = 'creation_time';
if (_alias != null) cName = '$_alias.$cName';
return GeneratedDateTimeColumn('creation_time', $tableName, false,
defaultValue: currentDateAndTime);
}
@ -579,8 +555,6 @@ class $SharedTodosTable extends SharedTodos
@override
GeneratedIntColumn get todo => _todo ??= _constructTodo();
GeneratedIntColumn _constructTodo() {
var cName = 'todo';
if (_alias != null) cName = '$_alias.$cName';
return GeneratedIntColumn(
'todo',
$tableName,
@ -592,8 +566,6 @@ class $SharedTodosTable extends SharedTodos
@override
GeneratedIntColumn get user => _user ??= _constructUser();
GeneratedIntColumn _constructUser() {
var cName = 'user';
if (_alias != null) cName = '$_alias.$cName';
return GeneratedIntColumn(
'user',
$tableName,
@ -641,45 +613,57 @@ class $SharedTodosTable extends SharedTodos
class TableWithoutPKData {
final int notReallyAnId;
TableWithoutPKData({this.notReallyAnId});
final num someFloat;
TableWithoutPKData({this.notReallyAnId, this.someFloat});
factory TableWithoutPKData.fromData(
Map<String, dynamic> data, GeneratedDatabase db,
{String prefix}) {
final effectivePrefix = prefix ?? '';
final intType = db.typeSystem.forDartType<int>();
final numType = db.typeSystem.forDartType<num>();
return TableWithoutPKData(
notReallyAnId: intType
.mapFromDatabaseResponse(data['${effectivePrefix}not_really_an_id']),
someFloat:
numType.mapFromDatabaseResponse(data['${effectivePrefix}some_float']),
);
}
factory TableWithoutPKData.fromJson(Map<String, dynamic> json) {
return TableWithoutPKData(
notReallyAnId: json['notReallyAnId'] as int,
someFloat: json['someFloat'] as num,
);
}
Map<String, dynamic> toJson() {
return {
'notReallyAnId': notReallyAnId,
'someFloat': someFloat,
};
}
TableWithoutPKData copyWith({int notReallyAnId}) => TableWithoutPKData(
TableWithoutPKData copyWith({int notReallyAnId, num someFloat}) =>
TableWithoutPKData(
notReallyAnId: notReallyAnId ?? this.notReallyAnId,
someFloat: someFloat ?? this.someFloat,
);
@override
String toString() {
return (StringBuffer('TableWithoutPKData(')
..write('notReallyAnId: $notReallyAnId')
..write('notReallyAnId: $notReallyAnId, ')
..write('someFloat: $someFloat')
..write(')'))
.toString();
}
@override
int get hashCode => $mrjf($mrjc(0, notReallyAnId.hashCode));
int get hashCode =>
$mrjf($mrjc($mrjc(0, notReallyAnId.hashCode), someFloat.hashCode));
@override
bool operator ==(other) =>
identical(this, other) ||
(other is TableWithoutPKData && other.notReallyAnId == notReallyAnId);
(other is TableWithoutPKData &&
other.notReallyAnId == notReallyAnId &&
other.someFloat == someFloat);
}
class $TableWithoutPKTable extends TableWithoutPK
@ -692,8 +676,6 @@ class $TableWithoutPKTable extends TableWithoutPK
GeneratedIntColumn get notReallyAnId =>
_notReallyAnId ??= _constructNotReallyAnId();
GeneratedIntColumn _constructNotReallyAnId() {
var cName = 'not_really_an_id';
if (_alias != null) cName = '$_alias.$cName';
return GeneratedIntColumn(
'not_really_an_id',
$tableName,
@ -701,8 +683,19 @@ class $TableWithoutPKTable extends TableWithoutPK
);
}
GeneratedRealColumn _someFloat;
@override
List<GeneratedColumn> get $columns => [notReallyAnId];
GeneratedRealColumn get someFloat => _someFloat ??= _constructSomeFloat();
GeneratedRealColumn _constructSomeFloat() {
return GeneratedRealColumn(
'some_float',
$tableName,
false,
);
}
@override
List<GeneratedColumn> get $columns => [notReallyAnId, someFloat];
@override
$TableWithoutPKTable get asDslTable => this;
@override
@ -711,7 +704,8 @@ class $TableWithoutPKTable extends TableWithoutPK
final String actualTableName = 'table_without_p_k';
@override
bool validateIntegrity(TableWithoutPKData instance, bool isInserting) =>
notReallyAnId.isAcceptableValue(instance.notReallyAnId, isInserting);
notReallyAnId.isAcceptableValue(instance.notReallyAnId, isInserting) &&
someFloat.isAcceptableValue(instance.someFloat, isInserting);
@override
Set<GeneratedColumn> get $primaryKey => <GeneratedColumn>{};
@override
@ -727,6 +721,9 @@ class $TableWithoutPKTable extends TableWithoutPK
if (d.notReallyAnId != null || includeNulls) {
map['not_really_an_id'] = Variable<int, IntType>(d.notReallyAnId);
}
if (d.someFloat != null || includeNulls) {
map['some_float'] = Variable<num, RealType>(d.someFloat);
}
return map;
}

View File

@ -42,7 +42,10 @@ void main() {
');'));
verify(mockQueryExecutor.call('CREATE TABLE IF NOT EXISTS '
'table_without_p_k (not_really_an_id INTEGER NOT NULL);'));
'table_without_p_k ('
'not_really_an_id INTEGER NOT NULL, '
'some_float REAL NOT NULL'
');'));
});
test('creates individual tables', () async {

View File

@ -3,7 +3,7 @@ import 'package:built_value/built_value.dart';
part 'specified_column.g.dart';
enum ColumnType { integer, text, boolean, datetime, blob }
enum ColumnType { integer, text, boolean, datetime, blob, real }
/// Name of a column. Contains additional info on whether the name was chosen
/// implicitly (based on the dart getter name) or explicitly (via an named())
@ -66,44 +66,48 @@ class SpecifiedColumn {
/// The dart type that matches the values of this column. For instance, if a
/// table has declared an `IntColumn`, the matching dart type name would be [int].
String get dartTypeName => {
String get dartTypeName => const {
ColumnType.boolean: 'bool',
ColumnType.text: 'String',
ColumnType.integer: 'int',
ColumnType.datetime: 'DateTime',
ColumnType.blob: 'Uint8List',
ColumnType.real: 'num',
}[type];
/// The column type from the dsl library. For instance, if a table has
/// declared an `IntColumn`, the matching dsl column name would also be an
/// `IntColumn`.
String get dslColumnTypeName => {
String get dslColumnTypeName => const {
ColumnType.boolean: 'BoolColumn',
ColumnType.text: 'TextColumn',
ColumnType.integer: 'IntColumn',
ColumnType.datetime: 'DateTimeColumn',
ColumnType.blob: 'BlobColumn',
ColumnType.real: 'RealColumn',
}[type];
/// The `GeneratedColumn` class that implements the [dslColumnTypeName].
/// For instance, if a table has declared an `IntColumn`, the matching
/// implementation name would be an `GeneratedIntColumn`.
String get implColumnTypeName => {
String get implColumnTypeName => const {
ColumnType.boolean: 'GeneratedBoolColumn',
ColumnType.text: 'GeneratedTextColumn',
ColumnType.integer: 'GeneratedIntColumn',
ColumnType.datetime: 'GeneratedDateTimeColumn',
ColumnType.blob: 'GeneratedBlobColumn'
ColumnType.blob: 'GeneratedBlobColumn',
ColumnType.real: 'GeneratedRealColumn',
}[type];
/// The class inside the moor library that represents the same sql type as
/// this column.
String get sqlTypeName => {
String get sqlTypeName => const {
ColumnType.boolean: 'BoolType',
ColumnType.text: 'StringType',
ColumnType.integer: 'IntType',
ColumnType.datetime: 'DateTimeType',
ColumnType.blob: 'BlobType',
ColumnType.real: 'RealType',
}[type];
const SpecifiedColumn({

View File

@ -10,9 +10,10 @@ const String startString = 'text';
const String startBool = 'boolean';
const String startDateTime = 'dateTime';
const String startBlob = 'blob';
const String startReal = 'real';
final Set<String> starters =
{startInt, startString, startBool, startDateTime, startBlob};
{startInt, startString, startBool, startDateTime, startBlob, startReal};
const String _methodNamed = 'named';
const String _methodPrimaryKey = 'primaryKey';
@ -172,6 +173,7 @@ class ColumnParser extends ParserBase {
startInt: ColumnType.integer,
startDateTime: ColumnType.datetime,
startBlob: ColumnType.blob,
startReal: ColumnType.real,
}[startMethod];
}
}

View File

@ -118,10 +118,7 @@ class TableWriter {
additionalParams['defaultValue'] = column.defaultArgument.toSource();
}
// Handle aliasing
expressionBuffer
..write("var cName = '${column.name.name}';\n")
..write("if (_alias != null) cName = '\$_alias.\$cName';\n")
// GeneratedIntColumn('sql_name', tableName, isNullable, additionalField: true)
..write('return ${column.implColumnTypeName}')
..write("('${column.name.name}', \$tableName, $isNullable, ");