Use a single generated column implementation

This commit is contained in:
Simon Binder 2021-06-19 16:31:08 +02:00
parent 77e2764a46
commit f3360d06a6
No known key found for this signature in database
GPG Key ID: 7891917E4147B8C0
34 changed files with 724 additions and 1095 deletions

View File

@ -244,68 +244,36 @@ class $UsersTable extends Users with TableInfo<$UsersTable, User> {
final String? _alias;
$UsersTable(this._db, [this._alias]);
final VerificationMeta _idMeta = const VerificationMeta('id');
@override
late final GeneratedIntColumn id = _constructId();
GeneratedIntColumn _constructId() {
return GeneratedIntColumn('id', $tableName, false,
hasAutoIncrement: true, declaredAsPrimaryKey: true);
}
late final GeneratedColumn<int?> id = GeneratedColumn<int?>(
'id', aliasedName, false,
typeName: 'INTEGER',
requiredDuringInsert: false,
defaultConstraints: 'PRIMARY KEY AUTOINCREMENT');
final VerificationMeta _nameMeta = const VerificationMeta('name');
@override
late final GeneratedTextColumn name = _constructName();
GeneratedTextColumn _constructName() {
return GeneratedTextColumn(
'name',
$tableName,
false,
);
}
late final GeneratedColumn<String?> name = GeneratedColumn<String?>(
'name', aliasedName, false,
typeName: 'TEXT', requiredDuringInsert: true);
final VerificationMeta _birthDateMeta = const VerificationMeta('birthDate');
@override
late final GeneratedDateTimeColumn birthDate = _constructBirthDate();
GeneratedDateTimeColumn _constructBirthDate() {
return GeneratedDateTimeColumn(
'birth_date',
$tableName,
false,
);
}
late final GeneratedColumn<DateTime?> birthDate = GeneratedColumn<DateTime?>(
'birth_date', aliasedName, false,
typeName: 'INTEGER', requiredDuringInsert: true);
final VerificationMeta _profilePictureMeta =
const VerificationMeta('profilePicture');
@override
late final GeneratedBlobColumn profilePicture = _constructProfilePicture();
GeneratedBlobColumn _constructProfilePicture() {
return GeneratedBlobColumn(
'profile_picture',
$tableName,
true,
);
}
late final GeneratedColumn<Uint8List?> profilePicture =
GeneratedColumn<Uint8List?>('profile_picture', aliasedName, true,
typeName: 'BLOB', requiredDuringInsert: false);
final VerificationMeta _preferencesMeta =
const VerificationMeta('preferences');
@override
late final GeneratedTextColumn preferences = _constructPreferences();
GeneratedTextColumn _constructPreferences() {
return GeneratedTextColumn(
'preferences',
$tableName,
true,
);
}
late final GeneratedColumn<String?> preferences = GeneratedColumn<String?>(
'preferences', aliasedName, true,
typeName: 'TEXT', requiredDuringInsert: false);
@override
List<GeneratedColumn> get $columns =>
[id, name, birthDate, profilePicture, preferences];
@override
$UsersTable get asDslTable => this;
String get aliasedName => _alias ?? 'users';
@override
String get $tableName => _alias ?? 'users';
@override
final String actualTableName = 'users';
String get actualTableName => 'users';
@override
VerificationContext validateIntegrity(Insertable<User> instance,
{bool isInserting = false}) {
@ -340,8 +308,8 @@ class $UsersTable extends Users with TableInfo<$UsersTable, User> {
Set<GeneratedColumn> get $primaryKey => {id};
@override
User map(Map<String, dynamic> data, {String? tablePrefix}) {
final effectivePrefix = tablePrefix != null ? '$tablePrefix.' : null;
return User.fromData(data, _db, prefix: effectivePrefix);
return User.fromData(data, _db,
prefix: tablePrefix != null ? '$tablePrefix.' : null);
}
@override
@ -508,46 +476,28 @@ class $FriendshipsTable extends Friendships
final String? _alias;
$FriendshipsTable(this._db, [this._alias]);
final VerificationMeta _firstUserMeta = const VerificationMeta('firstUser');
@override
late final GeneratedIntColumn firstUser = _constructFirstUser();
GeneratedIntColumn _constructFirstUser() {
return GeneratedIntColumn(
'first_user',
$tableName,
false,
);
}
late final GeneratedColumn<int?> firstUser = GeneratedColumn<int?>(
'first_user', aliasedName, false,
typeName: 'INTEGER', requiredDuringInsert: true);
final VerificationMeta _secondUserMeta = const VerificationMeta('secondUser');
@override
late final GeneratedIntColumn secondUser = _constructSecondUser();
GeneratedIntColumn _constructSecondUser() {
return GeneratedIntColumn(
'second_user',
$tableName,
false,
);
}
late final GeneratedColumn<int?> secondUser = GeneratedColumn<int?>(
'second_user', aliasedName, false,
typeName: 'INTEGER', requiredDuringInsert: true);
final VerificationMeta _reallyGoodFriendsMeta =
const VerificationMeta('reallyGoodFriends');
@override
late final GeneratedBoolColumn reallyGoodFriends =
_constructReallyGoodFriends();
GeneratedBoolColumn _constructReallyGoodFriends() {
return GeneratedBoolColumn('really_good_friends', $tableName, false,
defaultValue: const Constant(false));
}
late final GeneratedColumn<bool?> reallyGoodFriends = GeneratedColumn<bool?>(
'really_good_friends', aliasedName, false,
typeName: 'INTEGER',
requiredDuringInsert: false,
defaultConstraints: 'CHECK (really_good_friends IN (0, 1))',
defaultValue: const Constant(false));
@override
List<GeneratedColumn> get $columns =>
[firstUser, secondUser, reallyGoodFriends];
@override
$FriendshipsTable get asDslTable => this;
String get aliasedName => _alias ?? 'friendships';
@override
String get $tableName => _alias ?? 'friendships';
@override
final String actualTableName = 'friendships';
String get actualTableName => 'friendships';
@override
VerificationContext validateIntegrity(Insertable<Friendship> instance,
{bool isInserting = false}) {
@ -580,8 +530,8 @@ class $FriendshipsTable extends Friendships
Set<GeneratedColumn> get $primaryKey => {firstUser, secondUser};
@override
Friendship map(Map<String, dynamic> data, {String? tablePrefix}) {
final effectivePrefix = tablePrefix != null ? '$tablePrefix.' : null;
return Friendship.fromData(data, _db, prefix: effectivePrefix);
return Friendship.fromData(data, _db,
prefix: tablePrefix != null ? '$tablePrefix.' : null);
}
@override

View File

@ -129,21 +129,17 @@ class $UsersTable extends Users with TableInfo<$UsersTable, User> {
final String? _alias;
$UsersTable(this._db, [this._alias]);
final VerificationMeta _idMeta = const VerificationMeta('id');
@override
late final GeneratedIntColumn id = _constructId();
GeneratedIntColumn _constructId() {
return GeneratedIntColumn('id', aliasedName, false,
hasAutoIncrement: true, declaredAsPrimaryKey: true);
}
late final GeneratedColumn<int?> id = GeneratedColumn<int?>(
'id', aliasedName, false,
typeName: 'INTEGER',
requiredDuringInsert: false,
defaultConstraints: 'PRIMARY KEY AUTOINCREMENT');
final VerificationMeta _nameMeta = const VerificationMeta('name');
@override
late final GeneratedTextColumn name = _constructName();
GeneratedTextColumn _constructName() {
return GeneratedTextColumn('name', aliasedName, false,
defaultValue: const Constant('name'));
}
late final GeneratedColumn<String?> name = GeneratedColumn<String?>(
'name', aliasedName, false,
typeName: 'TEXT',
requiredDuringInsert: false,
defaultValue: const Constant('name'));
@override
List<GeneratedColumn> get $columns => [id, name];
@override
@ -357,34 +353,30 @@ class Groups extends Table with TableInfo<Groups, Group> {
final String? _alias;
Groups(this._db, [this._alias]);
final VerificationMeta _idMeta = const VerificationMeta('id');
late final GeneratedIntColumn id = _constructId();
GeneratedIntColumn _constructId() {
return GeneratedIntColumn('id', aliasedName, false,
$customConstraints: 'NOT NULL');
}
late final GeneratedColumn<int?> id = GeneratedColumn<int?>(
'id', aliasedName, false,
typeName: 'INTEGER',
requiredDuringInsert: false,
$customConstraints: 'NOT NULL');
final VerificationMeta _titleMeta = const VerificationMeta('title');
late final GeneratedTextColumn title = _constructTitle();
GeneratedTextColumn _constructTitle() {
return GeneratedTextColumn('title', aliasedName, false,
$customConstraints: 'NOT NULL');
}
late final GeneratedColumn<String?> title = GeneratedColumn<String?>(
'title', aliasedName, false,
typeName: 'TEXT',
requiredDuringInsert: true,
$customConstraints: 'NOT NULL');
final VerificationMeta _deletedMeta = const VerificationMeta('deleted');
late final GeneratedBoolColumn deleted = _constructDeleted();
GeneratedBoolColumn _constructDeleted() {
return GeneratedBoolColumn('deleted', aliasedName, true,
$customConstraints: 'DEFAULT FALSE',
defaultValue: const CustomExpression<bool>('FALSE'));
}
late final GeneratedColumn<bool?> deleted = GeneratedColumn<bool?>(
'deleted', aliasedName, true,
typeName: 'INTEGER',
requiredDuringInsert: false,
$customConstraints: 'DEFAULT FALSE',
defaultValue: const CustomExpression<bool>('FALSE'));
final VerificationMeta _ownerMeta = const VerificationMeta('owner');
late final GeneratedIntColumn owner = _constructOwner();
GeneratedIntColumn _constructOwner() {
return GeneratedIntColumn('owner', aliasedName, false,
$customConstraints: 'NOT NULL REFERENCES users (id)');
}
late final GeneratedColumn<int?> owner = GeneratedColumn<int?>(
'owner', aliasedName, false,
typeName: 'INTEGER',
requiredDuringInsert: true,
$customConstraints: 'NOT NULL REFERENCES users (id)');
@override
List<GeneratedColumn> get $columns => [id, title, deleted, owner];
@override

View File

@ -129,27 +129,23 @@ class Entries extends Table with TableInfo<Entries, Entrie> {
final String? _alias;
Entries(this._db, [this._alias]);
final VerificationMeta _idMeta = const VerificationMeta('id');
late final GeneratedIntColumn id = _constructId();
GeneratedIntColumn _constructId() {
return GeneratedIntColumn('id', $tableName, false,
declaredAsPrimaryKey: true, $customConstraints: 'PRIMARY KEY');
}
late final GeneratedColumn<int?> id = GeneratedColumn<int?>(
'id', aliasedName, false,
typeName: 'INTEGER',
requiredDuringInsert: false,
$customConstraints: 'PRIMARY KEY');
final VerificationMeta _valueMeta = const VerificationMeta('value');
late final GeneratedTextColumn value = _constructValue();
GeneratedTextColumn _constructValue() {
return GeneratedTextColumn('text', $tableName, false,
$customConstraints: 'NOT NULL');
}
late final GeneratedColumn<String?> value = GeneratedColumn<String?>(
'text', aliasedName, false,
typeName: 'TEXT',
requiredDuringInsert: true,
$customConstraints: 'NOT NULL');
@override
List<GeneratedColumn> get $columns => [id, value];
@override
Entries get asDslTable => this;
String get aliasedName => _alias ?? 'entries';
@override
String get $tableName => _alias ?? 'entries';
@override
final String actualTableName = 'entries';
String get actualTableName => 'entries';
@override
VerificationContext validateIntegrity(Insertable<Entrie> instance,
{bool isInserting = false}) {
@ -171,8 +167,8 @@ class Entries extends Table with TableInfo<Entries, Entrie> {
Set<GeneratedColumn> get $primaryKey => {id};
@override
Entrie map(Map<String, dynamic> data, {String? tablePrefix}) {
final effectivePrefix = tablePrefix != null ? '$tablePrefix.' : null;
return Entrie.fromData(data, _db, prefix: effectivePrefix);
return Entrie.fromData(data, _db,
prefix: tablePrefix != null ? '$tablePrefix.' : null);
}
@override

View File

@ -132,31 +132,25 @@ class Users extends Table with TableInfo<Users, User> {
final String _alias;
Users(this._db, [this._alias]);
final VerificationMeta _idMeta = const VerificationMeta('id');
GeneratedIntColumn _id;
GeneratedIntColumn get id => _id ??= _constructId();
GeneratedIntColumn _constructId() {
return GeneratedIntColumn('id', $tableName, false,
declaredAsPrimaryKey: true,
hasAutoIncrement: true,
$customConstraints: 'NOT NULL PRIMARY KEY AUTOINCREMENT');
}
GeneratedColumn<int> _id;
GeneratedColumn<int> get id =>
_id ??= GeneratedColumn<int>('id', aliasedName, false,
typeName: 'INTEGER',
requiredDuringInsert: false,
$customConstraints: 'NOT NULL PRIMARY KEY AUTOINCREMENT');
final VerificationMeta _nameMeta = const VerificationMeta('name');
GeneratedTextColumn _name;
GeneratedTextColumn get name => _name ??= _constructName();
GeneratedTextColumn _constructName() {
return GeneratedTextColumn('name', $tableName, false,
$customConstraints: 'NOT NULL');
}
GeneratedColumn<String> _name;
GeneratedColumn<String> get name =>
_name ??= GeneratedColumn<String>('name', aliasedName, false,
typeName: 'TEXT',
requiredDuringInsert: true,
$customConstraints: 'NOT NULL');
@override
List<GeneratedColumn> get $columns => [id, name];
@override
Users get asDslTable => this;
String get aliasedName => _alias ?? 'users';
@override
String get $tableName => _alias ?? 'users';
@override
final String actualTableName = 'users';
String get actualTableName => 'users';
@override
VerificationContext validateIntegrity(Insertable<User> instance,
{bool isInserting = false}) {
@ -178,8 +172,8 @@ class Users extends Table with TableInfo<Users, User> {
Set<GeneratedColumn> get $primaryKey => {id};
@override
User map(Map<String, dynamic> data, {String tablePrefix}) {
final effectivePrefix = tablePrefix != null ? '$tablePrefix.' : null;
return User.fromData(data, _db, prefix: effectivePrefix);
return User.fromData(data, _db,
prefix: tablePrefix != null ? '$tablePrefix.' : null);
}
@override

View File

@ -143,25 +143,16 @@ class $CategoriesTable extends Categories
final String? _alias;
$CategoriesTable(this._db, [this._alias]);
final VerificationMeta _idMeta = const VerificationMeta('id');
@override
late final GeneratedIntColumn id = _constructId();
GeneratedIntColumn _constructId() {
return GeneratedIntColumn('id', aliasedName, false,
hasAutoIncrement: true, declaredAsPrimaryKey: true);
}
late final GeneratedColumn<int?> id = GeneratedColumn<int?>(
'id', aliasedName, false,
typeName: 'INTEGER',
requiredDuringInsert: false,
defaultConstraints: 'PRIMARY KEY AUTOINCREMENT');
final VerificationMeta _descriptionMeta =
const VerificationMeta('description');
@override
late final GeneratedTextColumn description = _constructDescription();
GeneratedTextColumn _constructDescription() {
return GeneratedTextColumn(
'description',
aliasedName,
true,
);
}
late final GeneratedColumn<String?> description = GeneratedColumn<String?>(
'description', aliasedName, true,
typeName: 'TEXT', requiredDuringInsert: false);
@override
List<GeneratedColumn> get $columns => [id, description];
@override
@ -386,43 +377,26 @@ class $RecipesTable extends Recipes with TableInfo<$RecipesTable, Recipe> {
final String? _alias;
$RecipesTable(this._db, [this._alias]);
final VerificationMeta _idMeta = const VerificationMeta('id');
@override
late final GeneratedIntColumn id = _constructId();
GeneratedIntColumn _constructId() {
return GeneratedIntColumn('id', aliasedName, false,
hasAutoIncrement: true, declaredAsPrimaryKey: true);
}
late final GeneratedColumn<int?> id = GeneratedColumn<int?>(
'id', aliasedName, false,
typeName: 'INTEGER',
requiredDuringInsert: false,
defaultConstraints: 'PRIMARY KEY AUTOINCREMENT');
final VerificationMeta _titleMeta = const VerificationMeta('title');
@override
late final GeneratedTextColumn title = _constructTitle();
GeneratedTextColumn _constructTitle() {
return GeneratedTextColumn('title', aliasedName, false, maxTextLength: 16);
}
late final GeneratedColumn<String?> title = GeneratedColumn<String?>(
'title', aliasedName, false,
additionalChecks: GeneratedColumn.checkTextLength(maxTextLength: 16),
typeName: 'TEXT',
requiredDuringInsert: true);
final VerificationMeta _instructionsMeta =
const VerificationMeta('instructions');
@override
late final GeneratedTextColumn instructions = _constructInstructions();
GeneratedTextColumn _constructInstructions() {
return GeneratedTextColumn(
'instructions',
aliasedName,
false,
);
}
late final GeneratedColumn<String?> instructions = GeneratedColumn<String?>(
'instructions', aliasedName, false,
typeName: 'TEXT', requiredDuringInsert: true);
final VerificationMeta _categoryMeta = const VerificationMeta('category');
@override
late final GeneratedIntColumn category = _constructCategory();
GeneratedIntColumn _constructCategory() {
return GeneratedIntColumn(
'category',
aliasedName,
true,
);
}
late final GeneratedColumn<int?> category = GeneratedColumn<int?>(
'category', aliasedName, true,
typeName: 'INTEGER', requiredDuringInsert: false);
@override
List<GeneratedColumn> get $columns => [id, title, instructions, category];
@override
@ -627,36 +601,20 @@ class $IngredientsTable extends Ingredients
final String? _alias;
$IngredientsTable(this._db, [this._alias]);
final VerificationMeta _idMeta = const VerificationMeta('id');
@override
late final GeneratedIntColumn id = _constructId();
GeneratedIntColumn _constructId() {
return GeneratedIntColumn('id', aliasedName, false,
hasAutoIncrement: true, declaredAsPrimaryKey: true);
}
late final GeneratedColumn<int?> id = GeneratedColumn<int?>(
'id', aliasedName, false,
typeName: 'INTEGER',
requiredDuringInsert: false,
defaultConstraints: 'PRIMARY KEY AUTOINCREMENT');
final VerificationMeta _nameMeta = const VerificationMeta('name');
@override
late final GeneratedTextColumn name = _constructName();
GeneratedTextColumn _constructName() {
return GeneratedTextColumn(
'name',
aliasedName,
false,
);
}
late final GeneratedColumn<String?> name = GeneratedColumn<String?>(
'name', aliasedName, false,
typeName: 'TEXT', requiredDuringInsert: true);
final VerificationMeta _caloriesPer100gMeta =
const VerificationMeta('caloriesPer100g');
@override
late final GeneratedIntColumn caloriesPer100g = _constructCaloriesPer100g();
GeneratedIntColumn _constructCaloriesPer100g() {
return GeneratedIntColumn(
'calories',
aliasedName,
false,
);
}
late final GeneratedColumn<int?> caloriesPer100g = GeneratedColumn<int?>(
'calories', aliasedName, false,
typeName: 'INTEGER', requiredDuringInsert: true);
@override
List<GeneratedColumn> get $columns => [id, name, caloriesPer100g];
@override
@ -863,39 +821,18 @@ class $IngredientInRecipesTable extends IngredientInRecipes
final String? _alias;
$IngredientInRecipesTable(this._db, [this._alias]);
final VerificationMeta _recipeMeta = const VerificationMeta('recipe');
@override
late final GeneratedIntColumn recipe = _constructRecipe();
GeneratedIntColumn _constructRecipe() {
return GeneratedIntColumn(
'recipe',
aliasedName,
false,
);
}
late final GeneratedColumn<int?> recipe = GeneratedColumn<int?>(
'recipe', aliasedName, false,
typeName: 'INTEGER', requiredDuringInsert: true);
final VerificationMeta _ingredientMeta = const VerificationMeta('ingredient');
@override
late final GeneratedIntColumn ingredient = _constructIngredient();
GeneratedIntColumn _constructIngredient() {
return GeneratedIntColumn(
'ingredient',
aliasedName,
false,
);
}
late final GeneratedColumn<int?> ingredient = GeneratedColumn<int?>(
'ingredient', aliasedName, false,
typeName: 'INTEGER', requiredDuringInsert: true);
final VerificationMeta _amountInGramsMeta =
const VerificationMeta('amountInGrams');
@override
late final GeneratedIntColumn amountInGrams = _constructAmountInGrams();
GeneratedIntColumn _constructAmountInGrams() {
return GeneratedIntColumn(
'amount',
aliasedName,
false,
);
}
late final GeneratedColumn<int?> amountInGrams = GeneratedColumn<int?>(
'amount', aliasedName, false,
typeName: 'INTEGER', requiredDuringInsert: true);
@override
List<GeneratedColumn> get $columns => [recipe, ingredient, amountInGrams];
@override

View File

@ -8,32 +8,34 @@ abstract class Column<T> extends Expression<T> {
}
/// A column that stores int values.
abstract class IntColumn extends Column<int?> {}
typedef IntColumn = Column<int?>;
/// A column that stores boolean values. Booleans will be stored as an integer
/// that can either be 0 (false) or 1 (true).
abstract class BoolColumn extends Column<bool?> {}
typedef BoolColumn = Column<bool?>;
/// A column that stores text.
abstract class TextColumn extends Column<String?> {}
typedef TextColumn = Column<String?>;
/// A column that stores a [DateTime]. Times will be stored as unix timestamp
/// and will thus have a second accuracy.
abstract class DateTimeColumn extends Column<DateTime?> {}
typedef DateTimeColumn = Column<DateTime?>;
/// A column that stores arbitrary blobs of data as a [Uint8List].
abstract class BlobColumn extends Column<Uint8List?> {}
typedef BlobColumn = Column<Uint8List?>;
/// A column that stores floating point numeric values.
abstract class RealColumn extends Column<double?> {}
typedef RealColumn = Column<double?>;
/// 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
/// source code (specifically, it will analyze which of the methods you use) to
/// figure out the column structure of a table.
class ColumnBuilder<Builder, ResultColumn extends Column<ResultDartType>,
ResultDartType> {
class ColumnBuilder<T> {}
/// DSL extension to define a column with moor.
extension BuildColumn<T> on ColumnBuilder<T> {
/// By default, the field name will be used as the column name, e.g.
/// `IntColumn get id = integer()` will have "id" as its associated name.
/// Columns made up of multiple words are expected to be in camelCase and will
@ -45,11 +47,11 @@ class ColumnBuilder<Builder, ResultColumn extends Column<ResultDartType>,
/// Note that using [named] __does not__ have an effect on the json key of an
/// object. To change the json key, annotate this column getter with
/// [JsonKey].
Builder named(String name) => _isGenerated();
ColumnBuilder<T> named(String name) => _isGenerated();
/// Marks this column as nullable. Nullable columns should not appear in a
/// primary key. Columns are non-null by default.
Builder nullable() => _isGenerated();
ColumnBuilder<T?> nullable() => _isGenerated();
/// Tells moor to write a custom constraint after this column definition when
/// writing this column, for instance in a CREATE TABLE statement.
@ -76,7 +78,7 @@ class ColumnBuilder<Builder, ResultColumn extends Column<ResultDartType>,
/// See also:
/// - https://www.sqlite.org/syntax/column-constraint.html
/// - [GeneratedColumn.writeCustomConstraints]
Builder customConstraint(String constraint) => _isGenerated();
ColumnBuilder<T> customConstraint(String constraint) => _isGenerated();
/// The column will use this expression when a row is inserted and no value
/// has been specified.
@ -98,7 +100,7 @@ class ColumnBuilder<Builder, ResultColumn extends Column<ResultDartType>,
/// TABLE statements.
/// - [currentDate] and [currentDateAndTime], which are useful expressions to
/// store the current date/time as a default value.
Builder withDefault(Expression<ResultDartType> e) => _isGenerated();
ColumnBuilder<T> withDefault(Expression<T> e) => _isGenerated();
/// Sets a dynamic default value for this column.
///
@ -125,7 +127,7 @@ class ColumnBuilder<Builder, ResultColumn extends Column<ResultDartType>,
/// [withDefault] instead. [withDefault] will write the default value into the
/// generated `CREATE TABLE` statement. The underlying sql engine will then
/// apply the default value.
Builder clientDefault(ResultDartType Function() onInsert) => _isGenerated();
ColumnBuilder<T> clientDefault(T Function() onInsert) => _isGenerated();
/// Uses a custom [converter] to store custom Dart objects in a single column
/// and automatically mapping them from and to sql.
@ -163,45 +165,29 @@ class ColumnBuilder<Builder, ResultColumn extends Column<ResultDartType>,
/// ```
/// The generated row class will then use a `MyFancyClass` instead of a
/// `String`, which would usually be used for [Table.text] columns.
Builder map<T>(TypeConverter<T, ResultDartType> converter) => _isGenerated();
ColumnBuilder<T> map<Dart>(TypeConverter<Dart, T> converter) =>
_isGenerated();
/// Turns this column builder into a column. This method won't actually be
/// called in your code. Instead, moor_generator will take a look at your
/// source code to figure out your table structure.
ResultColumn call() => _isGenerated();
Column<T> call() => _isGenerated();
}
/// Tells the generator to build an [IntColumn]. See the docs at [ColumnBuilder]
/// for details.
class IntColumnBuilder
extends ColumnBuilder<IntColumnBuilder, IntColumn, int?> {
extension BuildIntColumn<T extends int?> on ColumnBuilder<T> {
/// Enables auto-increment for this column, which will also make this column
/// the primary key of the table.
///
/// For this reason, you can't use an [autoIncrement] column and also set a
/// custom [Table.primaryKey] on the same table.
IntColumnBuilder autoIncrement() => _isGenerated();
ColumnBuilder<T> autoIncrement() => _isGenerated();
}
/// Tells the generator to build an [BoolColumn]. See the docs at
/// [ColumnBuilder] for details.
class BoolColumnBuilder
extends ColumnBuilder<BoolColumnBuilder, BoolColumn, bool?> {}
/// Tells the generator to build an [BlobColumn]. See the docs at
/// [ColumnBuilder] for details.
class BlobColumnBuilder
extends ColumnBuilder<BlobColumnBuilder, BlobColumn, Uint8List?> {}
/// Tells the generator to build an [RealColumn]. See the docs at
/// [ColumnBuilder] for details.
class RealColumnBuilder
extends ColumnBuilder<RealColumnBuilder, RealColumn, num?> {}
/// Tells the generator to build an [TextColumn]. See the docs at
/// [ColumnBuilder] for details.
class TextColumnBuilder
extends ColumnBuilder<TextColumnBuilder, TextColumn, String?> {
extension BuildTextColumn<T extends String?> on ColumnBuilder<T> {
/// Puts a constraint on the minimum and maximum length of text that can be
/// stored in this column.
///
@ -210,14 +196,9 @@ class TextColumnBuilder
/// null and one tries to write a string which [String.length] is
/// _strictly less_ than [min], an exception will be thrown. Similarly, you
/// can't insert strings with a length _strictly greater_ than [max].
TextColumnBuilder withLength({int? min, int? max}) => _isGenerated();
ColumnBuilder<T> withLength({int? min, int? max}) => _isGenerated();
}
/// Tells the generator to build an [DateTimeColumn]. See the docs at
/// [ColumnBuilder] for details.
class DateTimeColumnBuilder
extends ColumnBuilder<DateTimeColumnBuilder, DateTimeColumn, DateTime?> {}
/// Annotation to use on column getters inside of a [Table] to define the name
/// of the column in the json used by [DataClass.toJson].
///

View File

@ -67,7 +67,7 @@ abstract class Table extends HasResultSet {
/// IntColumn get id => integer().autoIncrement()();
/// ```
@protected
IntColumnBuilder integer() => _isGenerated();
ColumnBuilder<int> integer() => _isGenerated();
/// Creates a column to store an `enum` class [T].
///
@ -75,7 +75,7 @@ abstract class Table extends HasResultSet {
/// corresponding to the enum's index. Note that this can invalidate your data
/// if you add another value to the enum class.
@protected
IntColumnBuilder intEnum<T>() => _isGenerated();
ColumnBuilder<int> intEnum<T>() => _isGenerated();
/// Use this as the body of a getter to declare a column that holds strings.
/// Example (inside the body of a table class):
@ -83,7 +83,7 @@ abstract class Table extends HasResultSet {
/// TextColumn get name => text()();
/// ```
@protected
TextColumnBuilder text() => _isGenerated();
ColumnBuilder<String> text() => _isGenerated();
/// Use this as the body of a getter to declare a column that holds bools.
/// Example (inside the body of a table class):
@ -91,7 +91,7 @@ abstract class Table extends HasResultSet {
/// BoolColumn get isAwesome => boolean()();
/// ```
@protected
BoolColumnBuilder boolean() => _isGenerated();
ColumnBuilder<bool> boolean() => _isGenerated();
/// Use this as the body of a getter to declare a column that holds date and
/// time. Note that [DateTime] values are stored on a second-accuracy.
@ -100,7 +100,7 @@ abstract class Table extends HasResultSet {
/// DateTimeColumn get accountCreatedAt => dateTime()();
/// ```
@protected
DateTimeColumnBuilder dateTime() => _isGenerated();
ColumnBuilder<DateTime> dateTime() => _isGenerated();
/// Use this as the body of a getter to declare a column that holds arbitrary
/// data blobs, stored as an [Uint8List]. Example:
@ -108,7 +108,7 @@ abstract class Table extends HasResultSet {
/// BlobColumn get payload => blob()();
/// ```
@protected
BlobColumnBuilder blob() => _isGenerated();
ColumnBuilder<Uint8List> blob() => _isGenerated();
/// Use this as the body of a getter to declare a column that holds floating
/// point numbers. Example
@ -116,7 +116,7 @@ abstract class Table extends HasResultSet {
/// RealColumn get averageSpeed => real()();
/// ```
@protected
RealColumnBuilder real() => _isGenerated();
ColumnBuilder<double> real() => _isGenerated();
}
/// A class to be used as an annotation on [Table] classes to customize the

View File

@ -19,8 +19,12 @@ class CustomExpression<D> extends Expression<D> {
/// mainly used for subqueries used as expressions.
final Iterable<TableInfo> watchedTables;
@override
final Precedence precedence;
/// Constructs a custom expression by providing the raw sql [content].
const CustomExpression(this.content, {this.watchedTables = const []});
const CustomExpression(this.content,
{this.watchedTables = const [], this.precedence = Precedence.unknown});
@override
void writeInto(GenerationContext context) {

View File

@ -237,8 +237,7 @@ class Migrator {
var hasAutoIncrement = false;
for (var i = 0; i < table.$columns.length; i++) {
final column = table.$columns[i];
if (column is GeneratedIntColumn && column.hasAutoIncrement) {
if (column.hasAutoIncrement) {
hasAutoIncrement = true;
}
@ -492,7 +491,8 @@ class TableMigration {
// isRequired returns false if the column has a client default value that
// would be used for inserts. We can't apply the client default here
// though, so it doesn't count as a default value.
final isRequired = column.isRequired || column.clientDefault != null;
final isRequired =
column.requiredDuringInsert || column.clientDefault != null;
if (isRequired && !columnTransformer.containsKey(column)) {
problematicNewColumns.add(column.$name);
}

View File

@ -34,7 +34,7 @@ part 'expressions/null_check.dart';
part 'expressions/text.dart';
part 'expressions/variables.dart';
part 'schema/columns.dart';
part 'schema/column_impl.dart';
part 'schema/entities.dart';
part 'schema/table_info.dart';

View File

@ -0,0 +1,182 @@
part of '../query_builder.dart';
const VerificationResult _invalidNull = VerificationResult.failure(
"This column is not nullable and doesn't have a default value. "
"Null fields thus can't be inserted.");
/// Implementation for a [Column] declared on a table.
class GeneratedColumn<T> extends Column<T> {
/// The sql name of this column.
final String $name;
/// [$name], but escaped if it's an sql keyword.
String get escapedName => escapeIfNeeded($name);
/// The name of the table that contains this column
final String tableName;
/// Whether null values are allowed for this column.
final bool $nullable;
/// Default constraints generated by moor.
final String? _defaultConstraints;
/// Custom constraints that have been specified for this column.
///
/// Some constraints, like `NOT NULL` or checks for booleans, are generated by
/// moor by default.
/// Constraints can also be overridden with [BuildColumn.customConstraints],
/// in which case the moor constraints will not be applied.
final String? $customConstraints;
/// The default expression to be used during inserts when no value has been
/// specified. Can be null if no default value is set.
final Expression<T>? defaultValue;
/// A function that yields a default column for inserts if no value has been
/// set. This is different to [defaultValue] since the function is written in
/// Dart, not SQL. It's a compile-time error to declare columns where both
/// [defaultValue] and [clientDefault] are non-null.
///
/// See also: [BuildColumn.clientDefault].
final T Function()? clientDefault;
/// Additional checks performed on values before inserts or updates.
final VerificationResult Function(T, VerificationMeta)? additionalChecks;
/// The sql type name, such as TEXT for texts.
final String typeName;
/// Whether a value is required for this column when inserting a new row.
final bool requiredDuringInsert;
/// Whether this column has an `AUTOINCREMENT` primary key constraint that was
/// created by moor.
bool get hasAutoIncrement =>
_defaultConstraints?.contains('AUTOINCREMENT') == true;
/// Used by generated code.
GeneratedColumn(
this.$name,
this.tableName,
this.$nullable, {
this.clientDefault,
required this.typeName,
String? defaultConstraints,
this.$customConstraints,
this.defaultValue,
this.additionalChecks,
this.requiredDuringInsert = false,
}) : _defaultConstraints = defaultConstraints;
/// Writes the definition of this column, as defined
/// [here](https://www.sqlite.org/syntax/column-def.html), into the given
/// buffer.
void writeColumnDefinition(GenerationContext into) {
into.buffer.write('$escapedName $typeName');
if ($customConstraints == null) {
into.buffer.write($nullable ? ' NULL' : ' NOT NULL');
final defaultValue = this.defaultValue;
if (defaultValue != null) {
into.buffer.write(' DEFAULT ');
// we need to write brackets if the default value is not a literal.
// see https://www.sqlite.org/syntax/column-constraint.html
final writeBrackets = !defaultValue.isLiteral;
if (writeBrackets) into.buffer.write('(');
defaultValue.writeInto(into);
if (writeBrackets) into.buffer.write(')');
}
// these custom constraints refer to builtin constraints from moor
if (_defaultConstraints != null) {
into.buffer..write(' ')..write(_defaultConstraints);
}
} else if ($customConstraints?.isNotEmpty == true) {
into.buffer..write(' ')..write($customConstraints);
}
}
@override
void writeInto(GenerationContext context, {bool ignoreEscape = false}) {
if (context.hasMultipleTables) {
context.buffer..write(tableName)..write('.');
}
context.buffer.write(ignoreEscape ? $name : escapedName);
}
/// Checks whether the given value fits into this column. The default
/// implementation only checks for nullability, but subclasses might enforce
/// additional checks. For instance, a text column might verify that a text
/// has a certain length.
///
/// Note: The behavior of this method was changed in moor 1.5. Before, null
/// values were interpreted as an absent value during updates or if the
/// [defaultValue] is set. Verification was skipped for absent values.
/// This is no longer the case, all null values are assumed to be an sql
/// `NULL`.
VerificationResult isAcceptableValue(T value, VerificationMeta meta) {
final nullOk = $nullable;
if (!nullOk && value == null) {
return _invalidNull;
} else {
return additionalChecks?.call(value, meta) ??
const VerificationResult.success();
}
}
/// A more general version of [isAcceptableValue] that supports any sql
/// expression.
///
/// The default implementation will not perform any check if [value] is not
/// a [Variable].
VerificationResult isAcceptableOrUnknown(
Expression value, VerificationMeta meta) {
if (value is Variable) {
return isAcceptableValue(value.value as T, meta);
} else {
return const VerificationResult.success();
}
}
@override
int get hashCode => $mrjf($mrjc(tableName.hashCode, $name.hashCode));
@override
bool operator ==(dynamic other) {
if (other.runtimeType != runtimeType) return false;
// ignore: test_types_in_equals
final typedOther = other as GeneratedColumn;
return typedOther.tableName == tableName && typedOther.$name == $name;
}
Variable _evaluateClientDefault() {
return Variable<T>(clientDefault!());
}
/// A value for [additionalChecks] validating allowed text lengths.
///
/// Used by generated code.
static VerificationResult Function(String?, VerificationMeta) checkTextLength(
{int? minTextLength, int? maxTextLength}) {
return (value, meta) {
if (value == null) return const VerificationResult.success();
final length = value.length;
if (minTextLength != null && minTextLength > length) {
return VerificationResult.failure(
'Must at least be $minTextLength characters long.');
}
if (maxTextLength != null && maxTextLength < length) {
return VerificationResult.failure(
'Must at most be $maxTextLength characters long.');
}
return const VerificationResult.success();
};
}
}

View File

@ -1,296 +0,0 @@
part of '../query_builder.dart';
const VerificationResult _invalidNull = VerificationResult.failure(
"This column is not nullable and doesn't have a default value. "
"Null fields thus can't be inserted.");
/// Base class for the implementation of [Column].
abstract class GeneratedColumn<T> extends Column<T> {
/// The sql name of this column.
final String $name;
/// [$name], but escaped if it's an sql keyword.
String get escapedName => escapeIfNeeded($name);
/// The name of the table that contains this column
final String tableName;
/// Whether null values are allowed for this column.
final bool $nullable;
/// If custom constraints have been specified for this column via
/// [ColumnBuilder.customConstraint], these are kept here. Otherwise, this
/// field is going to be null.
final String? $customConstraints;
/// The default expression to be used during inserts when no value has been
/// specified. Can be null if no default value is set.
final Expression<T>? defaultValue;
/// A function that yields a default column for inserts if no value has been
/// set. This is different to [defaultValue] since the function is written in
/// Dart, not SQL. It's a compile-time error to declare columns where both
/// [defaultValue] and [clientDefault] are non-null.
///
/// See also: [ColumnBuilder.clientDefault].
T Function()? clientDefault;
/// Used by generated code.
GeneratedColumn(this.$name, this.tableName, this.$nullable,
{this.$customConstraints, this.defaultValue});
/// Writes the definition of this column, as defined
/// [here](https://www.sqlite.org/syntax/column-def.html), into the given
/// buffer.
void writeColumnDefinition(GenerationContext into) {
into.buffer.write('$escapedName $typeName');
if ($customConstraints == null) {
into.buffer.write($nullable ? ' NULL' : ' NOT NULL');
final defaultValue = this.defaultValue;
if (defaultValue != null) {
into.buffer.write(' DEFAULT ');
// we need to write brackets if the default value is not a literal.
// see https://www.sqlite.org/syntax/column-constraint.html
final writeBrackets = !defaultValue.isLiteral;
if (writeBrackets) into.buffer.write('(');
defaultValue.writeInto(into);
if (writeBrackets) into.buffer.write(')');
}
// these custom constraints refer to builtin constraints from moor
writeCustomConstraints(into.buffer);
} else if ($customConstraints?.isNotEmpty == true) {
into.buffer..write(' ')..write($customConstraints);
}
}
/// Writes custom constraints that are supported by the Dart api from moor
/// (e.g. a `CHECK` for bool columns to ensure that the value is indeed either
/// 0 or 1).
@visibleForOverriding
void writeCustomConstraints(StringBuffer into) {}
/// The sql type name, such as TEXT for texts.
@visibleForOverriding
String get typeName;
@override
void writeInto(GenerationContext context, {bool ignoreEscape = false}) {
if (context.hasMultipleTables) {
context.buffer..write(tableName)..write('.');
}
context.buffer.write(ignoreEscape ? $name : escapedName);
}
/// Checks whether the given value fits into this column. The default
/// implementation only checks for nullability, but subclasses might enforce
/// additional checks. For instance, the [GeneratedTextColumn] can verify
/// that a text has a certain length.
///
/// Note: The behavior of this method was changed in moor 1.5. Before, null
/// values were interpreted as an absent value during updates or if the
/// [defaultValue] is set. Verification was skipped for absent values.
/// This is no longer the case, all null values are assumed to be an sql
/// `NULL`.
VerificationResult isAcceptableValue(T value, VerificationMeta meta) {
final nullOk = $nullable;
if (!nullOk && value == null) {
return _invalidNull;
} else {
return const VerificationResult.success();
}
}
/// A more general version of [isAcceptableValue] that supports any sql
/// expression.
///
/// The default implementation will not perform any check if [value] is not
/// a [Variable].
VerificationResult isAcceptableOrUnknown(
Expression value, VerificationMeta meta) {
if (value is Variable) {
return isAcceptableValue(value.value as T, meta);
} else {
return const VerificationResult.success();
}
}
/// Returns true if this column needs to be set when writing a new row into
/// a table.
bool get isRequired {
return !$nullable && defaultValue == null && clientDefault == null;
}
@override
int get hashCode => $mrjf($mrjc(tableName.hashCode, $name.hashCode));
@override
bool operator ==(dynamic other) {
if (other.runtimeType != runtimeType) return false;
// ignore: test_types_in_equals
final typedOther = other as GeneratedColumn;
return typedOther.tableName == tableName && typedOther.$name == $name;
}
Variable _evaluateClientDefault() {
return Variable<T>(clientDefault!());
}
}
/// Implementation for [TextColumn].
class GeneratedTextColumn extends GeneratedColumn<String?>
implements TextColumn {
/// Optional. The minimum text length.
final int? minTextLength;
/// Optional. The maximum text length.
final int? maxTextLength;
/// Used by generated code.
GeneratedTextColumn(
String name,
String tableName,
bool nullable, {
this.minTextLength,
this.maxTextLength,
String? $customConstraints,
Expression<String?>? defaultValue,
}) : super(name, tableName, nullable,
$customConstraints: $customConstraints, defaultValue: defaultValue);
@override
final String typeName = 'TEXT';
@override
VerificationResult isAcceptableValue(String? value, VerificationMeta meta) {
// handle nullability check in common column
if (value == null) return super.isAcceptableValue(null, meta);
final length = value.length;
if (minTextLength != null && minTextLength! > length) {
return VerificationResult.failure(
'Must at least be $minTextLength characters long.');
}
if (maxTextLength != null && maxTextLength! < length) {
return VerificationResult.failure(
'Must at most be $maxTextLength characters long.');
}
return const VerificationResult.success();
}
}
/// Implementation for [BoolColumn].
class GeneratedBoolColumn extends GeneratedColumn<bool?> implements BoolColumn {
/// Used by generated code
GeneratedBoolColumn(String name, String tableName, bool nullable,
{String? $customConstraints, Expression<bool?>? defaultValue})
: super(name, tableName, nullable,
$customConstraints: $customConstraints, defaultValue: defaultValue);
@override
final String typeName = 'INTEGER';
@override
void writeCustomConstraints(StringBuffer into) {
into.write(' CHECK ($escapedName in (0, 1))');
}
}
/// Implementation for [IntColumn]
class GeneratedIntColumn extends GeneratedColumn<int?> implements IntColumn {
/// Whether this column was declared to be a primary key via a column
/// constraint. The only way to do this in Dart is with
/// [IntColumnBuilder.autoIncrement]. In `.moor` files, declaring a column
/// to be `INTEGER NOT NULL PRIMARY KEY` will set this flag but not
/// [hasAutoIncrement]. If either field is enabled, this column will be an
/// alias for the rowid.
final bool declaredAsPrimaryKey;
/// Whether this column was declared to be an `AUTOINCREMENT` column, either
/// with [IntColumnBuilder.autoIncrement] or with an `AUTOINCREMENT` clause
/// in a `.moor` file.
final bool hasAutoIncrement;
@override
final String typeName = 'INTEGER';
/// Used by generated code.
GeneratedIntColumn(
String name,
String tableName,
bool nullable, {
this.declaredAsPrimaryKey = false,
this.hasAutoIncrement = false,
String? $customConstraints,
Expression<int?>? defaultValue,
}) : super(name, tableName, nullable,
$customConstraints: $customConstraints, defaultValue: defaultValue);
@override
void writeCustomConstraints(StringBuffer into) {
if (hasAutoIncrement) {
into.write(' PRIMARY KEY AUTOINCREMENT');
} else if (declaredAsPrimaryKey) {
into.write(' PRIMARY KEY');
}
}
@override
bool get isRequired {
final aliasForRowId = declaredAsPrimaryKey || hasAutoIncrement;
return !aliasForRowId && super.isRequired;
}
}
/// Implementation for [DateTimeColumn].
class GeneratedDateTimeColumn extends GeneratedColumn<DateTime?>
implements DateTimeColumn {
/// Used by generated code.
GeneratedDateTimeColumn(
String $name,
String tableName,
bool $nullable, {
String? $customConstraints,
Expression<DateTime?>? defaultValue,
}) : super($name, tableName, $nullable,
$customConstraints: $customConstraints, defaultValue: defaultValue);
@override
String get typeName => 'INTEGER'; // date-times are stored as unix-timestamps
}
/// Implementation for [BlobColumn]
class GeneratedBlobColumn extends GeneratedColumn<Uint8List?>
implements BlobColumn {
/// Used by generated code.
GeneratedBlobColumn(String $name, String tableName, bool $nullable,
{String? $customConstraints, Expression<Uint8List?>? defaultValue})
: super($name, tableName, $nullable,
$customConstraints: $customConstraints, defaultValue: defaultValue);
@override
final String typeName = 'BLOB';
}
/// Implementation for [RealColumn]
class GeneratedRealColumn extends GeneratedColumn<double?>
implements RealColumn {
/// Used by generated code
GeneratedRealColumn(
String $name,
String tableName,
bool $nullable, {
Expression<double>? defaultValue,
String? $customConstraints,
}) : super($name, tableName, $nullable,
defaultValue: defaultValue, $customConstraints: $customConstraints);
@override
String get typeName => 'REAL';
}

View File

@ -6,7 +6,7 @@ part of 'sql_types.dart';
/// Moor currently supports [DateTime], [double], [int], [Uint8List], [bool]
/// and [String] for [S].
///
/// Also see [ColumnBuilder.map] for details.
/// Also see [BuildColumn.map] for details.
abstract class TypeConverter<D, S> {
/// Empty constant constructor so that subclasses can have a constant
/// constructor.

View File

@ -6,7 +6,7 @@ homepage: https://moor.simonbinder.eu/
issue_tracker: https://github.com/simolus3/moor/issues
environment:
sdk: '>=2.12.0 <3.0.0'
sdk: '>=2.13.0 <3.0.0'
dependencies:
async: ^2.5.0

View File

@ -2,8 +2,10 @@ import 'package:moor/moor.dart';
import 'package:test/test.dart';
void main() {
final nullable = GeneratedDateTimeColumn('name', 'table', true);
final nonNull = GeneratedDateTimeColumn('name', 'table', false);
final nullable =
GeneratedColumn<DateTime>('name', 'table', true, typeName: 'INTEGER');
final nonNull =
GeneratedColumn<DateTime>('name', 'table', false, typeName: 'INTEGER');
test('should write column definition', () {
final nonNullQuery = GenerationContext.fromDb(null);

View File

@ -5,12 +5,12 @@ import '../data/tables/todos.dart';
void main() {
test('int column writes AUTOINCREMENT constraint', () {
final column = GeneratedIntColumn(
final column = GeneratedColumn<int>(
'foo',
'tbl',
false,
declaredAsPrimaryKey: true,
hasAutoIncrement: true,
typeName: 'INTEGER',
$customConstraints: 'NOT NULL PRIMARY KEY AUTOINCREMENT',
);
final context = GenerationContext.fromDb(TodoDb());
@ -21,13 +21,8 @@ void main() {
});
test('int column writes PRIMARY KEY constraint', () {
final column = GeneratedIntColumn(
'foo',
'tbl',
false,
declaredAsPrimaryKey: true,
hasAutoIncrement: false,
);
final column = GeneratedColumn<int>('foo', 'tbl', false,
typeName: 'INTEGER', $customConstraints: 'NOT NULL PRIMARY KEY');
final context = GenerationContext.fromDb(TodoDb());
column.writeColumnDefinition(context);

View File

@ -213,36 +213,25 @@ class ConfigTable extends Table with TableInfo<ConfigTable, Config> {
final String? _alias;
ConfigTable(this._db, [this._alias]);
final VerificationMeta _configKeyMeta = const VerificationMeta('configKey');
late final GeneratedTextColumn configKey = _constructConfigKey();
GeneratedTextColumn _constructConfigKey() {
return GeneratedTextColumn('config_key', aliasedName, false,
$customConstraints: 'not null primary key');
}
late final GeneratedColumn<String?> configKey = GeneratedColumn<String?>(
'config_key', aliasedName, false,
typeName: 'TEXT',
requiredDuringInsert: true,
$customConstraints: 'not null primary key');
final VerificationMeta _configValueMeta =
const VerificationMeta('configValue');
late final GeneratedTextColumn configValue = _constructConfigValue();
GeneratedTextColumn _constructConfigValue() {
return GeneratedTextColumn('config_value', aliasedName, true,
$customConstraints: '');
}
late final GeneratedColumn<String?> configValue = GeneratedColumn<String?>(
'config_value', aliasedName, true,
typeName: 'TEXT', requiredDuringInsert: false, $customConstraints: '');
final VerificationMeta _syncStateMeta = const VerificationMeta('syncState');
late final GeneratedIntColumn syncState = _constructSyncState();
GeneratedIntColumn _constructSyncState() {
return GeneratedIntColumn('sync_state', aliasedName, true,
$customConstraints: '');
}
late final GeneratedColumn<int?> syncState = GeneratedColumn<int?>(
'sync_state', aliasedName, true,
typeName: 'INTEGER', requiredDuringInsert: false, $customConstraints: '');
final VerificationMeta _syncStateImplicitMeta =
const VerificationMeta('syncStateImplicit');
late final GeneratedIntColumn syncStateImplicit =
_constructSyncStateImplicit();
GeneratedIntColumn _constructSyncStateImplicit() {
return GeneratedIntColumn('sync_state_implicit', aliasedName, true,
$customConstraints: '');
}
late final GeneratedColumn<int?> syncStateImplicit = GeneratedColumn<int?>(
'sync_state_implicit', aliasedName, true,
typeName: 'INTEGER', requiredDuringInsert: false, $customConstraints: '');
@override
List<GeneratedColumn> get $columns =>
[configKey, configValue, syncState, syncStateImplicit];
@ -425,20 +414,18 @@ class WithDefaults extends Table with TableInfo<WithDefaults, WithDefault> {
final String? _alias;
WithDefaults(this._db, [this._alias]);
final VerificationMeta _aMeta = const VerificationMeta('a');
late final GeneratedTextColumn a = _constructA();
GeneratedTextColumn _constructA() {
return GeneratedTextColumn('a', aliasedName, true,
$customConstraints: 'DEFAULT \'something\'',
defaultValue: const CustomExpression<String>('\'something\''));
}
late final GeneratedColumn<String?> a = GeneratedColumn<String?>(
'a', aliasedName, true,
typeName: 'TEXT',
requiredDuringInsert: false,
$customConstraints: 'DEFAULT \'something\'',
defaultValue: const CustomExpression<String>('\'something\''));
final VerificationMeta _bMeta = const VerificationMeta('b');
late final GeneratedIntColumn b = _constructB();
GeneratedIntColumn _constructB() {
return GeneratedIntColumn('b', aliasedName, true,
$customConstraints: 'UNIQUE');
}
late final GeneratedColumn<int?> b = GeneratedColumn<int?>(
'b', aliasedName, true,
typeName: 'INTEGER',
requiredDuringInsert: false,
$customConstraints: 'UNIQUE');
@override
List<GeneratedColumn> get $columns => [a, b];
@override
@ -521,12 +508,11 @@ class NoIds extends Table with TableInfo<NoIds, NoIdRow> {
final String? _alias;
NoIds(this._db, [this._alias]);
final VerificationMeta _payloadMeta = const VerificationMeta('payload');
late final GeneratedBlobColumn payload = _constructPayload();
GeneratedBlobColumn _constructPayload() {
return GeneratedBlobColumn('payload', aliasedName, false,
$customConstraints: 'NOT NULL PRIMARY KEY');
}
late final GeneratedColumn<Uint8List?> payload = GeneratedColumn<Uint8List?>(
'payload', aliasedName, false,
typeName: 'BLOB',
requiredDuringInsert: true,
$customConstraints: 'NOT NULL PRIMARY KEY');
@override
List<GeneratedColumn> get $columns => [payload];
@override
@ -727,24 +713,19 @@ class WithConstraints extends Table
final String? _alias;
WithConstraints(this._db, [this._alias]);
final VerificationMeta _aMeta = const VerificationMeta('a');
late final GeneratedTextColumn a = _constructA();
GeneratedTextColumn _constructA() {
return GeneratedTextColumn('a', aliasedName, true, $customConstraints: '');
}
late final GeneratedColumn<String?> a = GeneratedColumn<String?>(
'a', aliasedName, true,
typeName: 'TEXT', requiredDuringInsert: false, $customConstraints: '');
final VerificationMeta _bMeta = const VerificationMeta('b');
late final GeneratedIntColumn b = _constructB();
GeneratedIntColumn _constructB() {
return GeneratedIntColumn('b', aliasedName, false,
$customConstraints: 'NOT NULL');
}
late final GeneratedColumn<int?> b = GeneratedColumn<int?>(
'b', aliasedName, false,
typeName: 'INTEGER',
requiredDuringInsert: true,
$customConstraints: 'NOT NULL');
final VerificationMeta _cMeta = const VerificationMeta('c');
late final GeneratedRealColumn c = _constructC();
GeneratedRealColumn _constructC() {
return GeneratedRealColumn('c', aliasedName, true, $customConstraints: '');
}
late final GeneratedColumn<double?> c = GeneratedColumn<double?>(
'c', aliasedName, true,
typeName: 'REAL', requiredDuringInsert: false, $customConstraints: '');
@override
List<GeneratedColumn> get $columns => [a, b, c];
@override
@ -984,34 +965,24 @@ class Mytable extends Table with TableInfo<Mytable, MytableData> {
final String? _alias;
Mytable(this._db, [this._alias]);
final VerificationMeta _someidMeta = const VerificationMeta('someid');
late final GeneratedIntColumn someid = _constructSomeid();
GeneratedIntColumn _constructSomeid() {
return GeneratedIntColumn('someid', aliasedName, false,
$customConstraints: 'NOT NULL');
}
late final GeneratedColumn<int?> someid = GeneratedColumn<int?>(
'someid', aliasedName, false,
typeName: 'INTEGER',
requiredDuringInsert: false,
$customConstraints: 'NOT NULL');
final VerificationMeta _sometextMeta = const VerificationMeta('sometext');
late final GeneratedTextColumn sometext = _constructSometext();
GeneratedTextColumn _constructSometext() {
return GeneratedTextColumn('sometext', aliasedName, true,
$customConstraints: '');
}
late final GeneratedColumn<String?> sometext = GeneratedColumn<String?>(
'sometext', aliasedName, true,
typeName: 'TEXT', requiredDuringInsert: false, $customConstraints: '');
final VerificationMeta _isInsertingMeta =
const VerificationMeta('isInserting');
late final GeneratedBoolColumn isInserting = _constructIsInserting();
GeneratedBoolColumn _constructIsInserting() {
return GeneratedBoolColumn('is_inserting', aliasedName, true,
$customConstraints: '');
}
late final GeneratedColumn<bool?> isInserting = GeneratedColumn<bool?>(
'is_inserting', aliasedName, true,
typeName: 'INTEGER', requiredDuringInsert: false, $customConstraints: '');
final VerificationMeta _somedateMeta = const VerificationMeta('somedate');
late final GeneratedDateTimeColumn somedate = _constructSomedate();
GeneratedDateTimeColumn _constructSomedate() {
return GeneratedDateTimeColumn('somedate', aliasedName, true,
$customConstraints: '');
}
late final GeneratedColumn<DateTime?> somedate = GeneratedColumn<DateTime?>(
'somedate', aliasedName, true,
typeName: 'INTEGER', requiredDuringInsert: false, $customConstraints: '');
@override
List<GeneratedColumn> get $columns =>
[someid, sometext, isInserting, somedate];
@ -1218,26 +1189,17 @@ class Email extends Table
final String? _alias;
Email(this._db, [this._alias]);
final VerificationMeta _senderMeta = const VerificationMeta('sender');
late final GeneratedTextColumn sender = _constructSender();
GeneratedTextColumn _constructSender() {
return GeneratedTextColumn('sender', aliasedName, false,
$customConstraints: '');
}
late final GeneratedColumn<String?> sender = GeneratedColumn<String?>(
'sender', aliasedName, false,
typeName: 'TEXT', requiredDuringInsert: true, $customConstraints: '');
final VerificationMeta _titleMeta = const VerificationMeta('title');
late final GeneratedTextColumn title = _constructTitle();
GeneratedTextColumn _constructTitle() {
return GeneratedTextColumn('title', aliasedName, false,
$customConstraints: '');
}
late final GeneratedColumn<String?> title = GeneratedColumn<String?>(
'title', aliasedName, false,
typeName: 'TEXT', requiredDuringInsert: true, $customConstraints: '');
final VerificationMeta _bodyMeta = const VerificationMeta('body');
late final GeneratedTextColumn body = _constructBody();
GeneratedTextColumn _constructBody() {
return GeneratedTextColumn('body', aliasedName, false,
$customConstraints: '');
}
late final GeneratedColumn<String?> body = GeneratedColumn<String?>(
'body', aliasedName, false,
typeName: 'TEXT', requiredDuringInsert: true, $customConstraints: '');
@override
List<GeneratedColumn> get $columns => [sender, title, body];
@override
@ -1420,19 +1382,17 @@ class WeirdTable extends Table with TableInfo<WeirdTable, WeirdData> {
final String? _alias;
WeirdTable(this._db, [this._alias]);
final VerificationMeta _sqlClassMeta = const VerificationMeta('sqlClass');
late final GeneratedIntColumn sqlClass = _constructSqlClass();
GeneratedIntColumn _constructSqlClass() {
return GeneratedIntColumn('class', aliasedName, false,
$customConstraints: 'NOT NULL');
}
late final GeneratedColumn<int?> sqlClass = GeneratedColumn<int?>(
'class', aliasedName, false,
typeName: 'INTEGER',
requiredDuringInsert: true,
$customConstraints: 'NOT NULL');
final VerificationMeta _textColumnMeta = const VerificationMeta('textColumn');
late final GeneratedTextColumn textColumn = _constructTextColumn();
GeneratedTextColumn _constructTextColumn() {
return GeneratedTextColumn('text', aliasedName, false,
$customConstraints: 'NOT NULL');
}
late final GeneratedColumn<String?> textColumn = GeneratedColumn<String?>(
'text', aliasedName, false,
typeName: 'TEXT',
requiredDuringInsert: true,
$customConstraints: 'NOT NULL');
@override
List<GeneratedColumn> get $columns => [sqlClass, textColumn];
@override
@ -1581,42 +1541,18 @@ class MyView extends View<MyView, MyViewData> {
prefix: tablePrefix != null ? '$tablePrefix.' : null);
}
late final GeneratedTextColumn configKey = _constructConfigKey();
GeneratedTextColumn _constructConfigKey() {
return GeneratedTextColumn(
'config_key',
aliasedName,
false,
);
}
late final GeneratedTextColumn configValue = _constructConfigValue();
GeneratedTextColumn _constructConfigValue() {
return GeneratedTextColumn(
'config_value',
aliasedName,
true,
);
}
late final GeneratedIntColumn syncState = _constructSyncState();
GeneratedIntColumn _constructSyncState() {
return GeneratedIntColumn(
'sync_state',
aliasedName,
true,
);
}
late final GeneratedIntColumn syncStateImplicit =
_constructSyncStateImplicit();
GeneratedIntColumn _constructSyncStateImplicit() {
return GeneratedIntColumn(
'sync_state_implicit',
aliasedName,
true,
);
}
late final GeneratedColumn<String?> configKey = GeneratedColumn<String?>(
'config_key', aliasedName, false,
typeName: 'TEXT');
late final GeneratedColumn<String?> configValue = GeneratedColumn<String?>(
'config_value', aliasedName, true,
typeName: 'TEXT');
late final GeneratedColumn<int?> syncState = GeneratedColumn<int?>(
'sync_state', aliasedName, true,
typeName: 'INTEGER');
late final GeneratedColumn<int?> syncStateImplicit = GeneratedColumn<int?>(
'sync_state_implicit', aliasedName, true,
typeName: 'INTEGER');
}
abstract class _$CustomTablesDb extends GeneratedDatabase {
@ -1670,7 +1606,7 @@ abstract class _$CustomTablesDb extends GeneratedDatabase {
}
Selectable<Config> readDynamic(
{Expression<bool> Function(ConfigTable config) predicate =
{Expression<bool?> Function(ConfigTable config) predicate =
_$moor$default$1}) {
final generatedpredicate = $write(predicate(this.config));
return customSelect('SELECT * FROM config WHERE ${generatedpredicate.sql}',
@ -1679,7 +1615,8 @@ abstract class _$CustomTablesDb extends GeneratedDatabase {
}
Selectable<String> typeConverterVar(SyncType? var1, List<SyncType?> var2,
{Expression<bool> Function(ConfigTable config) pred = _$moor$default$2}) {
{Expression<bool?> Function(ConfigTable config) pred =
_$moor$default$2}) {
var $arrayStartIndex = 2;
final generatedpred = $write(pred(this.config));
$arrayStartIndex += generatedpred.amountOfVariables;
@ -1725,7 +1662,7 @@ abstract class _$CustomTablesDb extends GeneratedDatabase {
}
Selectable<MultipleResult> multiple(
{required Expression<bool> Function(WithDefaults d, WithConstraints c)
{required Expression<bool?> Function(WithDefaults d, WithConstraints c)
predicate}) {
final generatedpredicate = $write(
predicate(
@ -1752,7 +1689,7 @@ abstract class _$CustomTablesDb extends GeneratedDatabase {
}
Selectable<ReadRowIdResult> readRowId(
{required Expression<int> Function(ConfigTable config) expr}) {
{required Expression<int?> Function(ConfigTable config) expr}) {
final generatedexpr = $write(expr(this.config));
return customSelect(
'SELECT oid, * FROM config WHERE _rowid_ = ${generatedexpr.sql}',
@ -1837,9 +1774,9 @@ abstract class _$CustomTablesDb extends GeneratedDatabase {
}
OrderBy _$moor$default$0(ConfigTable _) => const OrderBy.nothing();
Expression<bool> _$moor$default$1(ConfigTable _) =>
Expression<bool?> _$moor$default$1(ConfigTable _) =>
const CustomExpression('(TRUE)');
Expression<bool> _$moor$default$2(ConfigTable _) =>
Expression<bool?> _$moor$default$2(ConfigTable _) =>
const CustomExpression('(TRUE)');
class JsonResult extends CustomResultSet {

View File

@ -229,54 +229,30 @@ class $TodosTableTable extends TodosTable
final String? _alias;
$TodosTableTable(this._db, [this._alias]);
final VerificationMeta _idMeta = const VerificationMeta('id');
@override
late final GeneratedIntColumn id = _constructId();
GeneratedIntColumn _constructId() {
return GeneratedIntColumn('id', aliasedName, false,
hasAutoIncrement: true, declaredAsPrimaryKey: true);
}
late final GeneratedColumn<int?> id = GeneratedColumn<int?>(
'id', aliasedName, false,
typeName: 'INTEGER',
requiredDuringInsert: false,
defaultConstraints: 'PRIMARY KEY AUTOINCREMENT');
final VerificationMeta _titleMeta = const VerificationMeta('title');
@override
late final GeneratedTextColumn title = _constructTitle();
GeneratedTextColumn _constructTitle() {
return GeneratedTextColumn('title', aliasedName, true,
minTextLength: 4, maxTextLength: 16);
}
late final GeneratedColumn<String?> title = GeneratedColumn<String?>(
'title', aliasedName, true,
additionalChecks:
GeneratedColumn.checkTextLength(minTextLength: 4, maxTextLength: 16),
typeName: 'TEXT',
requiredDuringInsert: false);
final VerificationMeta _contentMeta = const VerificationMeta('content');
@override
late final GeneratedTextColumn content = _constructContent();
GeneratedTextColumn _constructContent() {
return GeneratedTextColumn(
'content',
aliasedName,
false,
);
}
late final GeneratedColumn<String?> content = GeneratedColumn<String?>(
'content', aliasedName, false,
typeName: 'TEXT', requiredDuringInsert: true);
final VerificationMeta _targetDateMeta = const VerificationMeta('targetDate');
@override
late final GeneratedDateTimeColumn targetDate = _constructTargetDate();
GeneratedDateTimeColumn _constructTargetDate() {
return GeneratedDateTimeColumn(
'target_date',
aliasedName,
true,
);
}
late final GeneratedColumn<DateTime?> targetDate = GeneratedColumn<DateTime?>(
'target_date', aliasedName, true,
typeName: 'INTEGER', requiredDuringInsert: false);
final VerificationMeta _categoryMeta = const VerificationMeta('category');
@override
late final GeneratedIntColumn category = _constructCategory();
GeneratedIntColumn _constructCategory() {
return GeneratedIntColumn(
'category',
aliasedName,
true,
);
}
late final GeneratedColumn<int?> category = GeneratedColumn<int?>(
'category', aliasedName, true,
typeName: 'INTEGER', requiredDuringInsert: false);
@override
List<GeneratedColumn> get $columns =>
[id, title, content, targetDate, category];
@ -490,30 +466,24 @@ class $CategoriesTable extends Categories
final String? _alias;
$CategoriesTable(this._db, [this._alias]);
final VerificationMeta _idMeta = const VerificationMeta('id');
@override
late final GeneratedIntColumn id = _constructId();
GeneratedIntColumn _constructId() {
return GeneratedIntColumn('id', aliasedName, false,
hasAutoIncrement: true, declaredAsPrimaryKey: true);
}
late final GeneratedColumn<int?> id = GeneratedColumn<int?>(
'id', aliasedName, false,
typeName: 'INTEGER',
requiredDuringInsert: false,
defaultConstraints: 'PRIMARY KEY AUTOINCREMENT');
final VerificationMeta _descriptionMeta =
const VerificationMeta('description');
@override
late final GeneratedTextColumn description = _constructDescription();
GeneratedTextColumn _constructDescription() {
return GeneratedTextColumn('desc', aliasedName, false,
$customConstraints: 'NOT NULL UNIQUE');
}
late final GeneratedColumn<String?> description = GeneratedColumn<String?>(
'desc', aliasedName, false,
typeName: 'TEXT',
requiredDuringInsert: true,
$customConstraints: 'NOT NULL UNIQUE');
final VerificationMeta _priorityMeta = const VerificationMeta('priority');
@override
late final GeneratedIntColumn priority = _constructPriority();
GeneratedIntColumn _constructPriority() {
return GeneratedIntColumn('priority', aliasedName, false,
defaultValue: const Constant(0));
}
late final GeneratedColumn<int?> priority = GeneratedColumn<int?>(
'priority', aliasedName, false,
typeName: 'INTEGER',
requiredDuringInsert: false,
defaultValue: const Constant(0));
@override
List<GeneratedColumn> get $columns => [id, description, priority];
@override
@ -765,50 +735,37 @@ class $UsersTable extends Users with TableInfo<$UsersTable, User> {
final String? _alias;
$UsersTable(this._db, [this._alias]);
final VerificationMeta _idMeta = const VerificationMeta('id');
@override
late final GeneratedIntColumn id = _constructId();
GeneratedIntColumn _constructId() {
return GeneratedIntColumn('id', aliasedName, false,
hasAutoIncrement: true, declaredAsPrimaryKey: true);
}
late final GeneratedColumn<int?> id = GeneratedColumn<int?>(
'id', aliasedName, false,
typeName: 'INTEGER',
requiredDuringInsert: false,
defaultConstraints: 'PRIMARY KEY AUTOINCREMENT');
final VerificationMeta _nameMeta = const VerificationMeta('name');
@override
late final GeneratedTextColumn name = _constructName();
GeneratedTextColumn _constructName() {
return GeneratedTextColumn('name', aliasedName, false,
minTextLength: 6, maxTextLength: 32);
}
late final GeneratedColumn<String?> name = GeneratedColumn<String?>(
'name', aliasedName, false,
additionalChecks:
GeneratedColumn.checkTextLength(minTextLength: 6, maxTextLength: 32),
typeName: 'TEXT',
requiredDuringInsert: true);
final VerificationMeta _isAwesomeMeta = const VerificationMeta('isAwesome');
@override
late final GeneratedBoolColumn isAwesome = _constructIsAwesome();
GeneratedBoolColumn _constructIsAwesome() {
return GeneratedBoolColumn('is_awesome', aliasedName, false,
defaultValue: const Constant(true));
}
late final GeneratedColumn<bool?> isAwesome = GeneratedColumn<bool?>(
'is_awesome', aliasedName, false,
typeName: 'INTEGER',
requiredDuringInsert: false,
defaultConstraints: 'CHECK (is_awesome IN (0, 1))',
defaultValue: const Constant(true));
final VerificationMeta _profilePictureMeta =
const VerificationMeta('profilePicture');
@override
late final GeneratedBlobColumn profilePicture = _constructProfilePicture();
GeneratedBlobColumn _constructProfilePicture() {
return GeneratedBlobColumn(
'profile_picture',
aliasedName,
false,
);
}
late final GeneratedColumn<Uint8List?> profilePicture =
GeneratedColumn<Uint8List?>('profile_picture', aliasedName, false,
typeName: 'BLOB', requiredDuringInsert: true);
final VerificationMeta _creationTimeMeta =
const VerificationMeta('creationTime');
@override
late final GeneratedDateTimeColumn creationTime = _constructCreationTime();
GeneratedDateTimeColumn _constructCreationTime() {
return GeneratedDateTimeColumn('creation_time', aliasedName, false,
defaultValue: currentDateAndTime);
}
late final GeneratedColumn<DateTime?> creationTime =
GeneratedColumn<DateTime?>('creation_time', aliasedName, false,
typeName: 'INTEGER',
requiredDuringInsert: false,
defaultValue: currentDateAndTime);
@override
List<GeneratedColumn> get $columns =>
[id, name, isAwesome, profilePicture, creationTime];
@ -996,27 +953,13 @@ class $SharedTodosTable extends SharedTodos
final String? _alias;
$SharedTodosTable(this._db, [this._alias]);
final VerificationMeta _todoMeta = const VerificationMeta('todo');
@override
late final GeneratedIntColumn todo = _constructTodo();
GeneratedIntColumn _constructTodo() {
return GeneratedIntColumn(
'todo',
aliasedName,
false,
);
}
late final GeneratedColumn<int?> todo = GeneratedColumn<int?>(
'todo', aliasedName, false,
typeName: 'INTEGER', requiredDuringInsert: true);
final VerificationMeta _userMeta = const VerificationMeta('user');
@override
late final GeneratedIntColumn user = _constructUser();
GeneratedIntColumn _constructUser() {
return GeneratedIntColumn(
'user',
aliasedName,
false,
);
}
late final GeneratedColumn<int?> user = GeneratedColumn<int?>(
'user', aliasedName, false,
typeName: 'INTEGER', requiredDuringInsert: true);
@override
List<GeneratedColumn> get $columns => [todo, user];
@override
@ -1129,38 +1072,17 @@ class $TableWithoutPKTable extends TableWithoutPK
$TableWithoutPKTable(this._db, [this._alias]);
final VerificationMeta _notReallyAnIdMeta =
const VerificationMeta('notReallyAnId');
@override
late final GeneratedIntColumn notReallyAnId = _constructNotReallyAnId();
GeneratedIntColumn _constructNotReallyAnId() {
return GeneratedIntColumn(
'not_really_an_id',
aliasedName,
false,
);
}
late final GeneratedColumn<int?> notReallyAnId = GeneratedColumn<int?>(
'not_really_an_id', aliasedName, false,
typeName: 'INTEGER', requiredDuringInsert: true);
final VerificationMeta _someFloatMeta = const VerificationMeta('someFloat');
@override
late final GeneratedRealColumn someFloat = _constructSomeFloat();
GeneratedRealColumn _constructSomeFloat() {
return GeneratedRealColumn(
'some_float',
aliasedName,
false,
);
}
late final GeneratedColumn<double?> someFloat = GeneratedColumn<double?>(
'some_float', aliasedName, false,
typeName: 'REAL', requiredDuringInsert: true);
final VerificationMeta _customMeta = const VerificationMeta('custom');
@override
late final GeneratedTextColumn custom = _constructCustom();
GeneratedTextColumn _constructCustom() {
return GeneratedTextColumn(
'custom',
aliasedName,
false,
)..clientDefault = _uuid.v4;
}
late final GeneratedColumn<String?> custom = GeneratedColumn<String?>(
'custom', aliasedName, false,
typeName: 'TEXT', requiredDuringInsert: false, clientDefault: _uuid.v4);
@override
List<GeneratedColumn> get $columns => [notReallyAnId, someFloat, custom];
@override
@ -1323,16 +1245,9 @@ class $PureDefaultsTable extends PureDefaults
final String? _alias;
$PureDefaultsTable(this._db, [this._alias]);
final VerificationMeta _txtMeta = const VerificationMeta('txt');
@override
late final GeneratedTextColumn txt = _constructTxt();
GeneratedTextColumn _constructTxt() {
return GeneratedTextColumn(
'insert',
aliasedName,
true,
);
}
late final GeneratedColumn<String?> txt = GeneratedColumn<String?>(
'insert', aliasedName, true,
typeName: 'TEXT', requiredDuringInsert: false);
@override
List<GeneratedColumn> get $columns => [txt];
@override

View File

@ -4,7 +4,7 @@ import 'package:test/test.dart';
import '../data/utils/expect_generated.dart';
void main() {
final foo = GeneratedIntColumn('foo', 'bar', false);
const foo = CustomExpression<int>('foo', precedence: Precedence.primary);
group('count', () {
test('all', () {

View File

@ -5,10 +5,10 @@ import '../data/utils/expect_equality.dart';
import '../data/utils/expect_generated.dart';
void main() {
final i1 = GeneratedIntColumn('i1', 'tbl', true);
final i2 = GeneratedIntColumn('i2', 'tbl', true);
final s1 = GeneratedTextColumn('s1', 'tbl', true);
final s2 = GeneratedTextColumn('s2', 'tbl', true);
const i1 = CustomExpression<int>('i1', precedence: Precedence.primary);
const i2 = CustomExpression<int>('i2', precedence: Precedence.primary);
const s1 = CustomExpression<String>('s1', precedence: Precedence.primary);
const s2 = CustomExpression<String>('s2', precedence: Precedence.primary);
test('arithmetic test', () {
expect(i1 + i2 * i1, generates('i1 + i2 * i1'));

View File

@ -5,8 +5,8 @@ import '../data/utils/expect_equality.dart';
import '../data/utils/expect_generated.dart';
void main() {
final a = GeneratedBoolColumn('a', 'tbl', false);
final b = GeneratedBoolColumn('b', 'tbl', false);
const a = CustomExpression<bool>('a', precedence: Precedence.primary);
const b = CustomExpression<bool>('b', precedence: Precedence.primary);
test('boolean expressions via operators', () {
expect(a | b, generates('a OR b'));

View File

@ -5,7 +5,8 @@ import '../data/tables/todos.dart';
import '../data/utils/expect_equality.dart';
void main() {
final expression = GeneratedIntColumn('col', 'table', false);
const expression =
CustomExpression<int>('col', precedence: Precedence.primary);
final db = TodoDb();
final comparisons = {
@ -23,7 +24,8 @@ void main() {
};
group('can compare with other expressions', () {
final compare = GeneratedIntColumn('compare', 'table', false);
const compare =
CustomExpression<int>('compare', precedence: Precedence.primary);
comparisons.forEach((fn, value) {
test('for operator $value', () {
@ -53,8 +55,9 @@ void main() {
group('between', () {
test('other expressions', () {
final low = GeneratedIntColumn('low', 'table', false);
final high = GeneratedIntColumn('high', 'table', false);
const low = CustomExpression<int>('low', precedence: Precedence.primary);
const high =
CustomExpression<int>('high', precedence: Precedence.primary);
final ctx = GenerationContext.fromDb(db);
expression.isBetween(low, high).writeInto(ctx);

View File

@ -7,7 +7,8 @@ import '../data/utils/expect_generated.dart';
typedef _Extractor = Expression<int?> Function(Expression<DateTime?> d);
void main() {
final column = GeneratedDateTimeColumn('val', 'table', false);
const column =
CustomExpression<DateTime>('val', precedence: Precedence.primary);
group('extracting information via top-level method', () {
final expectedResults = <_Extractor, String>{

View File

@ -25,7 +25,7 @@ void main() {
});
test('generates cast expressions', () {
final expr = GeneratedIntColumn('c', 'tbl', false);
const expr = CustomExpression<int>('c');
expect(expr.cast<String>(), generates('CAST(c AS TEXT)'));
expect(expr.cast<int>(), generates('CAST(c AS INTEGER)'));

View File

@ -7,7 +7,8 @@ import '../data/utils/expect_generated.dart';
void main() {
final db = TodoDb();
final innerExpression = GeneratedTextColumn('name', 'table', true);
const innerExpression =
CustomExpression<String>('name', precedence: Precedence.primary);
group('values', () {
test('in expressions are generated', () {
final isInExpression = innerExpression.isIn(['Max', 'Tobias']);

View File

@ -6,7 +6,8 @@ import '../data/utils/expect_equality.dart';
import '../data/utils/expect_generated.dart';
void main() {
final innerExpression = GeneratedTextColumn('name', 'table', true);
const innerExpression =
CustomExpression<int>('name', precedence: Precedence.primary);
test('IS NULL expressions are generated', () {
final oldFunction = moor.isNull(innerExpression);

View File

@ -5,7 +5,8 @@ import '../data/tables/todos.dart';
import '../data/utils/expect_generated.dart';
void main() {
final expression = GeneratedTextColumn('col', 'table', false);
const expression =
CustomExpression<String>('col', precedence: Precedence.primary);
final db = TodoDb();
test('generates like expressions', () {

View File

@ -6,7 +6,7 @@ import '../data/utils/expect_generated.dart';
void main() {
test('json1 functions generate valid sql', () {
final column = GeneratedTextColumn('col', 'tbl', false);
const column = CustomExpression<String>('col');
expect(column.jsonArrayLength(), generates('json_array_length(col)'));
expect(

View File

@ -8,8 +8,8 @@ import '../data/tables/todos.dart';
import '../data/utils/expect_generated.dart';
void main() {
final a = GeneratedRealColumn('a', 'table', false);
final b = GeneratedRealColumn('b', 'table', false);
const a = CustomExpression<double>('a');
const b = CustomExpression<double>('b');
test('pow', () {
expect(sqlPow(a, b), generates('pow(a, b)'));
@ -24,7 +24,7 @@ void main() {
test('atan', () => expect(sqlAtan(a), generates('atan(a)')));
test('containsCase', () {
final c = GeneratedTextColumn('a', 'table', false);
const c = CustomExpression<String>('a');
expect(c.containsCase('foo'), generates('moor_contains(a, ?, 0)', ['foo']));
expect(

View File

@ -37,7 +37,7 @@ void main() {
'CREATE TABLE IF NOT EXISTS users '
'(id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, '
'name TEXT NOT NULL, '
'is_awesome INTEGER NOT NULL DEFAULT 1 CHECK (is_awesome in (0, 1)), '
'is_awesome INTEGER NOT NULL DEFAULT 1 CHECK (is_awesome IN (0, 1)), '
'profile_picture BLOB NOT NULL, '
'creation_time INTEGER NOT NULL '
"DEFAULT (strftime('%s', CURRENT_TIMESTAMP)));",
@ -70,7 +70,7 @@ void main() {
'CREATE TABLE IF NOT EXISTS users '
'(id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, '
'name TEXT NOT NULL, '
'is_awesome INTEGER NOT NULL DEFAULT 1 CHECK (is_awesome in (0, 1)), '
'is_awesome INTEGER NOT NULL DEFAULT 1 CHECK (is_awesome IN (0, 1)), '
'profile_picture BLOB NOT NULL, '
'creation_time INTEGER NOT NULL '
"DEFAULT (strftime('%s', CURRENT_TIMESTAMP)));",
@ -100,7 +100,7 @@ void main() {
verify(mockExecutor.runCustom('ALTER TABLE users ADD COLUMN '
'is_awesome INTEGER NOT NULL DEFAULT 1 '
'CHECK (is_awesome in (0, 1));'));
'CHECK (is_awesome IN (0, 1));'));
});
test('renames columns', () async {

View File

@ -20,17 +20,14 @@ class TodoEntry extends DataClass implements Insertable<TodoEntry> {
factory TodoEntry.fromData(Map<String, dynamic> data, GeneratedDatabase db,
{String prefix}) {
final effectivePrefix = prefix ?? '';
final intType = db.typeSystem.forDartType<int>();
final stringType = db.typeSystem.forDartType<String>();
final dateTimeType = db.typeSystem.forDartType<DateTime>();
return TodoEntry(
id: intType.mapFromDatabaseResponse(data['${effectivePrefix}id']),
content:
stringType.mapFromDatabaseResponse(data['${effectivePrefix}content']),
targetDate: dateTimeType
id: const IntType().mapFromDatabaseResponse(data['${effectivePrefix}id']),
content: const StringType()
.mapFromDatabaseResponse(data['${effectivePrefix}content']),
targetDate: const DateTimeType()
.mapFromDatabaseResponse(data['${effectivePrefix}target_date']),
category:
intType.mapFromDatabaseResponse(data['${effectivePrefix}category']),
category: const IntType()
.mapFromDatabaseResponse(data['${effectivePrefix}category']),
);
}
@override
@ -110,7 +107,7 @@ class TodoEntry extends DataClass implements Insertable<TodoEntry> {
int get hashCode => $mrjf($mrjc(id.hashCode,
$mrjc(content.hashCode, $mrjc(targetDate.hashCode, category.hashCode))));
@override
bool operator ==(dynamic other) =>
bool operator ==(Object other) =>
identical(this, other) ||
(other is TodoEntry &&
other.id == this.id &&
@ -198,56 +195,39 @@ class $TodosTable extends Todos with TableInfo<$TodosTable, TodoEntry> {
final String _alias;
$TodosTable(this._db, [this._alias]);
final VerificationMeta _idMeta = const VerificationMeta('id');
GeneratedIntColumn _id;
GeneratedColumn<int> _id;
@override
GeneratedIntColumn get id => _id ??= _constructId();
GeneratedIntColumn _constructId() {
return GeneratedIntColumn('id', $tableName, false,
hasAutoIncrement: true, declaredAsPrimaryKey: true);
}
GeneratedColumn<int> get id =>
_id ??= GeneratedColumn<int>('id', aliasedName, false,
typeName: 'INTEGER',
requiredDuringInsert: false,
defaultConstraints: 'PRIMARY KEY AUTOINCREMENT');
final VerificationMeta _contentMeta = const VerificationMeta('content');
GeneratedTextColumn _content;
GeneratedColumn<String> _content;
@override
GeneratedTextColumn get content => _content ??= _constructContent();
GeneratedTextColumn _constructContent() {
return GeneratedTextColumn(
'content',
$tableName,
false,
);
}
GeneratedColumn<String> get content =>
_content ??= GeneratedColumn<String>('content', aliasedName, false,
typeName: 'TEXT', requiredDuringInsert: true);
final VerificationMeta _targetDateMeta = const VerificationMeta('targetDate');
GeneratedDateTimeColumn _targetDate;
GeneratedColumn<DateTime> _targetDate;
@override
GeneratedDateTimeColumn get targetDate =>
_targetDate ??= _constructTargetDate();
GeneratedDateTimeColumn _constructTargetDate() {
return GeneratedDateTimeColumn(
'target_date',
$tableName,
true,
);
}
GeneratedColumn<DateTime> get targetDate => _targetDate ??=
GeneratedColumn<DateTime>('target_date', aliasedName, true,
typeName: 'INTEGER', requiredDuringInsert: false);
final VerificationMeta _categoryMeta = const VerificationMeta('category');
GeneratedIntColumn _category;
GeneratedColumn<int> _category;
@override
GeneratedIntColumn get category => _category ??= _constructCategory();
GeneratedIntColumn _constructCategory() {
return GeneratedIntColumn('category', $tableName, true,
$customConstraints: 'NULLABLE REFERENCES categories(id)');
}
GeneratedColumn<int> get category =>
_category ??= GeneratedColumn<int>('category', aliasedName, true,
typeName: 'INTEGER',
requiredDuringInsert: false,
$customConstraints: 'NULLABLE REFERENCES categories(id)');
@override
List<GeneratedColumn> get $columns => [id, content, targetDate, category];
@override
$TodosTable get asDslTable => this;
String get aliasedName => _alias ?? 'todos';
@override
String get $tableName => _alias ?? 'todos';
@override
final String actualTableName = 'todos';
String get actualTableName => 'todos';
@override
VerificationContext validateIntegrity(Insertable<TodoEntry> instance,
{bool isInserting = false}) {
@ -279,8 +259,8 @@ class $TodosTable extends Todos with TableInfo<$TodosTable, TodoEntry> {
Set<GeneratedColumn> get $primaryKey => {id};
@override
TodoEntry map(Map<String, dynamic> data, {String tablePrefix}) {
final effectivePrefix = tablePrefix != null ? '$tablePrefix.' : null;
return TodoEntry.fromData(data, _db, prefix: effectivePrefix);
return TodoEntry.fromData(data, _db,
prefix: tablePrefix != null ? '$tablePrefix.' : null);
}
@override
@ -296,12 +276,10 @@ class Category extends DataClass implements Insertable<Category> {
factory Category.fromData(Map<String, dynamic> data, GeneratedDatabase db,
{String prefix}) {
final effectivePrefix = prefix ?? '';
final intType = db.typeSystem.forDartType<int>();
final stringType = db.typeSystem.forDartType<String>();
return Category(
id: intType.mapFromDatabaseResponse(data['${effectivePrefix}id']),
description:
stringType.mapFromDatabaseResponse(data['${effectivePrefix}desc']),
id: const IntType().mapFromDatabaseResponse(data['${effectivePrefix}id']),
description: const StringType()
.mapFromDatabaseResponse(data['${effectivePrefix}desc']),
);
}
@override
@ -358,7 +336,7 @@ class Category extends DataClass implements Insertable<Category> {
@override
int get hashCode => $mrjf($mrjc(id.hashCode, description.hashCode));
@override
bool operator ==(dynamic other) =>
bool operator ==(Object other) =>
identical(this, other) ||
(other is Category &&
other.id == this.id &&
@ -421,36 +399,26 @@ class $CategoriesTable extends Categories
final String _alias;
$CategoriesTable(this._db, [this._alias]);
final VerificationMeta _idMeta = const VerificationMeta('id');
GeneratedIntColumn _id;
GeneratedColumn<int> _id;
@override
GeneratedIntColumn get id => _id ??= _constructId();
GeneratedIntColumn _constructId() {
return GeneratedIntColumn('id', $tableName, false,
hasAutoIncrement: true, declaredAsPrimaryKey: true);
}
GeneratedColumn<int> get id =>
_id ??= GeneratedColumn<int>('id', aliasedName, false,
typeName: 'INTEGER',
requiredDuringInsert: false,
defaultConstraints: 'PRIMARY KEY AUTOINCREMENT');
final VerificationMeta _descriptionMeta =
const VerificationMeta('description');
GeneratedTextColumn _description;
GeneratedColumn<String> _description;
@override
GeneratedTextColumn get description =>
_description ??= _constructDescription();
GeneratedTextColumn _constructDescription() {
return GeneratedTextColumn(
'desc',
$tableName,
false,
);
}
GeneratedColumn<String> get description =>
_description ??= GeneratedColumn<String>('desc', aliasedName, false,
typeName: 'TEXT', requiredDuringInsert: true);
@override
List<GeneratedColumn> get $columns => [id, description];
@override
$CategoriesTable get asDslTable => this;
String get aliasedName => _alias ?? 'categories';
@override
String get $tableName => _alias ?? 'categories';
@override
final String actualTableName = 'categories';
String get actualTableName => 'categories';
@override
VerificationContext validateIntegrity(Insertable<Category> instance,
{bool isInserting = false}) {
@ -472,8 +440,8 @@ class $CategoriesTable extends Categories
Set<GeneratedColumn> get $primaryKey => {id};
@override
Category map(Map<String, dynamic> data, {String tablePrefix}) {
final effectivePrefix = tablePrefix != null ? '$tablePrefix.' : null;
return Category.fromData(data, _db, prefix: effectivePrefix);
return Category.fromData(data, _db,
prefix: tablePrefix != null ? '$tablePrefix.' : null);
}
@override
@ -521,8 +489,8 @@ class CategoriesWithCountResult {
final String desc;
final int amount;
CategoriesWithCountResult({
@required this.id,
@required this.desc,
this.id,
this.desc,
@required this.amount,
});
}

View File

@ -7,7 +7,7 @@ packages:
name: async
url: "https://pub.dartlang.org"
source: hosted
version: "2.5.0"
version: "2.6.1"
boolean_selector:
dependency: transitive
description:
@ -120,7 +120,7 @@ packages:
name: source_span
url: "https://pub.dartlang.org"
source: hosted
version: "1.8.0"
version: "1.8.1"
sqflite:
dependency: "direct main"
description:
@ -183,7 +183,7 @@ packages:
name: test_api
url: "https://pub.dartlang.org"
source: hosted
version: "0.2.19"
version: "0.3.0"
typed_data:
dependency: transitive
description:

View File

@ -1,5 +1,6 @@
//@dart=2.9
import 'package:moor_generator/src/analyzer/options.dart';
import 'package:moor_generator/writer.dart';
import 'declarations/declaration.dart';
import 'types.dart';
@ -105,6 +106,7 @@ class MoorColumn implements HasDeclaration, HasType {
/// 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`.
@Deprecated('Use Column<innerColumnType()> instead')
String get dslColumnTypeName => const {
ColumnType.boolean: 'BoolColumn',
ColumnType.text: 'TextColumn',
@ -114,17 +116,52 @@ class MoorColumn implements HasDeclaration, HasType {
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 => const {
ColumnType.boolean: 'GeneratedBoolColumn',
ColumnType.text: 'GeneratedTextColumn',
ColumnType.integer: 'GeneratedIntColumn',
ColumnType.datetime: 'GeneratedDateTimeColumn',
ColumnType.blob: 'GeneratedBlobColumn',
ColumnType.real: 'GeneratedRealColumn',
}[type];
String innerColumnType(
[GenerationOptions options = const GenerationOptions()]) {
String code;
switch (type) {
case ColumnType.integer:
code = 'int';
break;
case ColumnType.text:
code = 'String';
break;
case ColumnType.boolean:
code = 'bool';
break;
case ColumnType.datetime:
code = 'DateTime';
break;
case ColumnType.blob:
code = 'Uint8List';
break;
case ColumnType.real:
code = 'double';
break;
}
// We currently use nullable columns everywhere because it's not clear how
// to express nullability in joins otherwise.
return options.nnbd ? '$code?' : code;
}
String sqlTypeName() {
switch (type) {
case ColumnType.integer:
case ColumnType.boolean:
case ColumnType.datetime:
return 'INTEGER';
case ColumnType.text:
return 'TEXT';
case ColumnType.blob:
return 'BLOB';
case ColumnType.real:
return 'REAL';
}
throw AssertionError("Can't happen");
}
@override
bool get isArray => false;

View File

@ -1,4 +1,5 @@
//@dart=2.9
import 'package:moor/sqlite_keywords.dart';
import 'package:moor_generator/moor_generator.dart';
import 'package:moor_generator/src/model/declarations/declaration.dart';
import 'package:moor_generator/src/utils/string_escaper.dart';
@ -18,35 +19,68 @@ abstract class TableOrViewWriter {
final additionalParams = <String, String>{};
final expressionBuffer = StringBuffer();
final defaultConstraints = <String>[];
var wrotePkConstraint = false;
for (final feature in column.features) {
if (feature is AutoIncrement) {
additionalParams['hasAutoIncrement'] = 'true';
} else if (feature is LimitingTextLength) {
if (feature is PrimaryKey) {
if (!wrotePkConstraint) {
defaultConstraints.add(feature is AutoIncrement
? 'PRIMARY KEY AUTOINCREMENT'
: 'PRIMARY KEY');
wrotePkConstraint = true;
}
}
if (feature is LimitingTextLength) {
final buffer = StringBuffer('GeneratedColumn.checkTextLength(');
if (feature.minLength != null) {
additionalParams['minTextLength'] = feature.minLength.toString();
buffer.write('minTextLength: ${feature.minLength},');
}
if (feature.maxLength != null) {
additionalParams['maxTextLength'] = feature.maxLength.toString();
buffer.write('maxTextLength: ${feature.maxLength}');
}
} else if (feature is PrimaryKey && column.type == ColumnType.integer) {
// this field is only relevant for integer columns because an INTEGER
// PRIMARY KEY is an alias for the rowid which should allow absent
// values during insert, even without the `AUTOINCREMENT` clause.
additionalParams['declaredAsPrimaryKey'] = 'true';
buffer.write(')');
additionalParams['additionalChecks'] = buffer.toString();
}
}
if (column.type == ColumnType.boolean) {
final name = escapeIfNeeded(column.name.name);
defaultConstraints.add('CHECK ($name IN (0, 1))');
}
additionalParams['typeName'] = asDartLiteral(column.sqlTypeName());
if (tableOrView is MoorTable) {
additionalParams['requiredDuringInsert'] = (tableOrView as MoorTable)
.isColumnRequiredForInsert(column)
.toString();
}
if (column.customConstraints != null) {
additionalParams['\$customConstraints'] =
asDartLiteral(column.customConstraints);
} else if (defaultConstraints.isNotEmpty) {
// Use the default constraints supported by moor
additionalParams['defaultConstraints'] =
asDartLiteral(defaultConstraints.join(' '));
}
if (column.defaultArgument != null) {
additionalParams['defaultValue'] = column.defaultArgument;
}
if (column.clientDefaultCode != null) {
additionalParams['clientDefault'] = column.clientDefaultCode;
}
final innerType = column.innerColumnType(options);
final type = 'GeneratedColumn<$innerType>';
expressionBuffer
..write('return ${column.implColumnTypeName}')
..write(type)
..write("('${column.name.name}', aliasedName, $isNullable, ");
var first = true;
@ -62,19 +96,13 @@ abstract class TableOrViewWriter {
expressionBuffer.write(')');
if (column.clientDefaultCode != null) {
expressionBuffer.write('..clientDefault = ${column.clientDefaultCode}');
}
expressionBuffer.write(';');
writeMemoizedGetterWithBody(
writeMemoizedGetter(
buffer: buffer,
getterName: column.dartGetterName,
returnType: column.implColumnTypeName,
returnType: type,
code: expressionBuffer.toString(),
hasOverride: isOverride,
options: options,
hasOverride: isOverride,
);
}