Support includes on the @UseDao annotation as well

This commit is contained in:
Simon Binder 2019-07-29 15:19:58 +02:00
parent e0a82b0e32
commit 634b1adb72
No known key found for this signature in database
GPG Key ID: 7891917E4147B8C0
8 changed files with 80 additions and 50 deletions

1
.gitattributes vendored Normal file
View File

@ -0,0 +1 @@
*.moor linguist-language=SQL

View File

@ -44,10 +44,12 @@ class UseMoor {
/// {@endtemplate} /// {@endtemplate}
final Map<String, String> queries; final Map<String, String> queries;
/// {@template moor_include_param}
/// Defines the `.moor` files to include when building the table structure for /// Defines the `.moor` files to include when building the table structure for
/// this database. /// this database.
/// ///
/// Please note that this feature is experimental at the moment. /// Please note that this feature is experimental at the moment.
/// {@endtemplate}
@experimental @experimental
final Set<String> include; final Set<String> include;
@ -87,8 +89,14 @@ class UseDao {
final List<Type> tables; final List<Type> tables;
/// {@macro moor_compile_queries_param} /// {@macro moor_compile_queries_param}
@experimental
final Map<String, String> queries; final Map<String, String> queries;
const UseDao({@required this.tables, @experimental this.queries = const {}}); /// {@macro moor_include_param}
@experimental
final Set<String> include;
const UseDao(
{@required this.tables,
this.queries = const {},
@experimental this.include = const {}});
} }

View File

@ -1,4 +1,4 @@
CREATE TABLE state ( CREATE TABLE states (
id INT NOT NULL PRIMARY KEY AUTOINCREMENT, id INT NOT NULL PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL name TEXT NOT NULL
); );
@ -6,5 +6,5 @@ CREATE TABLE state (
CREATE TABLE experiments ( CREATE TABLE experiments (
id INT NOT NULL PRIMARY KEY AUTOINCREMENT, id INT NOT NULL PRIMARY KEY AUTOINCREMENT,
description TEXT NOT NULL, description TEXT NOT NULL,
state INT REFERENCES state(id) ON UPDATE CASCADE ON DELETE SET NULL state INT REFERENCES states(id) ON UPDATE CASCADE ON DELETE SET NULL
) )

View File

@ -1187,23 +1187,23 @@ class $PureDefaultsTable extends PureDefaults
} }
} }
class StateData extends DataClass implements Insertable<StateData> { class State extends DataClass implements Insertable<State> {
final int id; final int id;
final String name; final String name;
StateData({@required this.id, @required this.name}); State({@required this.id, @required this.name});
factory StateData.fromData(Map<String, dynamic> data, GeneratedDatabase db, factory State.fromData(Map<String, dynamic> data, GeneratedDatabase db,
{String prefix}) { {String prefix}) {
final effectivePrefix = prefix ?? ''; final effectivePrefix = prefix ?? '';
final intType = db.typeSystem.forDartType<int>(); final intType = db.typeSystem.forDartType<int>();
final stringType = db.typeSystem.forDartType<String>(); final stringType = db.typeSystem.forDartType<String>();
return StateData( return State(
id: intType.mapFromDatabaseResponse(data['${effectivePrefix}id']), id: intType.mapFromDatabaseResponse(data['${effectivePrefix}id']),
name: stringType.mapFromDatabaseResponse(data['${effectivePrefix}name']), name: stringType.mapFromDatabaseResponse(data['${effectivePrefix}name']),
); );
} }
factory StateData.fromJson(Map<String, dynamic> json, factory State.fromJson(Map<String, dynamic> json,
{ValueSerializer serializer = const ValueSerializer.defaults()}) { {ValueSerializer serializer = const ValueSerializer.defaults()}) {
return StateData( return State(
id: serializer.fromJson<int>(json['id']), id: serializer.fromJson<int>(json['id']),
name: serializer.fromJson<String>(json['name']), name: serializer.fromJson<String>(json['name']),
); );
@ -1218,20 +1218,20 @@ class StateData extends DataClass implements Insertable<StateData> {
} }
@override @override
T createCompanion<T extends UpdateCompanion<StateData>>(bool nullToAbsent) { T createCompanion<T extends UpdateCompanion<State>>(bool nullToAbsent) {
return StateCompanion( return StatesCompanion(
id: id == null && nullToAbsent ? const Value.absent() : Value(id), id: id == null && nullToAbsent ? const Value.absent() : Value(id),
name: name == null && nullToAbsent ? const Value.absent() : Value(name), name: name == null && nullToAbsent ? const Value.absent() : Value(name),
) as T; ) as T;
} }
StateData copyWith({int id, String name}) => StateData( State copyWith({int id, String name}) => State(
id: id ?? this.id, id: id ?? this.id,
name: name ?? this.name, name: name ?? this.name,
); );
@override @override
String toString() { String toString() {
return (StringBuffer('StateData(') return (StringBuffer('State(')
..write('id: $id, ') ..write('id: $id, ')
..write('name: $name') ..write('name: $name')
..write(')')) ..write(')'))
@ -1243,25 +1243,24 @@ class StateData extends DataClass implements Insertable<StateData> {
@override @override
bool operator ==(other) => bool operator ==(other) =>
identical(this, other) || identical(this, other) ||
(other is StateData && other.id == id && other.name == name); (other is State && other.id == id && other.name == name);
} }
class StateCompanion extends UpdateCompanion<StateData> { class StatesCompanion extends UpdateCompanion<State> {
final Value<int> id; final Value<int> id;
final Value<String> name; final Value<String> name;
const StateCompanion({ const StatesCompanion({
this.id = const Value.absent(), this.id = const Value.absent(),
this.name = const Value.absent(), this.name = const Value.absent(),
}); });
} }
class $StateTable extends Table with TableInfo<$StateTable, StateData> { class States extends Table with TableInfo<States, State> {
final GeneratedDatabase _db; final GeneratedDatabase _db;
final String _alias; final String _alias;
$StateTable(this._db, [this._alias]); States(this._db, [this._alias]);
final VerificationMeta _idMeta = const VerificationMeta('id'); final VerificationMeta _idMeta = const VerificationMeta('id');
GeneratedIntColumn _id; GeneratedIntColumn _id;
@override
GeneratedIntColumn get id => _id ??= _constructId(); GeneratedIntColumn get id => _id ??= _constructId();
GeneratedIntColumn _constructId() { GeneratedIntColumn _constructId() {
return GeneratedIntColumn('id', $tableName, false, return GeneratedIntColumn('id', $tableName, false,
@ -1271,7 +1270,6 @@ class $StateTable extends Table with TableInfo<$StateTable, StateData> {
final VerificationMeta _nameMeta = const VerificationMeta('name'); final VerificationMeta _nameMeta = const VerificationMeta('name');
GeneratedTextColumn _name; GeneratedTextColumn _name;
@override
GeneratedTextColumn get name => _name ??= _constructName(); GeneratedTextColumn get name => _name ??= _constructName();
GeneratedTextColumn _constructName() { GeneratedTextColumn _constructName() {
return GeneratedTextColumn('name', $tableName, false, return GeneratedTextColumn('name', $tableName, false,
@ -1281,13 +1279,13 @@ class $StateTable extends Table with TableInfo<$StateTable, StateData> {
@override @override
List<GeneratedColumn> get $columns => [id, name]; List<GeneratedColumn> get $columns => [id, name];
@override @override
$StateTable get asDslTable => this; States get asDslTable => this;
@override @override
String get $tableName => _alias ?? 'state'; String get $tableName => _alias ?? 'states';
@override @override
final String actualTableName = 'state'; final String actualTableName = 'states';
@override @override
VerificationContext validateIntegrity(StateCompanion d, VerificationContext validateIntegrity(StatesCompanion d,
{bool isInserting = false}) { {bool isInserting = false}) {
final context = VerificationContext(); final context = VerificationContext();
if (d.id.present) { if (d.id.present) {
@ -1307,13 +1305,13 @@ class $StateTable extends Table with TableInfo<$StateTable, StateData> {
@override @override
Set<GeneratedColumn> get $primaryKey => {id}; Set<GeneratedColumn> get $primaryKey => {id};
@override @override
StateData map(Map<String, dynamic> data, {String tablePrefix}) { State map(Map<String, dynamic> data, {String tablePrefix}) {
final effectivePrefix = tablePrefix != null ? '$tablePrefix.' : null; final effectivePrefix = tablePrefix != null ? '$tablePrefix.' : null;
return StateData.fromData(data, _db, prefix: effectivePrefix); return State.fromData(data, _db, prefix: effectivePrefix);
} }
@override @override
Map<String, Variable> entityToSql(StateCompanion d) { Map<String, Variable> entityToSql(StatesCompanion d) {
final map = <String, Variable>{}; final map = <String, Variable>{};
if (d.id.present) { if (d.id.present) {
map['id'] = Variable<int, IntType>(d.id.value); map['id'] = Variable<int, IntType>(d.id.value);
@ -1325,8 +1323,8 @@ class $StateTable extends Table with TableInfo<$StateTable, StateData> {
} }
@override @override
$StateTable createAlias(String alias) { States createAlias(String alias) {
return $StateTable(_db, alias); return States(_db, alias);
} }
} }
@ -1415,14 +1413,12 @@ class ExperimentsCompanion extends UpdateCompanion<Experiment> {
}); });
} }
class $ExperimentsTable extends Table class Experiments extends Table with TableInfo<Experiments, Experiment> {
with TableInfo<$ExperimentsTable, Experiment> {
final GeneratedDatabase _db; final GeneratedDatabase _db;
final String _alias; final String _alias;
$ExperimentsTable(this._db, [this._alias]); Experiments(this._db, [this._alias]);
final VerificationMeta _idMeta = const VerificationMeta('id'); final VerificationMeta _idMeta = const VerificationMeta('id');
GeneratedIntColumn _id; GeneratedIntColumn _id;
@override
GeneratedIntColumn get id => _id ??= _constructId(); GeneratedIntColumn get id => _id ??= _constructId();
GeneratedIntColumn _constructId() { GeneratedIntColumn _constructId() {
return GeneratedIntColumn('id', $tableName, false, return GeneratedIntColumn('id', $tableName, false,
@ -1433,7 +1429,6 @@ class $ExperimentsTable extends Table
final VerificationMeta _descriptionMeta = final VerificationMeta _descriptionMeta =
const VerificationMeta('description'); const VerificationMeta('description');
GeneratedTextColumn _description; GeneratedTextColumn _description;
@override
GeneratedTextColumn get description => GeneratedTextColumn get description =>
_description ??= _constructDescription(); _description ??= _constructDescription();
GeneratedTextColumn _constructDescription() { GeneratedTextColumn _constructDescription() {
@ -1443,18 +1438,17 @@ class $ExperimentsTable extends Table
final VerificationMeta _stateMeta = const VerificationMeta('state'); final VerificationMeta _stateMeta = const VerificationMeta('state');
GeneratedIntColumn _state; GeneratedIntColumn _state;
@override
GeneratedIntColumn get state => _state ??= _constructState(); GeneratedIntColumn get state => _state ??= _constructState();
GeneratedIntColumn _constructState() { GeneratedIntColumn _constructState() {
return GeneratedIntColumn('state', $tableName, true, return GeneratedIntColumn('state', $tableName, true,
$customConstraints: $customConstraints:
'REFERENCES state(id) ON UPDATE CASCADE ON DELETE SET NULL'); 'REFERENCES states(id) ON UPDATE CASCADE ON DELETE SET NULL');
} }
@override @override
List<GeneratedColumn> get $columns => [id, description, state]; List<GeneratedColumn> get $columns => [id, description, state];
@override @override
$ExperimentsTable get asDslTable => this; Experiments get asDslTable => this;
@override @override
String get $tableName => _alias ?? 'experiments'; String get $tableName => _alias ?? 'experiments';
@override @override
@ -1507,8 +1501,8 @@ class $ExperimentsTable extends Table
} }
@override @override
$ExperimentsTable createAlias(String alias) { Experiments createAlias(String alias) {
return $ExperimentsTable(_db, alias); return Experiments(_db, alias);
} }
} }
@ -1554,10 +1548,10 @@ abstract class _$TodoDb extends GeneratedDatabase {
$PureDefaultsTable _pureDefaults; $PureDefaultsTable _pureDefaults;
$PureDefaultsTable get pureDefaults => $PureDefaultsTable get pureDefaults =>
_pureDefaults ??= $PureDefaultsTable(this); _pureDefaults ??= $PureDefaultsTable(this);
$StateTable _state; States _states;
$StateTable get state => _state ??= $StateTable(this); States get states => _states ??= States(this);
$ExperimentsTable _experiments; Experiments _experiments;
$ExperimentsTable get experiments => _experiments ??= $ExperimentsTable(this); Experiments get experiments => _experiments ??= Experiments(this);
SomeDao _someDao; SomeDao _someDao;
SomeDao get someDao => _someDao ??= SomeDao(this as TodoDb); SomeDao get someDao => _someDao ??= SomeDao(this as TodoDb);
AllTodosWithCategoryResult _rowToAllTodosWithCategoryResult(QueryRow row) { AllTodosWithCategoryResult _rowToAllTodosWithCategoryResult(QueryRow row) {
@ -1697,7 +1691,7 @@ abstract class _$TodoDb extends GeneratedDatabase {
sharedTodos, sharedTodos,
tableWithoutPK, tableWithoutPK,
pureDefaults, pureDefaults,
state, states,
experiments experiments
]; ];
} }

View File

@ -14,6 +14,10 @@ class SpecifiedTable {
/// of this table in generated Dart code. /// of this table in generated Dart code.
final String _overriddenName; final String _overriddenName;
/// Whether this table was created from an `ALTER TABLE` statement instead of
/// a Dart class.
bool get isFromSql => _overriddenName != null;
String get _baseName => _overriddenName ?? fromClass.name; String get _baseName => _overriddenName ?? fromClass.name;
/// The columns declared in this table. /// The columns declared in this table.
@ -25,8 +29,18 @@ class SpecifiedTable {
/// The name for the data class associated with this table /// The name for the data class associated with this table
final String dartTypeName; final String dartTypeName;
String get tableFieldName => ReCase(_baseName).camelCase; String get tableFieldName => _dbFieldName(_baseName);
String get tableInfoName => tableInfoNameForTableClass(_baseName); String get tableInfoName {
// if this table was parsed from sql, a user might want to refer to it
// directly because there is no user defined parent class.
// So, turn CREATE TABLE users into something called "Users" instead of
// "$UsersTable".
if (_overriddenName != null) {
return _overriddenName;
}
return tableInfoNameForTableClass(_baseName);
}
String get updateCompanionName => _updateCompanionName(_baseName); String get updateCompanionName => _updateCompanionName(_baseName);
/// The set of primary keys, if they have been explicitly defined by /// The set of primary keys, if they have been explicitly defined by
@ -48,6 +62,8 @@ class SpecifiedTable {
columns.map((c) => c.typeConverter).where((t) => t != null); columns.map((c) => c.typeConverter).where((t) => t != null);
} }
String _dbFieldName(String className) => ReCase(className).camelCase;
String tableInfoNameForTableClass(String className) => '\$${className}Table'; String tableInfoNameForTableClass(String className) => '\$${className}Table';
String _updateCompanionName(String className) => '${className}Companion'; String _updateCompanionName(String className) => '${className}Companion';

View File

@ -79,13 +79,13 @@ class CreateTable {
final tableName = table.name; final tableName = table.name;
final dartTableName = ReCase(tableName).pascalCase; final dartTableName = ReCase(tableName).pascalCase;
// todo respect WITHOUT ROWID clause and table constraints // todo include WITHOUT ROWID clause and table constraints
return SpecifiedTable( return SpecifiedTable(
fromClass: null, fromClass: null,
columns: foundColumns.values.toList(), columns: foundColumns.values.toList(),
sqlName: table.name, sqlName: table.name,
dartTypeName: dataClassNameForClassName(dartTableName), dartTypeName: dataClassNameForClassName(dartTableName),
overriddenName: dartTableName, overriddenName: ReCase(tableName).pascalCase,
primaryKey: primaryKey, primaryKey: primaryKey,
); );
} }

View File

@ -16,7 +16,16 @@ class UseDaoParser {
annotation.peek('tables').listValue.map((obj) => obj.toTypeValue()); annotation.peek('tables').listValue.map((obj) => obj.toTypeValue());
final queryStrings = annotation.peek('queries')?.mapValue ?? {}; final queryStrings = annotation.peek('queries')?.mapValue ?? {};
final includes = annotation
.read('include')
.objectValue
.toSetValue()
?.map((e) => e.toStringValue()) ??
{};
final parsedTables = await session.parseTables(tableTypes, element); final parsedTables = await session.parseTables(tableTypes, element);
parsedTables.addAll(await session.resolveIncludes(includes));
final parsedQueries = final parsedQueries =
await session.parseQueries(queryStrings, parsedTables); await session.parseQueries(queryStrings, parsedTables);

View File

@ -174,7 +174,9 @@ class TableWriter {
getterName: column.dartGetterName, getterName: column.dartGetterName,
returnType: column.implColumnTypeName, returnType: column.implColumnTypeName,
code: expressionBuffer.toString(), code: expressionBuffer.toString(),
hasOverride: true, // don't override on custom tables because we only override the column
// when the base class is user defined
hasOverride: !table.isFromSql,
); );
} }