mirror of https://github.com/AMT-Cheif/drift.git
Remove some moor references in drift_dev
This commit is contained in:
parent
116f98269d
commit
388b31e9ea
|
@ -3,7 +3,7 @@
|
||||||
part of 'main.dart';
|
part of 'main.dart';
|
||||||
|
|
||||||
// **************************************************************************
|
// **************************************************************************
|
||||||
// MoorGenerator
|
// DriftDatabaseGenerator
|
||||||
// **************************************************************************
|
// **************************************************************************
|
||||||
|
|
||||||
// ignore_for_file: type=lint
|
// ignore_for_file: type=lint
|
||||||
|
|
|
@ -3,7 +3,7 @@
|
||||||
part of 'custom_tables.dart';
|
part of 'custom_tables.dart';
|
||||||
|
|
||||||
// **************************************************************************
|
// **************************************************************************
|
||||||
// MoorGenerator
|
// DriftDatabaseGenerator
|
||||||
// **************************************************************************
|
// **************************************************************************
|
||||||
|
|
||||||
// ignore_for_file: type=lint
|
// ignore_for_file: type=lint
|
||||||
|
|
|
@ -3,7 +3,7 @@
|
||||||
part of 'todos.dart';
|
part of 'todos.dart';
|
||||||
|
|
||||||
// **************************************************************************
|
// **************************************************************************
|
||||||
// MoorGenerator
|
// DriftDatabaseGenerator
|
||||||
// **************************************************************************
|
// **************************************************************************
|
||||||
|
|
||||||
// ignore_for_file: type=lint
|
// ignore_for_file: type=lint
|
||||||
|
|
|
@ -15,30 +15,30 @@ builders:
|
||||||
import: "package:drift_dev/integrations/build.dart"
|
import: "package:drift_dev/integrations/build.dart"
|
||||||
builder_factories: ["preparingBuilder"]
|
builder_factories: ["preparingBuilder"]
|
||||||
build_extensions:
|
build_extensions:
|
||||||
".moor": [".temp.dart", ".dart_in_moor"]
|
".moor": [".temp.dart", ".dart_in_drift"]
|
||||||
".drift": [".temp.dart", ".dart_in_moor"]
|
".drift": [".temp.dart", ".dart_in_drift"]
|
||||||
build_to: cache
|
build_to: cache
|
||||||
auto_apply: dependents
|
auto_apply: dependents
|
||||||
applies_builders: ["drift_dev|cleanup"]
|
applies_builders: ["drift_dev:cleanup"]
|
||||||
|
|
||||||
drift_dev:
|
drift_dev:
|
||||||
import: "package:drift_dev/integrations/build.dart"
|
import: "package:drift_dev/integrations/build.dart"
|
||||||
builder_factories: ["moorBuilder"]
|
builder_factories: ["driftBuilder"]
|
||||||
build_extensions: {".dart": [".moor.g.part"]}
|
build_extensions: {".dart": [".moor.g.part"]}
|
||||||
auto_apply: dependents
|
auto_apply: dependents
|
||||||
build_to: cache
|
build_to: cache
|
||||||
required_inputs: [".dart_in_moor"]
|
required_inputs: [".dart_in_drift"]
|
||||||
applies_builders: ["source_gen|combining_builder"]
|
applies_builders: ["source_gen:combining_builder"]
|
||||||
|
|
||||||
not_shared:
|
not_shared:
|
||||||
import: "package:drift_dev/integrations/build.dart"
|
import: "package:drift_dev/integrations/build.dart"
|
||||||
builder_factories: ["moorBuilderNotShared"]
|
builder_factories: ["driftBuilderNotShared"]
|
||||||
build_extensions: {".dart": [".drift.dart"]}
|
build_extensions: {".dart": [".drift.dart"]}
|
||||||
build_to: source
|
build_to: source
|
||||||
auto_apply: none
|
auto_apply: none
|
||||||
required_inputs: [".dart_in_moor"]
|
required_inputs: [".dart_in_drift"]
|
||||||
|
|
||||||
post_process_builders:
|
post_process_builders:
|
||||||
cleanup:
|
cleanup:
|
||||||
import: "package:drift_dev/integrations/build.dart"
|
import: "package:drift_dev/integrations/build.dart"
|
||||||
builder_factory: "moorCleanup"
|
builder_factory: "driftCleanup"
|
||||||
|
|
|
@ -114,7 +114,7 @@ class _GenerateFromScratch extends GeneratedDatabase {
|
||||||
int get schemaVersion => 1;
|
int get schemaVersion => 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The implementation of this class is generated through the `moor_generator`
|
/// The implementation of this class is generated through the `drift_dev`
|
||||||
/// CLI tool.
|
/// CLI tool.
|
||||||
abstract class SchemaInstantiationHelper {
|
abstract class SchemaInstantiationHelper {
|
||||||
GeneratedDatabase databaseForVersion(QueryExecutor db, int version);
|
GeneratedDatabase databaseForVersion(QueryExecutor db, int version);
|
||||||
|
@ -180,14 +180,14 @@ class InitializedSchema {
|
||||||
///
|
///
|
||||||
/// All connections returned by this method point to the [rawDatabase].
|
/// All connections returned by this method point to the [rawDatabase].
|
||||||
/// However, each call to [newConnection] returns an independent connection
|
/// However, each call to [newConnection] returns an independent connection
|
||||||
/// that is considered closed from moor's point of view. This means that the
|
/// that is considered closed from drift's point of view. This means that the
|
||||||
/// [rawDatabase] can be used by multiple generated database classes that
|
/// [rawDatabase] can be used by multiple generated database classes that
|
||||||
/// can independently be opened and closed, albeit not simultaneously.
|
/// can independently be opened and closed, albeit not simultaneously.
|
||||||
///
|
///
|
||||||
/// ## Example
|
/// ## Example
|
||||||
///
|
///
|
||||||
/// When generating the schema helpers with the `--data-classes` and the
|
/// When generating the schema helpers with the `--data-classes` and the
|
||||||
/// `--companions` command-line flags, this method can be used to create moor
|
/// `--companions` command-line flags, this method can be used to create drift
|
||||||
/// databases inserting data at specific versions:
|
/// databases inserting data at specific versions:
|
||||||
///
|
///
|
||||||
/// ```dart
|
/// ```dart
|
||||||
|
|
|
@ -1,16 +1,16 @@
|
||||||
import 'package:build/build.dart';
|
import 'package:build/build.dart';
|
||||||
import 'package:drift_dev/src/backends/build/moor_builder.dart';
|
import 'package:drift_dev/src/backends/build/drift_builder.dart';
|
||||||
import 'package:drift_dev/src/backends/build/preprocess_builder.dart';
|
import 'package:drift_dev/src/backends/build/preprocess_builder.dart';
|
||||||
|
|
||||||
Builder moorBuilder(BuilderOptions options) =>
|
Builder driftBuilder(BuilderOptions options) =>
|
||||||
MoorSharedPartBuilder(options, isForNewDriftPackage: true);
|
DriftSharedPartBuilder(options, isForNewDriftPackage: true);
|
||||||
|
|
||||||
Builder moorBuilderNotShared(BuilderOptions options) =>
|
Builder driftBuilderNotShared(BuilderOptions options) =>
|
||||||
MoorPartBuilder(options, isForNewDriftPackage: true);
|
DriftPartBuilder(options, isForNewDriftPackage: true);
|
||||||
|
|
||||||
Builder preparingBuilder(BuilderOptions options) =>
|
Builder preparingBuilder(BuilderOptions options) =>
|
||||||
PreprocessBuilder(isForNewDriftPackage: true);
|
PreprocessBuilder(isForNewDriftPackage: true);
|
||||||
|
|
||||||
PostProcessBuilder moorCleanup(BuilderOptions options) {
|
PostProcessBuilder driftCleanup(BuilderOptions options) {
|
||||||
return const FileDeletingBuilder(['.temp.dart']);
|
return const FileDeletingBuilder(['.temp.dart']);
|
||||||
}
|
}
|
||||||
|
|
|
@ -4,5 +4,5 @@ import 'package:analyzer_plugin/starter.dart';
|
||||||
import 'package:drift_dev/src/backends/plugin/plugin.dart';
|
import 'package:drift_dev/src/backends/plugin/plugin.dart';
|
||||||
|
|
||||||
void start(List<String> args, SendPort sendPort) {
|
void start(List<String> args, SendPort sendPort) {
|
||||||
ServerPluginStarter(MoorPlugin.forProduction()).start(sendPort);
|
ServerPluginStarter(DriftPlugin.forProduction()).start(sendPort);
|
||||||
}
|
}
|
||||||
|
|
|
@ -58,11 +58,11 @@ const String _errorMessage = 'This getter does not create a valid column that '
|
||||||
/// the invocations on our way, we can extract the constraint for the column
|
/// the invocations on our way, we can extract the constraint for the column
|
||||||
/// (e.g. its name, whether it has auto increment, is a primary key and so on).
|
/// (e.g. its name, whether it has auto increment, is a primary key and so on).
|
||||||
class ColumnParser {
|
class ColumnParser {
|
||||||
final MoorDartParser base;
|
final DriftDartParser base;
|
||||||
|
|
||||||
ColumnParser(this.base);
|
ColumnParser(this.base);
|
||||||
|
|
||||||
MoorColumn? parse(MethodDeclaration getter, Element element) {
|
DriftColumn? parse(MethodDeclaration getter, Element element) {
|
||||||
final expr = base.returnExpressionOfMethod(getter);
|
final expr = base.returnExpressionOfMethod(getter);
|
||||||
|
|
||||||
if (expr is! FunctionExpressionInvocation) {
|
if (expr is! FunctionExpressionInvocation) {
|
||||||
|
@ -422,7 +422,7 @@ class ColumnParser {
|
||||||
|
|
||||||
final docString =
|
final docString =
|
||||||
getter.documentationComment?.tokens.map((t) => t.toString()).join('\n');
|
getter.documentationComment?.tokens.map((t) => t.toString()).join('\n');
|
||||||
return MoorColumn(
|
return DriftColumn(
|
||||||
type: columnType,
|
type: columnType,
|
||||||
dartGetterName: getter.name.name,
|
dartGetterName: getter.name.name,
|
||||||
name: name,
|
name: name,
|
||||||
|
|
|
@ -1,9 +1,9 @@
|
||||||
part of 'parser.dart';
|
part of 'parser.dart';
|
||||||
|
|
||||||
class UseMoorParser {
|
class DriftDatabaseParser {
|
||||||
final ParseDartStep step;
|
final ParseDartStep step;
|
||||||
|
|
||||||
UseMoorParser(this.step);
|
DriftDatabaseParser(this.step);
|
||||||
|
|
||||||
/// If [element] has a `@UseMoor` annotation, parses the database model
|
/// If [element] has a `@UseMoor` annotation, parses the database model
|
||||||
/// declared by that class and the referenced tables.
|
/// declared by that class and the referenced tables.
|
||||||
|
@ -69,7 +69,7 @@ class UseMoorParser {
|
||||||
final element = dbClass.thisType.getGetter('schemaVersion')?.variable;
|
final element = dbClass.thisType.getGetter('schemaVersion')?.variable;
|
||||||
if (element == null) return null;
|
if (element == null) return null;
|
||||||
|
|
||||||
final helper = MoorDartParser(step);
|
final helper = DriftDartParser(step);
|
||||||
|
|
||||||
if (element.isSynthetic) {
|
if (element.isSynthetic) {
|
||||||
// Getter, read from `=>` body if possible.
|
// Getter, read from `=>` body if possible.
|
|
@ -21,28 +21,28 @@ import '../dart_types.dart';
|
||||||
part 'column_parser.dart';
|
part 'column_parser.dart';
|
||||||
part 'table_parser.dart';
|
part 'table_parser.dart';
|
||||||
part 'use_dao_parser.dart';
|
part 'use_dao_parser.dart';
|
||||||
part 'use_moor_parser.dart';
|
part 'drift_database_parser.dart';
|
||||||
part 'view_parser.dart';
|
part 'view_parser.dart';
|
||||||
|
|
||||||
class MoorDartParser {
|
class DriftDartParser {
|
||||||
final ParseDartStep step;
|
final ParseDartStep step;
|
||||||
|
|
||||||
late ColumnParser _columnParser;
|
late ColumnParser _columnParser;
|
||||||
late TableParser _tableParser;
|
late TableParser _tableParser;
|
||||||
late ViewParser _viewParser;
|
late ViewParser _viewParser;
|
||||||
|
|
||||||
MoorDartParser(this.step) {
|
DriftDartParser(this.step) {
|
||||||
_columnParser = ColumnParser(this);
|
_columnParser = ColumnParser(this);
|
||||||
_tableParser = TableParser(this);
|
_tableParser = TableParser(this);
|
||||||
_viewParser = ViewParser(this);
|
_viewParser = ViewParser(this);
|
||||||
}
|
}
|
||||||
|
|
||||||
Future<MoorTable?> parseTable(ClassElement classElement) {
|
Future<DriftTable?> parseTable(ClassElement classElement) {
|
||||||
return _tableParser.parseTable(classElement);
|
return _tableParser.parseTable(classElement);
|
||||||
}
|
}
|
||||||
|
|
||||||
Future<MoorView?> parseView(
|
Future<MoorView?> parseView(
|
||||||
ClassElement classElement, List<MoorTable> tables) {
|
ClassElement classElement, List<DriftTable> tables) {
|
||||||
return _viewParser.parseView(classElement, tables);
|
return _viewParser.parseView(classElement, tables);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -50,7 +50,7 @@ class MoorDartParser {
|
||||||
///
|
///
|
||||||
/// When the column is invalid, an error will be logged and `null` is
|
/// When the column is invalid, an error will be logged and `null` is
|
||||||
/// returned.
|
/// returned.
|
||||||
Future<MoorColumn?> parseColumn(
|
Future<DriftColumn?> parseColumn(
|
||||||
MethodDeclaration declaration, Element element) {
|
MethodDeclaration declaration, Element element) {
|
||||||
return Future.value(_columnParser.parse(declaration, element));
|
return Future.value(_columnParser.parse(declaration, element));
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,12 +1,12 @@
|
||||||
part of 'parser.dart';
|
part of 'parser.dart';
|
||||||
|
|
||||||
/// Parses a [MoorTable] from a Dart class.
|
/// Parses a [DriftTable] from a Dart class.
|
||||||
class TableParser {
|
class TableParser {
|
||||||
final MoorDartParser base;
|
final DriftDartParser base;
|
||||||
|
|
||||||
TableParser(this.base);
|
TableParser(this.base);
|
||||||
|
|
||||||
Future<MoorTable?> parseTable(ClassElement element) async {
|
Future<DriftTable?> parseTable(ClassElement element) async {
|
||||||
final sqlName = await _parseTableName(element);
|
final sqlName = await _parseTableName(element);
|
||||||
if (sqlName == null) return null;
|
if (sqlName == null) return null;
|
||||||
|
|
||||||
|
@ -16,7 +16,7 @@ class TableParser {
|
||||||
|
|
||||||
final dataClassInfo = _readDataClassInformation(columns, element);
|
final dataClassInfo = _readDataClassInformation(columns, element);
|
||||||
|
|
||||||
final table = MoorTable(
|
final table = DriftTable(
|
||||||
fromClass: element,
|
fromClass: element,
|
||||||
columns: columns,
|
columns: columns,
|
||||||
sqlName: sqlName,
|
sqlName: sqlName,
|
||||||
|
@ -79,7 +79,7 @@ class TableParser {
|
||||||
}
|
}
|
||||||
|
|
||||||
_DataClassInformation _readDataClassInformation(
|
_DataClassInformation _readDataClassInformation(
|
||||||
List<MoorColumn> columns, ClassElement element) {
|
List<DriftColumn> columns, ClassElement element) {
|
||||||
DartObject? dataClassName;
|
DartObject? dataClassName;
|
||||||
DartObject? useRowClass;
|
DartObject? useRowClass;
|
||||||
|
|
||||||
|
@ -170,8 +170,8 @@ class TableParser {
|
||||||
return tableName;
|
return tableName;
|
||||||
}
|
}
|
||||||
|
|
||||||
Future<Set<MoorColumn>?> _readPrimaryKey(
|
Future<Set<DriftColumn>?> _readPrimaryKey(
|
||||||
ClassElement element, List<MoorColumn> columns) async {
|
ClassElement element, List<DriftColumn> columns) async {
|
||||||
final primaryKeyGetter =
|
final primaryKeyGetter =
|
||||||
element.lookUpGetter('primaryKey', element.library);
|
element.lookUpGetter('primaryKey', element.library);
|
||||||
|
|
||||||
|
@ -191,7 +191,7 @@ class TableParser {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
final expression = body.expression;
|
final expression = body.expression;
|
||||||
final parsedPrimaryKey = <MoorColumn>{};
|
final parsedPrimaryKey = <DriftColumn>{};
|
||||||
|
|
||||||
if (expression is SetOrMapLiteral) {
|
if (expression is SetOrMapLiteral) {
|
||||||
for (final entry in expression.elements) {
|
for (final entry in expression.elements) {
|
||||||
|
@ -222,8 +222,8 @@ class TableParser {
|
||||||
return parsedPrimaryKey;
|
return parsedPrimaryKey;
|
||||||
}
|
}
|
||||||
|
|
||||||
Future<List<Set<MoorColumn>>?> _readUniqueKeys(
|
Future<List<Set<DriftColumn>>?> _readUniqueKeys(
|
||||||
ClassElement element, List<MoorColumn> columns) async {
|
ClassElement element, List<DriftColumn> columns) async {
|
||||||
final uniqueKeyGetter = element.lookUpGetter('uniqueKeys', element.library);
|
final uniqueKeyGetter = element.lookUpGetter('uniqueKeys', element.library);
|
||||||
|
|
||||||
if (uniqueKeyGetter == null || uniqueKeyGetter.isFromDefaultTable) {
|
if (uniqueKeyGetter == null || uniqueKeyGetter.isFromDefaultTable) {
|
||||||
|
@ -243,12 +243,12 @@ class TableParser {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
final expression = body.expression;
|
final expression = body.expression;
|
||||||
final parsedUniqueKeys = <Set<MoorColumn>>[];
|
final parsedUniqueKeys = <Set<DriftColumn>>[];
|
||||||
|
|
||||||
if (expression is ListLiteral) {
|
if (expression is ListLiteral) {
|
||||||
for (final keySet in expression.elements) {
|
for (final keySet in expression.elements) {
|
||||||
if (keySet is SetOrMapLiteral) {
|
if (keySet is SetOrMapLiteral) {
|
||||||
final uniqueKey = <MoorColumn>{};
|
final uniqueKey = <DriftColumn>{};
|
||||||
for (final entry in keySet.elements) {
|
for (final entry in keySet.elements) {
|
||||||
if (entry is Identifier) {
|
if (entry is Identifier) {
|
||||||
final column = columns.singleWhereOrNull(
|
final column = columns.singleWhereOrNull(
|
||||||
|
@ -307,7 +307,7 @@ class TableParser {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
Future<Iterable<MoorColumn>> _parseColumns(ClassElement element) async {
|
Future<Iterable<DriftColumn>> _parseColumns(ClassElement element) async {
|
||||||
final columnNames = element.allSupertypes
|
final columnNames = element.allSupertypes
|
||||||
.map((t) => t.element)
|
.map((t) => t.element)
|
||||||
.followedBy([element])
|
.followedBy([element])
|
||||||
|
|
|
@ -2,12 +2,12 @@ part of 'parser.dart';
|
||||||
|
|
||||||
/// Parses a [MoorView] from a Dart class.
|
/// Parses a [MoorView] from a Dart class.
|
||||||
class ViewParser {
|
class ViewParser {
|
||||||
final MoorDartParser base;
|
final DriftDartParser base;
|
||||||
|
|
||||||
ViewParser(this.base);
|
ViewParser(this.base);
|
||||||
|
|
||||||
Future<MoorView?> parseView(
|
Future<MoorView?> parseView(
|
||||||
ClassElement element, List<MoorTable> tables) async {
|
ClassElement element, List<DriftTable> tables) async {
|
||||||
final name = await _parseViewName(element);
|
final name = await _parseViewName(element);
|
||||||
final columns = (await _parseColumns(element)).toList();
|
final columns = (await _parseColumns(element)).toList();
|
||||||
final staticReferences = await _parseStaticReferences(element, tables);
|
final staticReferences = await _parseStaticReferences(element, tables);
|
||||||
|
@ -34,7 +34,7 @@ class ViewParser {
|
||||||
}
|
}
|
||||||
|
|
||||||
_DataClassInformation _readDataClassInformation(
|
_DataClassInformation _readDataClassInformation(
|
||||||
List<MoorColumn> columns, ClassElement element) {
|
List<DriftColumn> columns, ClassElement element) {
|
||||||
DartObject? useRowClass;
|
DartObject? useRowClass;
|
||||||
DartObject? driftView;
|
DartObject? driftView;
|
||||||
String? customParentClass;
|
String? customParentClass;
|
||||||
|
@ -114,7 +114,7 @@ class ViewParser {
|
||||||
return ReCase(element.name).snakeCase;
|
return ReCase(element.name).snakeCase;
|
||||||
}
|
}
|
||||||
|
|
||||||
Future<Iterable<MoorColumn>> _parseColumns(ClassElement element) async {
|
Future<Iterable<DriftColumn>> _parseColumns(ClassElement element) async {
|
||||||
final columnNames = element.allSupertypes
|
final columnNames = element.allSupertypes
|
||||||
.map((t) => t.element)
|
.map((t) => t.element)
|
||||||
.followedBy([element])
|
.followedBy([element])
|
||||||
|
@ -154,7 +154,7 @@ class ViewParser {
|
||||||
await base.loadElementDeclaration(field.getter!) as MethodDeclaration;
|
await base.loadElementDeclaration(field.getter!) as MethodDeclaration;
|
||||||
final expression = (node.body as ExpressionFunctionBody).expression;
|
final expression = (node.body as ExpressionFunctionBody).expression;
|
||||||
|
|
||||||
return MoorColumn(
|
return DriftColumn(
|
||||||
type: sqlType,
|
type: sqlType,
|
||||||
dartGetterName: field.name,
|
dartGetterName: field.name,
|
||||||
name: ColumnName.implicitly(ReCase(field.name).snakeCase),
|
name: ColumnName.implicitly(ReCase(field.name).snakeCase),
|
||||||
|
@ -179,7 +179,7 @@ class ViewParser {
|
||||||
}
|
}
|
||||||
|
|
||||||
Future<List<TableReferenceInDartView>> _parseStaticReferences(
|
Future<List<TableReferenceInDartView>> _parseStaticReferences(
|
||||||
ClassElement element, List<MoorTable> tables) async {
|
ClassElement element, List<DriftTable> tables) async {
|
||||||
return await Stream.fromIterable(element.allSupertypes
|
return await Stream.fromIterable(element.allSupertypes
|
||||||
.map((t) => t.element)
|
.map((t) => t.element)
|
||||||
.followedBy([element]).expand((e) => e.fields))
|
.followedBy([element]).expand((e) => e.fields))
|
||||||
|
@ -190,7 +190,7 @@ class ViewParser {
|
||||||
}
|
}
|
||||||
|
|
||||||
Future<TableReferenceInDartView?> _getStaticReference(
|
Future<TableReferenceInDartView?> _getStaticReference(
|
||||||
FieldElement field, List<MoorTable> tables) async {
|
FieldElement field, List<DriftTable> tables) async {
|
||||||
if (field.getter != null) {
|
if (field.getter != null) {
|
||||||
try {
|
try {
|
||||||
final node = await base.loadElementDeclaration(field.getter!);
|
final node = await base.loadElementDeclaration(field.getter!);
|
||||||
|
@ -210,7 +210,7 @@ class ViewParser {
|
||||||
Future<ViewQueryInformation> _parseQuery(
|
Future<ViewQueryInformation> _parseQuery(
|
||||||
ClassElement element,
|
ClassElement element,
|
||||||
List<TableReferenceInDartView> references,
|
List<TableReferenceInDartView> references,
|
||||||
List<MoorColumn> columns) async {
|
List<DriftColumn> columns) async {
|
||||||
final as =
|
final as =
|
||||||
element.methods.where((method) => method.name == 'as').firstOrNull;
|
element.methods.where((method) => method.name == 'as').firstOrNull;
|
||||||
|
|
||||||
|
|
|
@ -21,7 +21,7 @@ class FoundDartClass {
|
||||||
}
|
}
|
||||||
|
|
||||||
ExistingRowClass? validateExistingClass(
|
ExistingRowClass? validateExistingClass(
|
||||||
Iterable<MoorColumn> columns,
|
Iterable<DriftColumn> columns,
|
||||||
FoundDartClass dartClass,
|
FoundDartClass dartClass,
|
||||||
String constructor,
|
String constructor,
|
||||||
bool generateInsertable,
|
bool generateInsertable,
|
||||||
|
@ -61,7 +61,7 @@ ExistingRowClass? validateExistingClass(
|
||||||
for (final column in columns) column.dartGetterName: column
|
for (final column in columns) column.dartGetterName: column
|
||||||
};
|
};
|
||||||
|
|
||||||
final columnsToParameter = <MoorColumn, ParameterElement>{};
|
final columnsToParameter = <DriftColumn, ParameterElement>{};
|
||||||
|
|
||||||
for (final parameter in ctor.parameters) {
|
for (final parameter in ctor.parameters) {
|
||||||
final column = unmatchedColumnsByName.remove(parameter.name);
|
final column = unmatchedColumnsByName.remove(parameter.name);
|
||||||
|
@ -170,7 +170,7 @@ UsedTypeConverter? readTypeConverter(
|
||||||
}
|
}
|
||||||
|
|
||||||
void _checkParameterType(
|
void _checkParameterType(
|
||||||
ParameterElement element, MoorColumn column, Step step) {
|
ParameterElement element, DriftColumn column, Step step) {
|
||||||
final type = element.type;
|
final type = element.type;
|
||||||
final library = element.library!;
|
final library = element.library!;
|
||||||
final typesystem = library.typeSystem;
|
final typesystem = library.typeSystem;
|
||||||
|
|
|
@ -23,7 +23,7 @@ String dataClassNameForClassName(String tableName) {
|
||||||
}
|
}
|
||||||
|
|
||||||
String? parseCustomParentClass(String dartTypeName, DartObject dataClassName,
|
String? parseCustomParentClass(String dartTypeName, DartObject dataClassName,
|
||||||
ClassElement element, MoorDartParser base) {
|
ClassElement element, DriftDartParser base) {
|
||||||
final extending = dataClassName.getField('extending');
|
final extending = dataClassName.getField('extending');
|
||||||
if (extending != null && !extending.isNull) {
|
if (extending != null && !extending.isNull) {
|
||||||
final extendingType = extending.toTypeValue();
|
final extendingType = extending.toTypeValue();
|
||||||
|
|
|
@ -30,13 +30,13 @@ class CreateTableReader {
|
||||||
CreateTableReader(this.stmt, this.step, this.helper,
|
CreateTableReader(this.stmt, this.step, this.helper,
|
||||||
[this.imports = const []]);
|
[this.imports = const []]);
|
||||||
|
|
||||||
Future<MoorTable?> extractTable(TypeMapper mapper) async {
|
Future<DriftTable?> extractTable(TypeMapper mapper) async {
|
||||||
Table table;
|
Table table;
|
||||||
try {
|
try {
|
||||||
table = _schemaReader.read(stmt);
|
table = _schemaReader.read(stmt);
|
||||||
} catch (e, s) {
|
} catch (e, s) {
|
||||||
print(s);
|
print(s);
|
||||||
step.reportError(ErrorInMoorFile(
|
step.reportError(ErrorInDriftFile(
|
||||||
span: stmt.tableNameToken!.span,
|
span: stmt.tableNameToken!.span,
|
||||||
message: 'Could not extract schema information for this table: $e',
|
message: 'Could not extract schema information for this table: $e',
|
||||||
));
|
));
|
||||||
|
@ -44,8 +44,8 @@ class CreateTableReader {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
final foundColumns = <String, MoorColumn>{};
|
final foundColumns = <String, DriftColumn>{};
|
||||||
Set<MoorColumn>? primaryKeyFromTableConstraint;
|
Set<DriftColumn>? primaryKeyFromTableConstraint;
|
||||||
|
|
||||||
for (final column in table.resultColumns) {
|
for (final column in table.resultColumns) {
|
||||||
final features = <ColumnFeature>[];
|
final features = <ColumnFeature>[];
|
||||||
|
@ -68,7 +68,7 @@ class CreateTableReader {
|
||||||
final dartType = await _readDartType(dartTypeName);
|
final dartType = await _readDartType(dartTypeName);
|
||||||
|
|
||||||
if (dartType == null) {
|
if (dartType == null) {
|
||||||
step.reportError(ErrorInMoorFile(
|
step.reportError(ErrorInDriftFile(
|
||||||
message: 'Type $dartTypeName could not be found. Are you missing '
|
message: 'Type $dartTypeName could not be found. Are you missing '
|
||||||
'an import?',
|
'an import?',
|
||||||
severity: Severity.error,
|
severity: Severity.error,
|
||||||
|
@ -82,7 +82,7 @@ class CreateTableReader {
|
||||||
helper.helperLibrary.typeProvider,
|
helper.helperLibrary.typeProvider,
|
||||||
);
|
);
|
||||||
} on InvalidTypeForEnumConverterException catch (e) {
|
} on InvalidTypeForEnumConverterException catch (e) {
|
||||||
step.reportError(ErrorInMoorFile(
|
step.reportError(ErrorInDriftFile(
|
||||||
message: e.errorDescription,
|
message: e.errorDescription,
|
||||||
severity: Severity.error,
|
severity: Severity.error,
|
||||||
span: column.definition!.typeNames!.span,
|
span: column.definition!.typeNames!.span,
|
||||||
|
@ -112,7 +112,7 @@ class CreateTableReader {
|
||||||
if (constraint is MappedBy) {
|
if (constraint is MappedBy) {
|
||||||
if (converter != null) {
|
if (converter != null) {
|
||||||
// Already has a converter from an ENUM type
|
// Already has a converter from an ENUM type
|
||||||
step.reportError(ErrorInMoorFile(
|
step.reportError(ErrorInDriftFile(
|
||||||
message: 'This column has an ENUM type, which implicitly creates '
|
message: 'This column has an ENUM type, which implicitly creates '
|
||||||
"a type converter. You can't apply another converter to such "
|
"a type converter. You can't apply another converter to such "
|
||||||
'column. ',
|
'column. ',
|
||||||
|
@ -148,13 +148,13 @@ class CreateTableReader {
|
||||||
// if the column definition isn't set - which can happen for CREATE
|
// if the column definition isn't set - which can happen for CREATE
|
||||||
// VIRTUAL TABLE statements - use the entire statement as declaration.
|
// VIRTUAL TABLE statements - use the entire statement as declaration.
|
||||||
final declaration =
|
final declaration =
|
||||||
MoorColumnDeclaration(column.definition ?? stmt, step.file);
|
DriftColumnDeclaration(column.definition ?? stmt, step.file);
|
||||||
|
|
||||||
if (converter != null) {
|
if (converter != null) {
|
||||||
column.applyTypeHint(TypeConverterHint(converter));
|
column.applyTypeHint(TypeConverterHint(converter));
|
||||||
}
|
}
|
||||||
|
|
||||||
final parsed = MoorColumn(
|
final parsed = DriftColumn(
|
||||||
type: moorType,
|
type: moorType,
|
||||||
nullable: column.type.nullable != false,
|
nullable: column.type.nullable != false,
|
||||||
dartGetterName: overriddenDartName ?? dartName,
|
dartGetterName: overriddenDartName ?? dartName,
|
||||||
|
@ -182,7 +182,7 @@ class CreateTableReader {
|
||||||
if (moorTableInfo.useExistingDartClass) {
|
if (moorTableInfo.useExistingDartClass) {
|
||||||
final clazz = await findDartClass(step, imports, overriddenNames);
|
final clazz = await findDartClass(step, imports, overriddenNames);
|
||||||
if (clazz == null) {
|
if (clazz == null) {
|
||||||
step.reportError(ErrorInMoorFile(
|
step.reportError(ErrorInDriftFile(
|
||||||
span: stmt.tableNameToken!.span,
|
span: stmt.tableNameToken!.span,
|
||||||
message: 'Existing Dart class $overriddenNames was not found, are '
|
message: 'Existing Dart class $overriddenNames was not found, are '
|
||||||
'you missing an import?',
|
'you missing an import?',
|
||||||
|
@ -221,7 +221,7 @@ class CreateTableReader {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
final moorTable = MoorTable(
|
final moorTable = DriftTable(
|
||||||
fromClass: null,
|
fromClass: null,
|
||||||
columns: foundColumns.values.toList(),
|
columns: foundColumns.values.toList(),
|
||||||
sqlName: table.name,
|
sqlName: table.name,
|
||||||
|
@ -232,14 +232,14 @@ class CreateTableReader {
|
||||||
overrideTableConstraints: constraints.isNotEmpty ? constraints : null,
|
overrideTableConstraints: constraints.isNotEmpty ? constraints : null,
|
||||||
// we take care of writing the primary key ourselves
|
// we take care of writing the primary key ourselves
|
||||||
overrideDontWriteConstraints: true,
|
overrideDontWriteConstraints: true,
|
||||||
declaration: MoorTableDeclaration(stmt, step.file),
|
declaration: DriftTableDeclaration(stmt, step.file),
|
||||||
existingRowClass: existingRowClass,
|
existingRowClass: existingRowClass,
|
||||||
isStrict: table.isStrict,
|
isStrict: table.isStrict,
|
||||||
)..parserTable = table;
|
)..parserTable = table;
|
||||||
|
|
||||||
// Having a mapping from parser table to moor tables helps with IDE features
|
// Having a mapping from parser table to moor tables helps with IDE features
|
||||||
// like "go to definition"
|
// like "go to definition"
|
||||||
table.setMeta<MoorTable>(moorTable);
|
table.setMeta<DriftTable>(moorTable);
|
||||||
|
|
||||||
return moorTable;
|
return moorTable;
|
||||||
}
|
}
|
||||||
|
@ -255,7 +255,7 @@ class CreateTableReader {
|
||||||
code,
|
code,
|
||||||
imports.map((e) => e.importedFile).where((e) => e.endsWith('.dart')));
|
imports.map((e) => e.importedFile).where((e) => e.endsWith('.dart')));
|
||||||
} on CannotReadExpressionException catch (e) {
|
} on CannotReadExpressionException catch (e) {
|
||||||
step.reportError(ErrorInMoorFile(span: mapper.span!, message: e.msg));
|
step.reportError(ErrorInDriftFile(span: mapper.span!, message: e.msg));
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -265,7 +265,7 @@ class CreateTableReader {
|
||||||
sqlType,
|
sqlType,
|
||||||
nullable,
|
nullable,
|
||||||
(errorMsg) => step
|
(errorMsg) => step
|
||||||
.reportError(ErrorInMoorFile(span: mapper.span!, message: errorMsg)),
|
.reportError(ErrorInDriftFile(span: mapper.span!, message: errorMsg)),
|
||||||
helper,
|
helper,
|
||||||
);
|
);
|
||||||
}
|
}
|
|
@ -9,16 +9,16 @@ import 'package:sqlparser/utils/find_referenced_tables.dart';
|
||||||
|
|
||||||
/// Handles `REFERENCES` clauses in tables by resolving their columns and
|
/// Handles `REFERENCES` clauses in tables by resolving their columns and
|
||||||
/// reporting errors if they don't exist. Further, sets the
|
/// reporting errors if they don't exist. Further, sets the
|
||||||
/// [MoorTable.references] field for tables declared in moor.
|
/// [DriftTable.references] field for tables declared in moor.
|
||||||
class EntityHandler extends BaseAnalyzer {
|
class EntityHandler extends BaseAnalyzer {
|
||||||
final ParsedMoorFile file;
|
final ParsedDriftFile file;
|
||||||
|
|
||||||
AnalyzeMoorStep get moorStep => step as AnalyzeMoorStep;
|
AnalyzeMoorStep get moorStep => step as AnalyzeMoorStep;
|
||||||
|
|
||||||
EntityHandler(
|
EntityHandler(
|
||||||
AnalyzeMoorStep step,
|
AnalyzeMoorStep step,
|
||||||
this.file,
|
this.file,
|
||||||
List<MoorTable> availableTables,
|
List<DriftTable> availableTables,
|
||||||
) :
|
) :
|
||||||
// we'll analyze views later, so pass an empty list for now. Otherwise
|
// we'll analyze views later, so pass an empty list for now. Otherwise
|
||||||
// the incomplete views would be added to the engine.
|
// the incomplete views would be added to the engine.
|
||||||
|
@ -27,17 +27,17 @@ class EntityHandler extends BaseAnalyzer {
|
||||||
}
|
}
|
||||||
|
|
||||||
final Map<CreateTriggerStatement, MoorTrigger> _triggers = {};
|
final Map<CreateTriggerStatement, MoorTrigger> _triggers = {};
|
||||||
final Map<TableInducingStatement, MoorTable> _tables = {};
|
final Map<TableInducingStatement, DriftTable> _tables = {};
|
||||||
final Map<CreateIndexStatement, MoorIndex> _indexes = {};
|
final Map<CreateIndexStatement, MoorIndex> _indexes = {};
|
||||||
|
|
||||||
late _ReferenceResolvingVisitor _referenceResolver;
|
late _ReferenceResolvingVisitor _referenceResolver;
|
||||||
|
|
||||||
void handle() {
|
void handle() {
|
||||||
for (final entity in file.declaredEntities) {
|
for (final entity in file.declaredEntities) {
|
||||||
if (entity is MoorTable) {
|
if (entity is DriftTable) {
|
||||||
entity.references.clear();
|
entity.references.clear();
|
||||||
final node =
|
final node =
|
||||||
_handleMoorDeclaration<MoorTableDeclaration>(entity, _tables);
|
_handleMoorDeclaration<DriftTableDeclaration>(entity, _tables);
|
||||||
_lint(node, entity.sqlName);
|
_lint(node, entity.sqlName);
|
||||||
} else if (entity is MoorTrigger) {
|
} else if (entity is MoorTrigger) {
|
||||||
entity.clearResolvedReferences();
|
entity.clearResolvedReferences();
|
||||||
|
@ -55,9 +55,9 @@ class EntityHandler extends BaseAnalyzer {
|
||||||
} else if (entity is MoorIndex) {
|
} else if (entity is MoorIndex) {
|
||||||
entity.table = null;
|
entity.table = null;
|
||||||
|
|
||||||
_handleMoorDeclaration<MoorIndexDeclaration>(entity, _indexes);
|
_handleMoorDeclaration<DriftIndexDeclaration>(entity, _indexes);
|
||||||
} else if (entity is SpecialQuery) {
|
} else if (entity is SpecialQuery) {
|
||||||
final node = (entity.declaration as MoorSpecialQueryDeclaration).node;
|
final node = (entity.declaration as DriftSpecialQueryDeclaration).node;
|
||||||
|
|
||||||
_lint(node, 'special @create table');
|
_lint(node, 'special @create table');
|
||||||
entity.references.addAll(_findTables(node.statement));
|
entity.references.addAll(_findTables(node.statement));
|
||||||
|
@ -73,7 +73,7 @@ class EntityHandler extends BaseAnalyzer {
|
||||||
lintContext(context, displayName);
|
lintContext(context, displayName);
|
||||||
}
|
}
|
||||||
|
|
||||||
Iterable<MoorTable> _findTables(AstNode node) {
|
Iterable<DriftTable> _findTables(AstNode node) {
|
||||||
return findReferences(node, includeViews: false).cast();
|
return findReferences(node, includeViews: false).cast();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -83,7 +83,7 @@ class EntityHandler extends BaseAnalyzer {
|
||||||
return finder.writtenTables.map(mapper.writtenToMoor);
|
return finder.writtenTables.map(mapper.writtenToMoor);
|
||||||
}
|
}
|
||||||
|
|
||||||
AstNode _handleMoorDeclaration<T extends MoorDeclaration>(
|
AstNode _handleMoorDeclaration<T extends DriftFileDeclaration>(
|
||||||
HasDeclaration e,
|
HasDeclaration e,
|
||||||
Map<AstNode, HasDeclaration> map,
|
Map<AstNode, HasDeclaration> map,
|
||||||
) {
|
) {
|
||||||
|
@ -94,7 +94,7 @@ class EntityHandler extends BaseAnalyzer {
|
||||||
return declaration.node;
|
return declaration.node;
|
||||||
}
|
}
|
||||||
|
|
||||||
MoorTable? _inducedTable(TableInducingStatement stmt) {
|
DriftTable? _inducedTable(TableInducingStatement stmt) {
|
||||||
return _tables[stmt];
|
return _tables[stmt];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -112,7 +112,7 @@ class _ReferenceResolvingVisitor extends RecursiveVisitor<void, void> {
|
||||||
|
|
||||||
_ReferenceResolvingVisitor(this.handler);
|
_ReferenceResolvingVisitor(this.handler);
|
||||||
|
|
||||||
MoorTable? _resolveTable(TableReference reference) {
|
DriftTable? _resolveTable(TableReference reference) {
|
||||||
return handler.tables
|
return handler.tables
|
||||||
.firstWhereOrNull((t) => t.sqlName == reference.tableName);
|
.firstWhereOrNull((t) => t.sqlName == reference.tableName);
|
||||||
}
|
}
|
||||||
|
@ -121,7 +121,7 @@ class _ReferenceResolvingVisitor extends RecursiveVisitor<void, void> {
|
||||||
void visitCreateTriggerStatement(CreateTriggerStatement e, void arg) {
|
void visitCreateTriggerStatement(CreateTriggerStatement e, void arg) {
|
||||||
final table = _resolveTable(e.onTable);
|
final table = _resolveTable(e.onTable);
|
||||||
if (table == null) {
|
if (table == null) {
|
||||||
handler.step.reportError(ErrorInMoorFile(
|
handler.step.reportError(ErrorInDriftFile(
|
||||||
severity: Severity.error,
|
severity: Severity.error,
|
||||||
span: e.onTable.span!,
|
span: e.onTable.span!,
|
||||||
message: 'Target table ${e.onTable.tableName} could not be found.',
|
message: 'Target table ${e.onTable.tableName} could not be found.',
|
||||||
|
@ -136,7 +136,7 @@ class _ReferenceResolvingVisitor extends RecursiveVisitor<void, void> {
|
||||||
void visitCreateIndexStatement(CreateIndexStatement e, void arg) {
|
void visitCreateIndexStatement(CreateIndexStatement e, void arg) {
|
||||||
final table = _resolveTable(e.on);
|
final table = _resolveTable(e.on);
|
||||||
if (table == null) {
|
if (table == null) {
|
||||||
handler.step.reportError(ErrorInMoorFile(
|
handler.step.reportError(ErrorInDriftFile(
|
||||||
severity: Severity.error,
|
severity: Severity.error,
|
||||||
span: e.on.span!,
|
span: e.on.span!,
|
||||||
message: 'Target table ${e.on.tableName} could not be found.',
|
message: 'Target table ${e.on.tableName} could not be found.',
|
||||||
|
@ -153,7 +153,7 @@ class _ReferenceResolvingVisitor extends RecursiveVisitor<void, void> {
|
||||||
final referencedTable = _resolveTable(clause.foreignTable);
|
final referencedTable = _resolveTable(clause.foreignTable);
|
||||||
|
|
||||||
if (referencedTable == null) {
|
if (referencedTable == null) {
|
||||||
handler.step.reportError(ErrorInMoorFile(
|
handler.step.reportError(ErrorInDriftFile(
|
||||||
severity: Severity.error,
|
severity: Severity.error,
|
||||||
span: clause.span!,
|
span: clause.span!,
|
||||||
message:
|
message:
|
|
@ -1,6 +1,6 @@
|
||||||
import 'package:drift_dev/moor_generator.dart';
|
import 'package:drift_dev/moor_generator.dart';
|
||||||
|
import 'package:drift_dev/src/analyzer/drift/create_table_reader.dart';
|
||||||
import 'package:drift_dev/src/analyzer/errors.dart';
|
import 'package:drift_dev/src/analyzer/errors.dart';
|
||||||
import 'package:drift_dev/src/analyzer/moor/create_table_reader.dart';
|
|
||||||
import 'package:drift_dev/src/analyzer/runner/results.dart';
|
import 'package:drift_dev/src/analyzer/runner/results.dart';
|
||||||
import 'package:drift_dev/src/analyzer/runner/steps.dart';
|
import 'package:drift_dev/src/analyzer/runner/steps.dart';
|
||||||
import 'package:sqlparser/sqlparser.dart';
|
import 'package:sqlparser/sqlparser.dart';
|
||||||
|
@ -13,7 +13,7 @@ class MoorParser {
|
||||||
|
|
||||||
MoorParser(this.step, this.helper);
|
MoorParser(this.step, this.helper);
|
||||||
|
|
||||||
Future<ParsedMoorFile> parseAndAnalyze() async {
|
Future<ParsedDriftFile> parseAndAnalyze() async {
|
||||||
final engine = step.task.session.spawnEngine();
|
final engine = step.task.session.spawnEngine();
|
||||||
final result = engine.parseDriftFile(step.content);
|
final result = engine.parseDriftFile(step.content);
|
||||||
final parsedFile = result.rootNode as DriftFile;
|
final parsedFile = result.rootNode as DriftFile;
|
||||||
|
@ -22,7 +22,7 @@ class MoorParser {
|
||||||
final queryDeclarations = <DeclaredMoorQuery>[];
|
final queryDeclarations = <DeclaredMoorQuery>[];
|
||||||
final importStatements = <ImportStatement>[];
|
final importStatements = <ImportStatement>[];
|
||||||
|
|
||||||
final createdEntities = <MoorSchemaEntity>[];
|
final createdEntities = <DriftSchemaEntity>[];
|
||||||
|
|
||||||
for (final parsedStmt in parsedFile.statements) {
|
for (final parsedStmt in parsedFile.statements) {
|
||||||
if (parsedStmt is ImportStatement) {
|
if (parsedStmt is ImportStatement) {
|
||||||
|
@ -48,7 +48,7 @@ class MoorParser {
|
||||||
parsedStmt.identifier as SpecialStatementIdentifier;
|
parsedStmt.identifier as SpecialStatementIdentifier;
|
||||||
if (identifier.specialName != 'create') {
|
if (identifier.specialName != 'create') {
|
||||||
step.reportError(
|
step.reportError(
|
||||||
ErrorInMoorFile(
|
ErrorInDriftFile(
|
||||||
span: identifier.nameToken!.span,
|
span: identifier.nameToken!.span,
|
||||||
message: 'Only @create is supported at the moment.',
|
message: 'Only @create is supported at the moment.',
|
||||||
),
|
),
|
||||||
|
@ -61,7 +61,7 @@ class MoorParser {
|
||||||
}
|
}
|
||||||
|
|
||||||
for (final error in result.errors) {
|
for (final error in result.errors) {
|
||||||
step.reportError(ErrorInMoorFile(
|
step.reportError(ErrorInDriftFile(
|
||||||
severity: Severity.error,
|
severity: Severity.error,
|
||||||
span: error.token.span,
|
span: error.token.span,
|
||||||
message: error.message,
|
message: error.message,
|
||||||
|
@ -75,7 +75,7 @@ class MoorParser {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
final analyzedFile = ParsedMoorFile(
|
final analyzedFile = ParsedDriftFile(
|
||||||
result,
|
result,
|
||||||
declaredEntities: createdEntities,
|
declaredEntities: createdEntities,
|
||||||
queries: queryDeclarations,
|
queries: queryDeclarations,
|
|
@ -9,13 +9,13 @@ typedef LogFunction = void Function(dynamic message,
|
||||||
[Object? error, StackTrace? stackTrace]);
|
[Object? error, StackTrace? stackTrace]);
|
||||||
|
|
||||||
/// Base class for errors that can be presented to a user.
|
/// Base class for errors that can be presented to a user.
|
||||||
class MoorError {
|
class DriftError {
|
||||||
final Severity severity;
|
final Severity severity;
|
||||||
final String message;
|
final String message;
|
||||||
|
|
||||||
bool wasDuringParsing = true;
|
bool wasDuringParsing = true;
|
||||||
|
|
||||||
MoorError({required this.severity, required this.message});
|
DriftError({required this.severity, required this.message});
|
||||||
|
|
||||||
bool get isError =>
|
bool get isError =>
|
||||||
severity == Severity.criticalError || severity == Severity.error;
|
severity == Severity.criticalError || severity == Severity.error;
|
||||||
|
@ -32,7 +32,7 @@ class MoorError {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
class ErrorInDartCode extends MoorError {
|
class ErrorInDartCode extends DriftError {
|
||||||
final Element? affectedElement;
|
final Element? affectedElement;
|
||||||
final dart.AstNode? affectedNode;
|
final dart.AstNode? affectedNode;
|
||||||
|
|
||||||
|
@ -77,16 +77,16 @@ class ErrorInDartCode extends MoorError {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
class ErrorInMoorFile extends MoorError {
|
class ErrorInDriftFile extends DriftError {
|
||||||
final FileSpan span;
|
final FileSpan span;
|
||||||
|
|
||||||
ErrorInMoorFile(
|
ErrorInDriftFile(
|
||||||
{required this.span,
|
{required this.span,
|
||||||
required String message,
|
required String message,
|
||||||
Severity severity = Severity.warning})
|
Severity severity = Severity.warning})
|
||||||
: super(message: message, severity: severity);
|
: super(message: message, severity: severity);
|
||||||
|
|
||||||
factory ErrorInMoorFile.fromSqlParser(AnalysisError error,
|
factory ErrorInDriftFile.fromSqlParser(AnalysisError error,
|
||||||
{Severity? overrideSeverity}) {
|
{Severity? overrideSeverity}) {
|
||||||
// Describe how to change the sqlite version for errors caused by a wrong
|
// Describe how to change the sqlite version for errors caused by a wrong
|
||||||
// version
|
// version
|
||||||
|
@ -99,7 +99,7 @@ class ErrorInMoorFile extends MoorError {
|
||||||
final defaultSeverity =
|
final defaultSeverity =
|
||||||
error.type == AnalysisErrorType.hint ? Severity.hint : Severity.error;
|
error.type == AnalysisErrorType.hint ? Severity.hint : Severity.error;
|
||||||
|
|
||||||
return ErrorInMoorFile(
|
return ErrorInDriftFile(
|
||||||
span: error.span!,
|
span: error.span!,
|
||||||
message: msg,
|
message: msg,
|
||||||
severity: overrideSeverity ?? defaultSeverity,
|
severity: overrideSeverity ?? defaultSeverity,
|
||||||
|
@ -113,10 +113,10 @@ class ErrorInMoorFile extends MoorError {
|
||||||
}
|
}
|
||||||
|
|
||||||
class ErrorSink {
|
class ErrorSink {
|
||||||
final List<MoorError> _errors = [];
|
final List<DriftError> _errors = [];
|
||||||
UnmodifiableListView<MoorError> get errors => UnmodifiableListView(_errors);
|
UnmodifiableListView<DriftError> get errors => UnmodifiableListView(_errors);
|
||||||
|
|
||||||
void report(MoorError error) {
|
void report(DriftError error) {
|
||||||
_errors.add(error);
|
_errors.add(error);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -14,7 +14,7 @@ part 'options.g.dart';
|
||||||
fieldRename: FieldRename.snake,
|
fieldRename: FieldRename.snake,
|
||||||
createToJson: false,
|
createToJson: false,
|
||||||
)
|
)
|
||||||
class MoorOptions {
|
class DriftOptions {
|
||||||
static const _defaultSqliteVersion = SqliteVersion.v3(34);
|
static const _defaultSqliteVersion = SqliteVersion.v3(34);
|
||||||
|
|
||||||
/// Whether moor should generate a `fromJsonString` factory for data classes.
|
/// Whether moor should generate a `fromJsonString` factory for data classes.
|
||||||
|
@ -99,7 +99,7 @@ class MoorOptions {
|
||||||
final bool scopedDartComponents;
|
final bool scopedDartComponents;
|
||||||
|
|
||||||
@internal
|
@internal
|
||||||
const MoorOptions.defaults({
|
const DriftOptions.defaults({
|
||||||
this.generateFromJsonStringConstructor = false,
|
this.generateFromJsonStringConstructor = false,
|
||||||
this.overrideHashAndEqualsInResultSets = false,
|
this.overrideHashAndEqualsInResultSets = false,
|
||||||
this.compactQueryMethods = false,
|
this.compactQueryMethods = false,
|
||||||
|
@ -121,7 +121,7 @@ class MoorOptions {
|
||||||
this.dialect = const DialectOptions(SqlDialect.sqlite, null),
|
this.dialect = const DialectOptions(SqlDialect.sqlite, null),
|
||||||
});
|
});
|
||||||
|
|
||||||
MoorOptions({
|
DriftOptions({
|
||||||
required this.generateFromJsonStringConstructor,
|
required this.generateFromJsonStringConstructor,
|
||||||
required this.overrideHashAndEqualsInResultSets,
|
required this.overrideHashAndEqualsInResultSets,
|
||||||
required this.compactQueryMethods,
|
required this.compactQueryMethods,
|
||||||
|
@ -161,7 +161,7 @@ class MoorOptions {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
factory MoorOptions.fromJson(Map json) => _$MoorOptionsFromJson(json);
|
factory DriftOptions.fromJson(Map json) => _$DriftOptionsFromJson(json);
|
||||||
|
|
||||||
SqliteAnalysisOptions? get sqliteOptions {
|
SqliteAnalysisOptions? get sqliteOptions {
|
||||||
return dialect?.options ?? sqliteAnalysisOptions;
|
return dialect?.options ?? sqliteAnalysisOptions;
|
||||||
|
|
|
@ -6,8 +6,8 @@ part of 'options.dart';
|
||||||
// JsonSerializableGenerator
|
// JsonSerializableGenerator
|
||||||
// **************************************************************************
|
// **************************************************************************
|
||||||
|
|
||||||
MoorOptions _$MoorOptionsFromJson(Map json) => $checkedCreate(
|
DriftOptions _$DriftOptionsFromJson(Map json) => $checkedCreate(
|
||||||
'MoorOptions',
|
'DriftOptions',
|
||||||
json,
|
json,
|
||||||
($checkedConvert) {
|
($checkedConvert) {
|
||||||
$checkKeys(
|
$checkKeys(
|
||||||
|
@ -34,7 +34,7 @@ MoorOptions _$MoorOptionsFromJson(Map json) => $checkedCreate(
|
||||||
'scoped_dart_components'
|
'scoped_dart_components'
|
||||||
],
|
],
|
||||||
);
|
);
|
||||||
final val = MoorOptions(
|
final val = DriftOptions(
|
||||||
generateFromJsonStringConstructor: $checkedConvert(
|
generateFromJsonStringConstructor: $checkedConvert(
|
||||||
'write_from_json_string_constructor', (v) => v as bool? ?? false),
|
'write_from_json_string_constructor', (v) => v as bool? ?? false),
|
||||||
overrideHashAndEqualsInResultSets: $checkedConvert(
|
overrideHashAndEqualsInResultSets: $checkedConvert(
|
||||||
|
|
|
@ -76,8 +76,9 @@ class FileGraph {
|
||||||
}
|
}
|
||||||
|
|
||||||
enum FileType {
|
enum FileType {
|
||||||
/// A `.moor` file, containing `CREATE TABLE` statements and queries.
|
/// A `.drift` (or `.moor`) file, containing `CREATE TABLE` statements and
|
||||||
moor,
|
/// queries.
|
||||||
|
drift,
|
||||||
|
|
||||||
/// A dart library. Note that, in particular, this doesn't include `part of`
|
/// A dart library. Note that, in particular, this doesn't include `part of`
|
||||||
/// files, as those aren't libraries.
|
/// files, as those aren't libraries.
|
||||||
|
|
|
@ -1,7 +1,7 @@
|
||||||
import 'package:analyzer/dart/element/element.dart';
|
import 'package:analyzer/dart/element/element.dart';
|
||||||
|
|
||||||
/// Inputs coming from an external system (such as the analyzer, the build
|
/// Inputs coming from an external system (such as the analyzer, the build
|
||||||
/// package, etc.) that will be further analyzed by moor.
|
/// package, etc.) that will be further analyzed by drift_dev.
|
||||||
abstract class Input {
|
abstract class Input {
|
||||||
final String path;
|
final String path;
|
||||||
|
|
||||||
|
@ -15,9 +15,9 @@ class DartInput extends Input {
|
||||||
DartInput(String path, this.library) : super(path);
|
DartInput(String path, this.library) : super(path);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Input for a `.moor` file
|
/// Input for a `.drift` file
|
||||||
class MoorInput extends Input {
|
class DriftFileInput extends Input {
|
||||||
final String content;
|
final String content;
|
||||||
|
|
||||||
MoorInput(String path, this.content) : super(path);
|
DriftFileInput(String path, this.content) : super(path);
|
||||||
}
|
}
|
||||||
|
|
|
@ -4,10 +4,10 @@ import 'package:drift_dev/src/analyzer/runner/file_graph.dart';
|
||||||
import 'package:sqlparser/sqlparser.dart';
|
import 'package:sqlparser/sqlparser.dart';
|
||||||
|
|
||||||
abstract class FileResult {
|
abstract class FileResult {
|
||||||
final List<MoorSchemaEntity> declaredEntities;
|
final List<DriftSchemaEntity> declaredEntities;
|
||||||
|
|
||||||
Iterable<MoorTable> get declaredTables =>
|
Iterable<DriftTable> get declaredTables =>
|
||||||
declaredEntities.whereType<MoorTable>();
|
declaredEntities.whereType<DriftTable>();
|
||||||
Iterable<MoorView> get declaredViews =>
|
Iterable<MoorView> get declaredViews =>
|
||||||
declaredEntities.whereType<MoorView>();
|
declaredEntities.whereType<MoorView>();
|
||||||
|
|
||||||
|
@ -20,18 +20,18 @@ class ParsedDartFile extends FileResult {
|
||||||
final List<Dao> declaredDaos;
|
final List<Dao> declaredDaos;
|
||||||
final List<Database> declaredDatabases;
|
final List<Database> declaredDatabases;
|
||||||
|
|
||||||
Iterable<BaseMoorAccessor> get dbAccessors =>
|
Iterable<BaseDriftAccessor> get dbAccessors =>
|
||||||
declaredDatabases.cast<BaseMoorAccessor>().followedBy(declaredDaos);
|
declaredDatabases.cast<BaseDriftAccessor>().followedBy(declaredDaos);
|
||||||
|
|
||||||
ParsedDartFile(
|
ParsedDartFile(
|
||||||
{required this.library,
|
{required this.library,
|
||||||
List<MoorTable> declaredTables = const [],
|
List<DriftTable> declaredTables = const [],
|
||||||
this.declaredDaos = const [],
|
this.declaredDaos = const [],
|
||||||
this.declaredDatabases = const []})
|
this.declaredDatabases = const []})
|
||||||
: super(declaredTables);
|
: super(declaredTables);
|
||||||
}
|
}
|
||||||
|
|
||||||
class ParsedMoorFile extends FileResult {
|
class ParsedDriftFile extends FileResult {
|
||||||
final ParseResult parseResult;
|
final ParseResult parseResult;
|
||||||
DriftFile get parsedFile => parseResult.rootNode as DriftFile;
|
DriftFile get parsedFile => parseResult.rootNode as DriftFile;
|
||||||
|
|
||||||
|
@ -45,9 +45,9 @@ class ParsedMoorFile extends FileResult {
|
||||||
List<SqlQuery>? resolvedQueries;
|
List<SqlQuery>? resolvedQueries;
|
||||||
Map<ImportStatement, FoundFile>? resolvedImports;
|
Map<ImportStatement, FoundFile>? resolvedImports;
|
||||||
|
|
||||||
ParsedMoorFile(
|
ParsedDriftFile(
|
||||||
this.parseResult, {
|
this.parseResult, {
|
||||||
List<MoorSchemaEntity> declaredEntities = const [],
|
List<DriftSchemaEntity> declaredEntities = const [],
|
||||||
this.queries = const [],
|
this.queries = const [],
|
||||||
this.imports = const [],
|
this.imports = const [],
|
||||||
this.otherComponents = const [],
|
this.otherComponents = const [],
|
||||||
|
|
|
@ -5,9 +5,9 @@ import 'package:collection/collection.dart';
|
||||||
import 'package:drift/drift.dart';
|
import 'package:drift/drift.dart';
|
||||||
import 'package:drift_dev/moor_generator.dart';
|
import 'package:drift_dev/moor_generator.dart';
|
||||||
import 'package:drift_dev/src/analyzer/dart/parser.dart';
|
import 'package:drift_dev/src/analyzer/dart/parser.dart';
|
||||||
|
import 'package:drift_dev/src/analyzer/drift/entity_handler.dart';
|
||||||
|
import 'package:drift_dev/src/analyzer/drift/parser.dart';
|
||||||
import 'package:drift_dev/src/analyzer/errors.dart';
|
import 'package:drift_dev/src/analyzer/errors.dart';
|
||||||
import 'package:drift_dev/src/analyzer/moor/entity_handler.dart';
|
|
||||||
import 'package:drift_dev/src/analyzer/moor/parser.dart';
|
|
||||||
import 'package:drift_dev/src/analyzer/runner/file_graph.dart';
|
import 'package:drift_dev/src/analyzer/runner/file_graph.dart';
|
||||||
import 'package:drift_dev/src/analyzer/runner/results.dart';
|
import 'package:drift_dev/src/analyzer/runner/results.dart';
|
||||||
import 'package:drift_dev/src/analyzer/runner/task.dart';
|
import 'package:drift_dev/src/analyzer/runner/task.dart';
|
||||||
|
@ -37,7 +37,7 @@ abstract class Step {
|
||||||
|
|
||||||
Step(this.task, this.file);
|
Step(this.task, this.file);
|
||||||
|
|
||||||
void reportError(MoorError error) =>
|
void reportError(DriftError error) =>
|
||||||
errors.report(error..wasDuringParsing = isParsing);
|
errors.report(error..wasDuringParsing = isParsing);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -47,13 +47,13 @@ abstract class AnalyzingStep extends Step {
|
||||||
@override
|
@override
|
||||||
final bool isParsing = false;
|
final bool isParsing = false;
|
||||||
|
|
||||||
Iterable<MoorSchemaEntity> _availableEntities(Iterable<FoundFile> imports) {
|
Iterable<DriftSchemaEntity> _availableEntities(Iterable<FoundFile> imports) {
|
||||||
return imports.expand<MoorSchemaEntity>((file) =>
|
return imports.expand<DriftSchemaEntity>((file) =>
|
||||||
file.currentResult?.declaredEntities ?? const Iterable.empty());
|
file.currentResult?.declaredEntities ?? const Iterable.empty());
|
||||||
}
|
}
|
||||||
|
|
||||||
Iterable<MoorTable> _availableTables(Iterable<FoundFile> imports) {
|
Iterable<DriftTable> _availableTables(Iterable<FoundFile> imports) {
|
||||||
return _availableEntities(imports).whereType<MoorTable>();
|
return _availableEntities(imports).whereType<DriftTable>();
|
||||||
}
|
}
|
||||||
|
|
||||||
Iterable<MoorView> _availableViews(Iterable<FoundFile> imports) {
|
Iterable<MoorView> _availableViews(Iterable<FoundFile> imports) {
|
||||||
|
|
|
@ -62,7 +62,7 @@ class AnalyzeDartStep extends AnalyzingStep {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
List<MoorSchemaEntity>? availableEntities;
|
List<DriftSchemaEntity>? availableEntities;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
availableEntities = sortEntitiesTopologically(unsortedEntities);
|
availableEntities = sortEntitiesTopologically(unsortedEntities);
|
||||||
|
@ -98,10 +98,11 @@ class AnalyzeDartStep extends AnalyzingStep {
|
||||||
|
|
||||||
final availableQueries = transitiveImports
|
final availableQueries = transitiveImports
|
||||||
.map((f) => f.currentResult)
|
.map((f) => f.currentResult)
|
||||||
.whereType<ParsedMoorFile>()
|
.whereType<ParsedDriftFile>()
|
||||||
.expand((f) => f.resolvedQueries ?? const <Never>[]);
|
.expand((f) => f.resolvedQueries ?? const <Never>[]);
|
||||||
|
|
||||||
final availableTables = availableEntities.whereType<MoorTable>().toList();
|
final availableTables =
|
||||||
|
availableEntities.whereType<DriftTable>().toList();
|
||||||
final availableViews = availableEntities.whereType<MoorView>().toList();
|
final availableViews = availableEntities.whereType<MoorView>().toList();
|
||||||
final parser = SqlAnalyzer(
|
final parser = SqlAnalyzer(
|
||||||
this, availableTables, availableViews, accessor.declaredQueries);
|
this, availableTables, availableViews, accessor.declaredQueries);
|
||||||
|
@ -118,9 +119,9 @@ class AnalyzeDartStep extends AnalyzingStep {
|
||||||
|
|
||||||
/// Resolves a `.reference` action declared on a Dart-defined column.
|
/// Resolves a `.reference` action declared on a Dart-defined column.
|
||||||
void _resolveDartColumnReferences(
|
void _resolveDartColumnReferences(
|
||||||
Map<ClassElement, MoorSchemaEntity> dartTables) {
|
Map<ClassElement, DriftSchemaEntity> dartTables) {
|
||||||
dartTables.forEach((dartClass, moorEntity) {
|
dartTables.forEach((dartClass, moorEntity) {
|
||||||
if (moorEntity is! MoorTable) return;
|
if (moorEntity is! DriftTable) return;
|
||||||
|
|
||||||
for (final column in moorEntity.columns) {
|
for (final column in moorEntity.columns) {
|
||||||
for (var i = 0; i < column.features.length; i++) {
|
for (var i = 0; i < column.features.length; i++) {
|
||||||
|
@ -129,7 +130,7 @@ class AnalyzeDartStep extends AnalyzingStep {
|
||||||
if (feature is UnresolvedDartForeignKeyReference) {
|
if (feature is UnresolvedDartForeignKeyReference) {
|
||||||
final table = dartTables[feature.otherTable];
|
final table = dartTables[feature.otherTable];
|
||||||
|
|
||||||
if (table is! MoorTable) {
|
if (table is! DriftTable) {
|
||||||
reportError(ErrorInDartCode(
|
reportError(ErrorInDartCode(
|
||||||
message: 'This class has not been added as a table',
|
message: 'This class has not been added as a table',
|
||||||
affectedElement: feature.surroundingElementForErrors,
|
affectedElement: feature.surroundingElementForErrors,
|
||||||
|
|
|
@ -9,7 +9,7 @@ class AnalyzeViewsInDriftFileStep extends AnalyzingStep {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
final parseResult = file.currentResult as ParsedMoorFile;
|
final parseResult = file.currentResult as ParsedDriftFile;
|
||||||
final availableTables =
|
final availableTables =
|
||||||
_availableTables(task.crawlImports(parseResult.resolvedImports!.values))
|
_availableTables(task.crawlImports(parseResult.resolvedImports!.values))
|
||||||
.followedBy(parseResult.declaredTables)
|
.followedBy(parseResult.declaredTables)
|
||||||
|
@ -30,7 +30,7 @@ class AnalyzeMoorStep extends AnalyzingStep {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
final parseResult = file.currentResult as ParsedMoorFile;
|
final parseResult = file.currentResult as ParsedDriftFile;
|
||||||
|
|
||||||
final transitiveImports =
|
final transitiveImports =
|
||||||
task.crawlImports(parseResult.resolvedImports!.values).toList();
|
task.crawlImports(parseResult.resolvedImports!.values).toList();
|
||||||
|
@ -38,7 +38,7 @@ class AnalyzeMoorStep extends AnalyzingStep {
|
||||||
// Check that all imports are valid
|
// Check that all imports are valid
|
||||||
parseResult.resolvedImports!.forEach((node, fileRef) {
|
parseResult.resolvedImports!.forEach((node, fileRef) {
|
||||||
if (fileRef.type == FileType.other) {
|
if (fileRef.type == FileType.other) {
|
||||||
reportError(ErrorInMoorFile(
|
reportError(ErrorInDriftFile(
|
||||||
span: node.span!,
|
span: node.span!,
|
||||||
message: "Invalid import (the file exists, but couldn't be parsed). "
|
message: "Invalid import (the file exists, but couldn't be parsed). "
|
||||||
'Is it a part file?',
|
'Is it a part file?',
|
||||||
|
|
|
@ -1,7 +1,7 @@
|
||||||
part of '../steps.dart';
|
part of '../steps.dart';
|
||||||
|
|
||||||
/// Extracts the following information from a Dart file:
|
/// Extracts the following information from a Dart file:
|
||||||
/// - [MoorTable]s, which are read from Dart classes extending `Table`.
|
/// - [DriftTable]s, which are read from Dart classes extending `Table`.
|
||||||
/// - [Database]s, which are read from `@UseMoor`-annotated classes
|
/// - [Database]s, which are read from `@UseMoor`-annotated classes
|
||||||
/// - [Dao]s, which are read from `@UseDao`-annotated classes.
|
/// - [Dao]s, which are read from `@UseDao`-annotated classes.
|
||||||
///
|
///
|
||||||
|
@ -16,15 +16,15 @@ class ParseDartStep extends Step {
|
||||||
final LibraryElement library;
|
final LibraryElement library;
|
||||||
final HelperLibrary resolvedHelper;
|
final HelperLibrary resolvedHelper;
|
||||||
|
|
||||||
late MoorDartParser _parser;
|
late DriftDartParser _parser;
|
||||||
MoorDartParser get parser => _parser;
|
DriftDartParser get parser => _parser;
|
||||||
|
|
||||||
final Map<ClassElement, MoorTable> _tables = {};
|
final Map<ClassElement, DriftTable> _tables = {};
|
||||||
final Map<ClassElement, MoorView> _views = {};
|
final Map<ClassElement, MoorView> _views = {};
|
||||||
|
|
||||||
ParseDartStep(Task task, FoundFile file, this.library, this.resolvedHelper)
|
ParseDartStep(Task task, FoundFile file, this.library, this.resolvedHelper)
|
||||||
: super(task, file) {
|
: super(task, file) {
|
||||||
_parser = MoorDartParser(this);
|
_parser = DriftDartParser(this);
|
||||||
}
|
}
|
||||||
|
|
||||||
Future<ParsedDartFile> parse() async {
|
Future<ParsedDartFile> parse() async {
|
||||||
|
@ -58,7 +58,7 @@ class ParseDartStep extends Step {
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
Future<MoorTable?> _parseTable(ClassElement element) async {
|
Future<DriftTable?> _parseTable(ClassElement element) async {
|
||||||
if (!_tables.containsKey(element)) {
|
if (!_tables.containsKey(element)) {
|
||||||
final table = await parser.parseTable(element);
|
final table = await parser.parseTable(element);
|
||||||
|
|
||||||
|
@ -71,7 +71,7 @@ class ParseDartStep extends Step {
|
||||||
}
|
}
|
||||||
|
|
||||||
Future<MoorView?> _parseView(
|
Future<MoorView?> _parseView(
|
||||||
ClassElement element, List<MoorTable> tables) async {
|
ClassElement element, List<DriftTable> tables) async {
|
||||||
if (!_views.containsKey(element)) {
|
if (!_views.containsKey(element)) {
|
||||||
final view = await parser.parseView(element, tables);
|
final view = await parser.parseView(element, tables);
|
||||||
|
|
||||||
|
@ -82,7 +82,7 @@ class ParseDartStep extends Step {
|
||||||
return _views[element];
|
return _views[element];
|
||||||
}
|
}
|
||||||
|
|
||||||
void _lintDartTable(MoorTable table, ClassElement from) {
|
void _lintDartTable(DriftTable table, ClassElement from) {
|
||||||
if (table.primaryKey != null) {
|
if (table.primaryKey != null) {
|
||||||
final hasAdditional = table.columns.any((c) {
|
final hasAdditional = table.columns.any((c) {
|
||||||
final isPk = c.features.any((f) => f is PrimaryKey);
|
final isPk = c.features.any((f) => f is PrimaryKey);
|
||||||
|
@ -106,7 +106,7 @@ class ParseDartStep extends Step {
|
||||||
/// annotation.
|
/// annotation.
|
||||||
Future<Database?> parseDatabase(
|
Future<Database?> parseDatabase(
|
||||||
ClassElement element, ConstantReader annotation) {
|
ClassElement element, ConstantReader annotation) {
|
||||||
return UseMoorParser(this).parseDatabase(element, annotation);
|
return DriftDatabaseParser(this).parseDatabase(element, annotation);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Parses a [Dao] from a class declaration that has a `UseDao`
|
/// Parses a [Dao] from a class declaration that has a `UseDao`
|
||||||
|
@ -115,11 +115,11 @@ class ParseDartStep extends Step {
|
||||||
return UseDaoParser(this).parseDao(element, annotation);
|
return UseDaoParser(this).parseDao(element, annotation);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Resolves a [MoorTable] for the class of each [DartType] in [types].
|
/// Resolves a [DriftTable] for the class of each [DartType] in [types].
|
||||||
/// The [initializedBy] element should be the piece of code that caused the
|
/// The [initializedBy] element should be the piece of code that caused the
|
||||||
/// parsing (e.g. the database class that is annotated with `@DriftDatabase`).
|
/// parsing (e.g. the database class that is annotated with `@DriftDatabase`).
|
||||||
/// This will allow for more descriptive error messages.
|
/// This will allow for more descriptive error messages.
|
||||||
Future<List<MoorTable>> parseTables(
|
Future<List<DriftTable>> parseTables(
|
||||||
Iterable<DartType> types, Element initializedBy) {
|
Iterable<DartType> types, Element initializedBy) {
|
||||||
return Future.wait(types.map((type) {
|
return Future.wait(types.map((type) {
|
||||||
if (!_tableTypeChecker.isAssignableFrom(type.element!)) {
|
if (!_tableTypeChecker.isAssignableFrom(type.element!)) {
|
||||||
|
@ -142,8 +142,8 @@ class ParseDartStep extends Step {
|
||||||
/// The [initializedBy] element should be the piece of code that caused the
|
/// The [initializedBy] element should be the piece of code that caused the
|
||||||
/// parsing (e.g. the database class that is annotated with `@DriftDatabase`).
|
/// parsing (e.g. the database class that is annotated with `@DriftDatabase`).
|
||||||
/// This will allow for more descriptive error messages.
|
/// This will allow for more descriptive error messages.
|
||||||
Future<List<MoorView>> parseViews(
|
Future<List<MoorView>> parseViews(Iterable<DartType> types,
|
||||||
Iterable<DartType> types, Element initializedBy, List<MoorTable> tables) {
|
Element initializedBy, List<DriftTable> tables) {
|
||||||
return Future.wait(types.map((type) {
|
return Future.wait(types.map((type) {
|
||||||
if (!_viewTypeChecker.isAssignableFrom(type.element!)) {
|
if (!_viewTypeChecker.isAssignableFrom(type.element!)) {
|
||||||
reportError(ErrorInDartCode(
|
reportError(ErrorInDartCode(
|
||||||
|
|
|
@ -6,7 +6,7 @@ class ParseMoorStep extends Step {
|
||||||
|
|
||||||
ParseMoorStep(Task task, FoundFile file, this.content) : super(task, file);
|
ParseMoorStep(Task task, FoundFile file, this.content) : super(task, file);
|
||||||
|
|
||||||
Future<ParsedMoorFile> parseFile() async {
|
Future<ParsedDriftFile> parseFile() async {
|
||||||
final parser = MoorParser(this, await task.helper);
|
final parser = MoorParser(this, await task.helper);
|
||||||
return parser.parseAndAnalyze();
|
return parser.parseAndAnalyze();
|
||||||
}
|
}
|
||||||
|
|
|
@ -61,8 +61,8 @@ class Task {
|
||||||
// todo we force that moor files are analyzed first because they contain
|
// todo we force that moor files are analyzed first because they contain
|
||||||
// resolved queries which are copied into database accessors. Can we find
|
// resolved queries which are copied into database accessors. Can we find
|
||||||
// a way to remove this special-handling?
|
// a way to remove this special-handling?
|
||||||
final moorFiles = _analyzedFiles.where((f) => f.type == FileType.moor);
|
final moorFiles = _analyzedFiles.where((f) => f.type == FileType.drift);
|
||||||
final otherFiles = _analyzedFiles.where((f) => f.type != FileType.moor);
|
final otherFiles = _analyzedFiles.where((f) => f.type != FileType.drift);
|
||||||
|
|
||||||
for (final moorFile in moorFiles) {
|
for (final moorFile in moorFiles) {
|
||||||
moorFile.errors.clearNonParsingErrors();
|
moorFile.errors.clearNonParsingErrors();
|
||||||
|
@ -95,15 +95,15 @@ class Task {
|
||||||
final resolvedImports = <FoundFile>{};
|
final resolvedImports = <FoundFile>{};
|
||||||
|
|
||||||
switch (file.type) {
|
switch (file.type) {
|
||||||
case FileType.moor:
|
case FileType.drift:
|
||||||
final content = await backend.readMoor(file.uri);
|
final content = await backend.readMoor(file.uri);
|
||||||
final step = createdStep = ParseMoorStep(this, file, content);
|
final step = createdStep = ParseMoorStep(this, file, content);
|
||||||
|
|
||||||
ParsedMoorFile parsed;
|
ParsedDriftFile parsed;
|
||||||
try {
|
try {
|
||||||
parsed = await step.parseFile();
|
parsed = await step.parseFile();
|
||||||
} on Exception catch (e) {
|
} on Exception catch (e) {
|
||||||
file.errors.report(MoorError(
|
file.errors.report(DriftError(
|
||||||
severity: Severity.error,
|
severity: Severity.error,
|
||||||
message: 'Could not parse file: $e',
|
message: 'Could not parse file: $e',
|
||||||
)..wasDuringParsing = true);
|
)..wasDuringParsing = true);
|
||||||
|
@ -115,7 +115,7 @@ class Task {
|
||||||
for (final import in parsed.imports) {
|
for (final import in parsed.imports) {
|
||||||
final found = await _resolveOrReportError(file, import.importedFile,
|
final found = await _resolveOrReportError(file, import.importedFile,
|
||||||
(errorMsg) {
|
(errorMsg) {
|
||||||
step.reportError(ErrorInMoorFile(
|
step.reportError(ErrorInDriftFile(
|
||||||
span: import.importString!.span,
|
span: import.importString!.span,
|
||||||
severity: Severity.error,
|
severity: Severity.error,
|
||||||
message: errorMsg,
|
message: errorMsg,
|
||||||
|
@ -143,7 +143,7 @@ class Task {
|
||||||
file.currentResult = parsed;
|
file.currentResult = parsed;
|
||||||
|
|
||||||
final daosAndDatabases = parsed.declaredDaos
|
final daosAndDatabases = parsed.declaredDaos
|
||||||
.cast<BaseMoorAccessor>()
|
.cast<BaseDriftAccessor>()
|
||||||
.followedBy(parsed.declaredDatabases);
|
.followedBy(parsed.declaredDatabases);
|
||||||
|
|
||||||
for (final accessor in daosAndDatabases) {
|
for (final accessor in daosAndDatabases) {
|
||||||
|
@ -212,9 +212,10 @@ class Task {
|
||||||
yield available;
|
yield available;
|
||||||
|
|
||||||
var importsFromHere = const Iterable<FoundFile>.empty();
|
var importsFromHere = const Iterable<FoundFile>.empty();
|
||||||
if (available.type == FileType.moor) {
|
if (available.type == FileType.drift) {
|
||||||
importsFromHere =
|
importsFromHere = (available.currentResult as ParsedDriftFile)
|
||||||
(available.currentResult as ParsedMoorFile).resolvedImports!.values;
|
.resolvedImports!
|
||||||
|
.values;
|
||||||
}
|
}
|
||||||
|
|
||||||
for (final next in importsFromHere) {
|
for (final next in importsFromHere) {
|
||||||
|
@ -235,7 +236,7 @@ class Task {
|
||||||
case FileType.dartLibrary:
|
case FileType.dartLibrary:
|
||||||
step = AnalyzeDartStep(this, file)..analyze();
|
step = AnalyzeDartStep(this, file)..analyze();
|
||||||
break;
|
break;
|
||||||
case FileType.moor:
|
case FileType.drift:
|
||||||
final analyzeMoor = step = AnalyzeMoorStep(this, file);
|
final analyzeMoor = step = AnalyzeMoorStep(this, file);
|
||||||
await analyzeMoor.analyze();
|
await analyzeMoor.analyze();
|
||||||
break;
|
break;
|
||||||
|
|
|
@ -1,7 +1,7 @@
|
||||||
import 'dart:async';
|
import 'dart:async';
|
||||||
|
|
||||||
|
import 'package:drift_dev/src/analyzer/drift/moor_ffi_extension.dart';
|
||||||
import 'package:drift_dev/src/analyzer/errors.dart';
|
import 'package:drift_dev/src/analyzer/errors.dart';
|
||||||
import 'package:drift_dev/src/analyzer/moor/moor_ffi_extension.dart';
|
|
||||||
import 'package:drift_dev/src/analyzer/runner/file_graph.dart';
|
import 'package:drift_dev/src/analyzer/runner/file_graph.dart';
|
||||||
import 'package:drift_dev/src/analyzer/runner/task.dart';
|
import 'package:drift_dev/src/analyzer/runner/task.dart';
|
||||||
import 'package:drift_dev/src/backends/backend.dart';
|
import 'package:drift_dev/src/backends/backend.dart';
|
||||||
|
@ -11,8 +11,8 @@ import 'package:sqlparser/sqlparser.dart';
|
||||||
import 'options.dart';
|
import 'options.dart';
|
||||||
|
|
||||||
const _fileEndings = {
|
const _fileEndings = {
|
||||||
'.moor': FileType.moor,
|
'.moor': FileType.drift,
|
||||||
'.drift': FileType.moor,
|
'.drift': FileType.drift,
|
||||||
'.dart': FileType.dartLibrary,
|
'.dart': FileType.dartLibrary,
|
||||||
};
|
};
|
||||||
|
|
||||||
|
@ -20,12 +20,12 @@ const _fileEndings = {
|
||||||
class MoorSession {
|
class MoorSession {
|
||||||
final FileGraph fileGraph = FileGraph();
|
final FileGraph fileGraph = FileGraph();
|
||||||
final Backend backend;
|
final Backend backend;
|
||||||
MoorOptions options;
|
DriftOptions options;
|
||||||
|
|
||||||
final _completedTasks = StreamController<Task>.broadcast();
|
final _completedTasks = StreamController<Task>.broadcast();
|
||||||
final _changedFiles = StreamController<List<FoundFile>>.broadcast();
|
final _changedFiles = StreamController<List<FoundFile>>.broadcast();
|
||||||
|
|
||||||
MoorSession(this.backend, {this.options = const MoorOptions.defaults()});
|
MoorSession(this.backend, {this.options = const DriftOptions.defaults()});
|
||||||
|
|
||||||
/// Stream that emits a [Task] that has been completed.
|
/// Stream that emits a [Task] that has been completed.
|
||||||
Stream<Task> get completedTasks => _completedTasks.stream;
|
Stream<Task> get completedTasks => _completedTasks.stream;
|
||||||
|
@ -83,7 +83,7 @@ class MoorSession {
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Finds all current errors in the [file] and transitive imports thereof.
|
/// Finds all current errors in the [file] and transitive imports thereof.
|
||||||
Iterable<MoorError> errorsInFileAndImports(FoundFile file) {
|
Iterable<DriftError> errorsInFileAndImports(FoundFile file) {
|
||||||
final targetFiles = [file, ...fileGraph.crawl(file)];
|
final targetFiles = [file, ...fileGraph.crawl(file)];
|
||||||
|
|
||||||
return targetFiles.fold(const Iterable.empty(), (errors, file) {
|
return targetFiles.fold(const Iterable.empty(), (errors, file) {
|
||||||
|
|
|
@ -18,7 +18,7 @@ import 'package:drift_dev/src/analyzer/errors.dart';
|
||||||
/// matching table. This restriction might be lifted in the future, but it makes
|
/// matching table. This restriction might be lifted in the future, but it makes
|
||||||
/// the implementation easier.
|
/// the implementation easier.
|
||||||
class CustomResultClassTransformer {
|
class CustomResultClassTransformer {
|
||||||
final BaseMoorAccessor accessor;
|
final BaseDriftAccessor accessor;
|
||||||
|
|
||||||
CustomResultClassTransformer(this.accessor);
|
CustomResultClassTransformer(this.accessor);
|
||||||
|
|
||||||
|
|
|
@ -1,4 +1,4 @@
|
||||||
import 'package:drift_dev/moor_generator.dart' show MoorColumn;
|
import 'package:drift_dev/moor_generator.dart' show DriftColumn;
|
||||||
import 'package:sqlparser/sqlparser.dart';
|
import 'package:sqlparser/sqlparser.dart';
|
||||||
|
|
||||||
import '../query_handler.dart';
|
import '../query_handler.dart';
|
||||||
|
@ -173,7 +173,7 @@ class _LintingVisitor extends RecursiveVisitor<void, void> {
|
||||||
|
|
||||||
// second, check that no required columns are left out
|
// second, check that no required columns are left out
|
||||||
final resolved = e.table.resolved;
|
final resolved = e.table.resolved;
|
||||||
List<MoorColumn> required;
|
List<DriftColumn> required;
|
||||||
if (resolved is Table) {
|
if (resolved is Table) {
|
||||||
final specifiedTable =
|
final specifiedTable =
|
||||||
linter.mapper.tableToMoor(e.table.resolved as Table)!;
|
linter.mapper.tableToMoor(e.table.resolved as Table)!;
|
||||||
|
|
|
@ -13,7 +13,7 @@ import 'package:sqlparser/utils/find_referenced_tables.dart';
|
||||||
import 'required_variables.dart';
|
import 'required_variables.dart';
|
||||||
|
|
||||||
abstract class BaseAnalyzer {
|
abstract class BaseAnalyzer {
|
||||||
final List<MoorTable> tables;
|
final List<DriftTable> tables;
|
||||||
final List<MoorView> views;
|
final List<MoorView> views;
|
||||||
final Step step;
|
final Step step;
|
||||||
|
|
||||||
|
@ -38,13 +38,13 @@ abstract class BaseAnalyzer {
|
||||||
}
|
}
|
||||||
|
|
||||||
@protected
|
@protected
|
||||||
Iterable<MoorSchemaEntity> findReferences(AstNode node,
|
Iterable<DriftSchemaEntity> findReferences(AstNode node,
|
||||||
{bool includeViews = true}) {
|
{bool includeViews = true}) {
|
||||||
final finder = ReferencedTablesVisitor();
|
final finder = ReferencedTablesVisitor();
|
||||||
node.acceptWithoutArg(finder);
|
node.acceptWithoutArg(finder);
|
||||||
|
|
||||||
var entities =
|
var entities =
|
||||||
finder.foundTables.map<MoorSchemaEntity?>(mapper.tableToMoor);
|
finder.foundTables.map<DriftSchemaEntity?>(mapper.tableToMoor);
|
||||||
if (includeViews) {
|
if (includeViews) {
|
||||||
entities = entities.followedBy(finder.foundViews.map(mapper.viewToMoor));
|
entities = entities.followedBy(finder.foundViews.map(mapper.viewToMoor));
|
||||||
}
|
}
|
||||||
|
@ -65,11 +65,11 @@ abstract class BaseAnalyzer {
|
||||||
@protected
|
@protected
|
||||||
void report(AnalysisError error,
|
void report(AnalysisError error,
|
||||||
{String Function()? msg, Severity? severity}) {
|
{String Function()? msg, Severity? severity}) {
|
||||||
if (step.file.type == FileType.moor) {
|
if (step.file.type == FileType.drift) {
|
||||||
step.reportError(
|
step.reportError(
|
||||||
ErrorInMoorFile.fromSqlParser(error, overrideSeverity: severity));
|
ErrorInDriftFile.fromSqlParser(error, overrideSeverity: severity));
|
||||||
} else {
|
} else {
|
||||||
step.reportError(MoorError(
|
step.reportError(DriftError(
|
||||||
severity: severity!,
|
severity: severity!,
|
||||||
message: msg!(),
|
message: msg!(),
|
||||||
));
|
));
|
||||||
|
@ -93,7 +93,7 @@ class SqlAnalyzer extends BaseAnalyzer {
|
||||||
|
|
||||||
final List<SqlQuery> foundQueries = [];
|
final List<SqlQuery> foundQueries = [];
|
||||||
|
|
||||||
SqlAnalyzer(Step step, List<MoorTable> tables, List<MoorView> views,
|
SqlAnalyzer(Step step, List<DriftTable> tables, List<MoorView> views,
|
||||||
this.definedQueries)
|
this.definedQueries)
|
||||||
: super(tables, views, step);
|
: super(tables, views, step);
|
||||||
|
|
||||||
|
@ -125,7 +125,7 @@ class SqlAnalyzer extends BaseAnalyzer {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} catch (e, s) {
|
} catch (e, s) {
|
||||||
step.reportError(MoorError(
|
step.reportError(DriftError(
|
||||||
severity: Severity.criticalError,
|
severity: Severity.criticalError,
|
||||||
message: 'Error while trying to parse $name: $e, $s'));
|
message: 'Error while trying to parse $name: $e, $s'));
|
||||||
continue;
|
continue;
|
||||||
|
|
|
@ -147,7 +147,7 @@ class QueryHandler {
|
||||||
_applyFoundTables(tableFinder);
|
_applyFoundTables(tableFinder);
|
||||||
|
|
||||||
final moorTables =
|
final moorTables =
|
||||||
_foundTables.map(mapper.tableToMoor).whereType<MoorTable>().toList();
|
_foundTables.map(mapper.tableToMoor).whereType<DriftTable>().toList();
|
||||||
final moorViews =
|
final moorViews =
|
||||||
_foundViews.map(mapper.viewToMoor).whereType<MoorView>().toList();
|
_foundViews.map(mapper.viewToMoor).whereType<MoorView>().toList();
|
||||||
|
|
||||||
|
@ -212,7 +212,7 @@ class QueryHandler {
|
||||||
}
|
}
|
||||||
|
|
||||||
final resultEntryToColumn = <ResultColumn, String>{};
|
final resultEntryToColumn = <ResultColumn, String>{};
|
||||||
final resultColumnNameToMoor = <String, MoorColumn>{};
|
final resultColumnNameToMoor = <String, DriftColumn>{};
|
||||||
var matches = true;
|
var matches = true;
|
||||||
|
|
||||||
// go trough all columns of the table in question
|
// go trough all columns of the table in question
|
||||||
|
|
|
@ -9,15 +9,15 @@ import 'required_variables.dart';
|
||||||
/// Converts tables and types between the moor_generator and the sqlparser
|
/// Converts tables and types between the moor_generator and the sqlparser
|
||||||
/// library.
|
/// library.
|
||||||
class TypeMapper {
|
class TypeMapper {
|
||||||
final Map<Table, MoorTable> _engineTablesToSpecified = {};
|
final Map<Table, DriftTable> _engineTablesToSpecified = {};
|
||||||
final Map<View, MoorView> _engineViewsToSpecified = {};
|
final Map<View, MoorView> _engineViewsToSpecified = {};
|
||||||
final bool applyTypeConvertersToVariables;
|
final bool applyTypeConvertersToVariables;
|
||||||
|
|
||||||
TypeMapper({this.applyTypeConvertersToVariables = false});
|
TypeMapper({this.applyTypeConvertersToVariables = false});
|
||||||
|
|
||||||
/// Convert a [MoorTable] from moor into something that can be understood
|
/// Convert a [DriftTable] from moor into something that can be understood
|
||||||
/// by the sqlparser library.
|
/// by the sqlparser library.
|
||||||
Table extractStructure(MoorTable table) {
|
Table extractStructure(DriftTable table) {
|
||||||
if (table.parserTable != null) {
|
if (table.parserTable != null) {
|
||||||
final parserTbl = table.parserTable!;
|
final parserTbl = table.parserTable!;
|
||||||
_engineTablesToSpecified[parserTbl] = table;
|
_engineTablesToSpecified[parserTbl] = table;
|
||||||
|
@ -34,7 +34,7 @@ class TypeMapper {
|
||||||
|
|
||||||
final column = TableColumn(specified.name.name, type,
|
final column = TableColumn(specified.name.name, type,
|
||||||
isGenerated: specified.isGenerated);
|
isGenerated: specified.isGenerated);
|
||||||
column.setMeta<MoorColumn>(specified);
|
column.setMeta<DriftColumn>(specified);
|
||||||
|
|
||||||
columns.add(column);
|
columns.add(column);
|
||||||
}
|
}
|
||||||
|
@ -44,7 +44,7 @@ class TypeMapper {
|
||||||
resolvedColumns: columns,
|
resolvedColumns: columns,
|
||||||
isVirtual: table.isVirtualTable,
|
isVirtual: table.isVirtualTable,
|
||||||
);
|
);
|
||||||
engineTable.setMeta<MoorTable>(table);
|
engineTable.setMeta<DriftTable>(table);
|
||||||
_engineTablesToSpecified[engineTable] = table;
|
_engineTablesToSpecified[engineTable] = table;
|
||||||
return engineTable;
|
return engineTable;
|
||||||
}
|
}
|
||||||
|
@ -317,7 +317,7 @@ class TypeMapper {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
MoorEntityWithResultSet moorEntity;
|
DriftEntityWithResultSet moorEntity;
|
||||||
|
|
||||||
if (resultSet is Table) {
|
if (resultSet is Table) {
|
||||||
moorEntity = tableToMoor(resultSet)!;
|
moorEntity = tableToMoor(resultSet)!;
|
||||||
|
@ -337,7 +337,7 @@ class TypeMapper {
|
||||||
..astNode = placeholder;
|
..astNode = placeholder;
|
||||||
}
|
}
|
||||||
|
|
||||||
MoorTable? tableToMoor(Table table) {
|
DriftTable? tableToMoor(Table table) {
|
||||||
return _engineTablesToSpecified[table];
|
return _engineTablesToSpecified[table];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -345,7 +345,7 @@ class TypeMapper {
|
||||||
return _engineViewsToSpecified[view];
|
return _engineViewsToSpecified[view];
|
||||||
}
|
}
|
||||||
|
|
||||||
MoorEntityWithResultSet? viewOrTableToMoor(dynamic entity) {
|
DriftEntityWithResultSet? viewOrTableToMoor(dynamic entity) {
|
||||||
if (entity is Table) {
|
if (entity is Table) {
|
||||||
return tableToMoor(entity);
|
return tableToMoor(entity);
|
||||||
} else if (entity is View) {
|
} else if (entity is View) {
|
||||||
|
|
|
@ -1,6 +1,6 @@
|
||||||
import 'package:drift_dev/moor_generator.dart';
|
import 'package:drift_dev/moor_generator.dart';
|
||||||
|
import 'package:drift_dev/src/analyzer/drift/find_dart_class.dart';
|
||||||
import 'package:drift_dev/src/analyzer/errors.dart';
|
import 'package:drift_dev/src/analyzer/errors.dart';
|
||||||
import 'package:drift_dev/src/analyzer/moor/find_dart_class.dart';
|
|
||||||
import 'package:drift_dev/src/analyzer/runner/steps.dart';
|
import 'package:drift_dev/src/analyzer/runner/steps.dart';
|
||||||
import 'package:drift_dev/src/analyzer/sql_queries/query_analyzer.dart';
|
import 'package:drift_dev/src/analyzer/sql_queries/query_analyzer.dart';
|
||||||
import 'package:drift_dev/src/utils/type_converter_hint.dart';
|
import 'package:drift_dev/src/utils/type_converter_hint.dart';
|
||||||
|
@ -11,15 +11,15 @@ import '../dart_types.dart';
|
||||||
class ViewAnalyzer extends BaseAnalyzer {
|
class ViewAnalyzer extends BaseAnalyzer {
|
||||||
final List<ImportStatement> imports;
|
final List<ImportStatement> imports;
|
||||||
|
|
||||||
ViewAnalyzer(Step step, List<MoorTable> tables, this.imports)
|
ViewAnalyzer(Step step, List<DriftTable> tables, this.imports)
|
||||||
: super(tables, const [], step);
|
: super(tables, const [], step);
|
||||||
|
|
||||||
/// Resolves all the views in topological order.
|
/// Resolves all the views in topological order.
|
||||||
Future<void> resolve(Iterable<MoorView> viewsToAnalyze) async {
|
Future<void> resolve(Iterable<MoorView> viewsToAnalyze) async {
|
||||||
// Going through the topologically sorted list and analyzing each view.
|
// Going through the topologically sorted list and analyzing each view.
|
||||||
for (final view in viewsToAnalyze) {
|
for (final view in viewsToAnalyze) {
|
||||||
if (view.declaration is! MoorViewDeclaration) continue;
|
if (view.declaration is! DriftViewDeclaration) continue;
|
||||||
final viewDeclaration = view.declaration as MoorViewDeclaration;
|
final viewDeclaration = view.declaration as DriftViewDeclaration;
|
||||||
|
|
||||||
final ctx =
|
final ctx =
|
||||||
engine.analyzeNode(viewDeclaration.node, view.file!.parseResult.sql);
|
engine.analyzeNode(viewDeclaration.node, view.file!.parseResult.sql);
|
||||||
|
@ -30,7 +30,7 @@ class ViewAnalyzer extends BaseAnalyzer {
|
||||||
const SchemaFromCreateTable(driftExtensions: true)
|
const SchemaFromCreateTable(driftExtensions: true)
|
||||||
.readView(ctx, declaration);
|
.readView(ctx, declaration);
|
||||||
|
|
||||||
final columns = <MoorColumn>[];
|
final columns = <DriftColumn>[];
|
||||||
final columnDartNames = <String>{};
|
final columnDartNames = <String>{};
|
||||||
for (final column in parserView.resolvedColumns) {
|
for (final column in parserView.resolvedColumns) {
|
||||||
final type = column.type;
|
final type = column.type;
|
||||||
|
@ -39,7 +39,7 @@ class ViewAnalyzer extends BaseAnalyzer {
|
||||||
converter = (type.hint as TypeConverterHint).converter;
|
converter = (type.hint as TypeConverterHint).converter;
|
||||||
}
|
}
|
||||||
|
|
||||||
final moorColumn = MoorColumn(
|
final moorColumn = DriftColumn(
|
||||||
type: mapper.resolvedToMoor(type),
|
type: mapper.resolvedToMoor(type),
|
||||||
name: ColumnName.explicitly(column.name),
|
name: ColumnName.explicitly(column.name),
|
||||||
nullable: type?.nullable == true,
|
nullable: type?.nullable == true,
|
||||||
|
@ -59,7 +59,7 @@ class ViewAnalyzer extends BaseAnalyzer {
|
||||||
if (desiredNames.useExistingDartClass) {
|
if (desiredNames.useExistingDartClass) {
|
||||||
final clazz = await findDartClass(step, imports, dataClassName);
|
final clazz = await findDartClass(step, imports, dataClassName);
|
||||||
if (clazz == null) {
|
if (clazz == null) {
|
||||||
step.reportError(ErrorInMoorFile(
|
step.reportError(ErrorInDriftFile(
|
||||||
span: declaration.viewNameToken!.span,
|
span: declaration.viewNameToken!.span,
|
||||||
message: 'Existing Dart class $dataClassName was not found, are '
|
message: 'Existing Dart class $dataClassName was not found, are '
|
||||||
'you missing an import?',
|
'you missing an import?',
|
||||||
|
|
|
@ -9,9 +9,9 @@ import 'package:drift_dev/src/backends/backend.dart';
|
||||||
import 'package:logging/logging.dart';
|
import 'package:logging/logging.dart';
|
||||||
|
|
||||||
class BuildBackend extends Backend {
|
class BuildBackend extends Backend {
|
||||||
final MoorOptions options;
|
final DriftOptions options;
|
||||||
|
|
||||||
BuildBackend([this.options = const MoorOptions.defaults()]);
|
BuildBackend([this.options = const DriftOptions.defaults()]);
|
||||||
|
|
||||||
BuildBackendTask createTask(BuildStep step) {
|
BuildBackendTask createTask(BuildStep step) {
|
||||||
return BuildBackendTask(step, this);
|
return BuildBackendTask(step, this);
|
||||||
|
@ -71,7 +71,7 @@ class BuildBackendTask extends BackendTask {
|
||||||
// we try to detect all calls of resolveTypeOf in an earlier builder and
|
// we try to detect all calls of resolveTypeOf in an earlier builder and
|
||||||
// prepare the result. See PreprocessBuilder for details
|
// prepare the result. See PreprocessBuilder for details
|
||||||
final preparedHelperFile =
|
final preparedHelperFile =
|
||||||
_resolve(context).changeExtension('.dart_in_moor');
|
_resolve(context).changeExtension('.dart_in_drift');
|
||||||
final temporaryFile = _resolve(context).changeExtension('.temp.dart');
|
final temporaryFile = _resolve(context).changeExtension('.temp.dart');
|
||||||
|
|
||||||
if (!await step.canRead(preparedHelperFile)) {
|
if (!await step.canRead(preparedHelperFile)) {
|
||||||
|
|
|
@ -6,7 +6,7 @@ import 'package:drift_dev/src/analyzer/runner/task.dart';
|
||||||
import 'package:drift_dev/src/analyzer/session.dart';
|
import 'package:drift_dev/src/analyzer/session.dart';
|
||||||
import 'package:drift_dev/src/backends/build/build_backend.dart';
|
import 'package:drift_dev/src/backends/build/build_backend.dart';
|
||||||
import 'package:drift_dev/src/backends/build/generators/dao_generator.dart';
|
import 'package:drift_dev/src/backends/build/generators/dao_generator.dart';
|
||||||
import 'package:drift_dev/src/backends/build/generators/moor_generator.dart';
|
import 'package:drift_dev/src/backends/build/generators/database_generator.dart';
|
||||||
import 'package:drift_dev/writer.dart';
|
import 'package:drift_dev/writer.dart';
|
||||||
import 'package:source_gen/source_gen.dart';
|
import 'package:source_gen/source_gen.dart';
|
||||||
|
|
||||||
|
@ -16,8 +16,8 @@ class _BuilderFlags {
|
||||||
|
|
||||||
final _flags = Resource(() => _BuilderFlags());
|
final _flags = Resource(() => _BuilderFlags());
|
||||||
|
|
||||||
mixin MoorBuilder on Builder {
|
mixin DriftBuilder on Builder {
|
||||||
MoorOptions get options;
|
DriftOptions get options;
|
||||||
bool get isForNewDriftPackage;
|
bool get isForNewDriftPackage;
|
||||||
|
|
||||||
Writer createWriter() {
|
Writer createWriter() {
|
||||||
|
@ -48,14 +48,14 @@ mixin MoorBuilder on Builder {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
T _createBuilder<T extends MoorBuilder>(
|
T _createBuilder<T extends DriftBuilder>(
|
||||||
BuilderOptions options,
|
BuilderOptions options,
|
||||||
T Function(List<Generator> generators, MoorOptions parsedOptions) creator,
|
T Function(List<Generator> generators, DriftOptions parsedOptions) creator,
|
||||||
) {
|
) {
|
||||||
final parsedOptions = MoorOptions.fromJson(options.config);
|
final parsedOptions = DriftOptions.fromJson(options.config);
|
||||||
|
|
||||||
final generators = <Generator>[
|
final generators = <Generator>[
|
||||||
MoorGenerator(),
|
DriftDatabaseGenerator(),
|
||||||
DaoGenerator(),
|
DaoGenerator(),
|
||||||
];
|
];
|
||||||
|
|
||||||
|
@ -68,21 +68,21 @@ T _createBuilder<T extends MoorBuilder>(
|
||||||
return builder;
|
return builder;
|
||||||
}
|
}
|
||||||
|
|
||||||
class MoorSharedPartBuilder extends SharedPartBuilder with MoorBuilder {
|
class DriftSharedPartBuilder extends SharedPartBuilder with DriftBuilder {
|
||||||
@override
|
@override
|
||||||
final MoorOptions options;
|
final DriftOptions options;
|
||||||
|
|
||||||
@override
|
@override
|
||||||
final bool isForNewDriftPackage;
|
final bool isForNewDriftPackage;
|
||||||
|
|
||||||
MoorSharedPartBuilder._(List<Generator> generators, String name, this.options,
|
DriftSharedPartBuilder._(List<Generator> generators, String name,
|
||||||
this.isForNewDriftPackage)
|
this.options, this.isForNewDriftPackage)
|
||||||
: super(generators, name);
|
: super(generators, name);
|
||||||
|
|
||||||
factory MoorSharedPartBuilder(BuilderOptions options,
|
factory DriftSharedPartBuilder(BuilderOptions options,
|
||||||
{bool isForNewDriftPackage = false}) {
|
{bool isForNewDriftPackage = false}) {
|
||||||
return _createBuilder(options, (generators, parsedOptions) {
|
return _createBuilder(options, (generators, parsedOptions) {
|
||||||
return MoorSharedPartBuilder._(
|
return DriftSharedPartBuilder._(
|
||||||
generators, 'moor', parsedOptions, isForNewDriftPackage);
|
generators, 'moor', parsedOptions, isForNewDriftPackage);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
@ -102,21 +102,21 @@ class MoorSharedPartBuilder extends SharedPartBuilder with MoorBuilder {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
class MoorPartBuilder extends PartBuilder with MoorBuilder {
|
class DriftPartBuilder extends PartBuilder with DriftBuilder {
|
||||||
@override
|
@override
|
||||||
final MoorOptions options;
|
final DriftOptions options;
|
||||||
|
|
||||||
@override
|
@override
|
||||||
final bool isForNewDriftPackage;
|
final bool isForNewDriftPackage;
|
||||||
|
|
||||||
MoorPartBuilder._(List<Generator> generators, String extension, this.options,
|
DriftPartBuilder._(List<Generator> generators, String extension, this.options,
|
||||||
this.isForNewDriftPackage)
|
this.isForNewDriftPackage)
|
||||||
: super(generators, extension);
|
: super(generators, extension);
|
||||||
|
|
||||||
factory MoorPartBuilder(BuilderOptions options,
|
factory DriftPartBuilder(BuilderOptions options,
|
||||||
{bool isForNewDriftPackage = false}) {
|
{bool isForNewDriftPackage = false}) {
|
||||||
return _createBuilder(options, (generators, parsedOptions) {
|
return _createBuilder(options, (generators, parsedOptions) {
|
||||||
return MoorPartBuilder._(
|
return DriftPartBuilder._(
|
||||||
generators,
|
generators,
|
||||||
isForNewDriftPackage ? '.drift.dart' : '.moor.dart',
|
isForNewDriftPackage ? '.drift.dart' : '.moor.dart',
|
||||||
parsedOptions,
|
parsedOptions,
|
||||||
|
@ -126,5 +126,5 @@ class MoorPartBuilder extends PartBuilder with MoorBuilder {
|
||||||
}
|
}
|
||||||
|
|
||||||
abstract class BaseGenerator {
|
abstract class BaseGenerator {
|
||||||
late MoorBuilder builder;
|
late DriftBuilder builder;
|
||||||
}
|
}
|
|
@ -1,5 +1,5 @@
|
||||||
import 'package:build/build.dart';
|
import 'package:build/build.dart';
|
||||||
import 'package:drift_dev/src/backends/build/moor_builder.dart';
|
import 'package:drift_dev/src/backends/build/drift_builder.dart';
|
||||||
import 'package:drift_dev/src/utils/type_utils.dart';
|
import 'package:drift_dev/src/utils/type_utils.dart';
|
||||||
import 'package:drift_dev/writer.dart';
|
import 'package:drift_dev/writer.dart';
|
||||||
import 'package:source_gen/source_gen.dart';
|
import 'package:source_gen/source_gen.dart';
|
||||||
|
@ -8,7 +8,7 @@ import '../../../model/base_entity.dart';
|
||||||
|
|
||||||
class DaoGenerator extends Generator implements BaseGenerator {
|
class DaoGenerator extends Generator implements BaseGenerator {
|
||||||
@override
|
@override
|
||||||
late MoorBuilder builder;
|
late DriftBuilder builder;
|
||||||
|
|
||||||
@override
|
@override
|
||||||
Future<String> generate(LibraryReader library, BuildStep buildStep) async {
|
Future<String> generate(LibraryReader library, BuildStep buildStep) async {
|
||||||
|
@ -25,7 +25,7 @@ class DaoGenerator extends Generator implements BaseGenerator {
|
||||||
classScope.leaf().write('mixin _\$${daoName}Mixin on '
|
classScope.leaf().write('mixin _\$${daoName}Mixin on '
|
||||||
'DatabaseAccessor<$dbTypeName> {\n');
|
'DatabaseAccessor<$dbTypeName> {\n');
|
||||||
|
|
||||||
for (final entity in dao.entities.whereType<MoorEntityWithResultSet>()) {
|
for (final entity in dao.entities.whereType<DriftEntityWithResultSet>()) {
|
||||||
final infoType = entity.entityInfoName;
|
final infoType = entity.entityInfoName;
|
||||||
final getterName = entity.dbGetterName;
|
final getterName = entity.dbGetterName;
|
||||||
classScope.leaf().write(
|
classScope.leaf().write(
|
||||||
|
|
|
@ -1,14 +1,14 @@
|
||||||
import 'package:build/build.dart';
|
import 'package:build/build.dart';
|
||||||
import 'package:drift_dev/src/backends/build/moor_builder.dart';
|
import 'package:drift_dev/src/backends/build/drift_builder.dart';
|
||||||
import 'package:drift_dev/writer.dart';
|
import 'package:drift_dev/writer.dart';
|
||||||
import 'package:pub_semver/pub_semver.dart';
|
import 'package:pub_semver/pub_semver.dart';
|
||||||
import 'package:source_gen/source_gen.dart';
|
import 'package:source_gen/source_gen.dart';
|
||||||
|
|
||||||
final _minLanguageVersion = Version(2, 12, 0);
|
final _minLanguageVersion = Version(2, 12, 0);
|
||||||
|
|
||||||
class MoorGenerator extends Generator implements BaseGenerator {
|
class DriftDatabaseGenerator extends Generator implements BaseGenerator {
|
||||||
@override
|
@override
|
||||||
late MoorBuilder builder;
|
late DriftBuilder builder;
|
||||||
|
|
||||||
@override
|
@override
|
||||||
Future<String> generate(LibraryReader library, BuildStep buildStep) async {
|
Future<String> generate(LibraryReader library, BuildStep buildStep) async {
|
|
@ -5,26 +5,26 @@ import 'package:build/build.dart';
|
||||||
import 'package:drift_dev/src/utils/string_escaper.dart';
|
import 'package:drift_dev/src/utils/string_escaper.dart';
|
||||||
import 'package:sqlparser/sqlparser.dart';
|
import 'package:sqlparser/sqlparser.dart';
|
||||||
|
|
||||||
/// A support builder that runs before the main moor_generator to parse and
|
/// A support builder that runs before the main generator to parse and resolve
|
||||||
/// resolve inline Dart resources in a moor file.
|
/// inline Dart resources in a moor file.
|
||||||
///
|
///
|
||||||
/// We use this builder to extract and analyze inline Dart expressions from moor
|
/// We use this builder to extract and analyze inline Dart expressions from
|
||||||
/// files, which are mainly used for type converters. For instance, let's say
|
/// drift files, which are mainly used for type converters. For instance, let's
|
||||||
/// we had a moor file like this:
|
/// say we had a drift file like this:
|
||||||
/// ```
|
/// ```
|
||||||
/// -- called input.moor
|
/// -- called input.drift
|
||||||
/// import 'package:my_package/converter.dart';
|
/// import 'package:my_package/converter.dart';
|
||||||
///
|
///
|
||||||
/// CREATE TABLE users (
|
/// CREATE TABLE users (
|
||||||
/// preferences TEXT MAPPED BY `const PreferencesConverter()`
|
/// preferences TEXT MAPPED BY `const PreferencesConverter()`
|
||||||
/// );
|
/// );
|
||||||
/// ```
|
/// ```
|
||||||
/// For that file, the [PreprocessBuilder] would generate a `.dart_in_moor` file
|
/// For that file, the [PreprocessBuilder] would generate a `.dart_in_drift`
|
||||||
/// which contains information about the static type of all expressions in the
|
/// file which contains information about the static type of all expressions in
|
||||||
/// moor file. The main generator can then read the `.dart_in_moor` file to
|
/// the drift file. The main generator can then read the `.dart_in_drift` file
|
||||||
/// resolve those expressions.
|
/// to resolve those expressions.
|
||||||
class PreprocessBuilder extends Builder {
|
class PreprocessBuilder extends Builder {
|
||||||
static const _outputs = ['.temp.dart', '.dart_in_moor'];
|
static const _outputs = ['.temp.dart', '.dart_in_drift'];
|
||||||
|
|
||||||
final bool isForNewDriftPackage;
|
final bool isForNewDriftPackage;
|
||||||
|
|
||||||
|
@ -112,7 +112,7 @@ class PreprocessBuilder extends Builder {
|
||||||
await buildStep.writeAsString(tempDartAsset, dartBuffer.toString());
|
await buildStep.writeAsString(tempDartAsset, dartBuffer.toString());
|
||||||
|
|
||||||
// And the file mapping Dart expressions onto the variable names here
|
// And the file mapping Dart expressions onto the variable names here
|
||||||
final outputAsset = input.changeExtension('.dart_in_moor');
|
final outputAsset = input.changeExtension('.dart_in_drift');
|
||||||
await buildStep.writeAsString(outputAsset, json.encode(codeToField));
|
await buildStep.writeAsString(outputAsset, json.encode(codeToField));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -28,7 +28,7 @@ class MoorDriver {
|
||||||
MoorDriver(this._resourceProvider,
|
MoorDriver(this._resourceProvider,
|
||||||
{required String contextRoot,
|
{required String contextRoot,
|
||||||
String? sdkPath,
|
String? sdkPath,
|
||||||
MoorOptions options = const MoorOptions.defaults()}) {
|
DriftOptions options = const DriftOptions.defaults()}) {
|
||||||
final overlayed = OverlayResourceProvider(_resourceProvider);
|
final overlayed = OverlayResourceProvider(_resourceProvider);
|
||||||
final collection = AnalysisContextCollection(
|
final collection = AnalysisContextCollection(
|
||||||
includedPaths: [contextRoot],
|
includedPaths: [contextRoot],
|
||||||
|
@ -44,7 +44,7 @@ class MoorDriver {
|
||||||
MoorDriver.forContext(this._resourceProvider, this.context) {
|
MoorDriver.forContext(this._resourceProvider, this.context) {
|
||||||
final overlayed = OverlayResourceProvider(_resourceProvider);
|
final overlayed = OverlayResourceProvider(_resourceProvider);
|
||||||
backend = StandaloneBackend(context, overlayed);
|
backend = StandaloneBackend(context, overlayed);
|
||||||
session = MoorSession(backend, options: const MoorOptions.defaults());
|
session = MoorSession(backend, options: const DriftOptions.defaults());
|
||||||
}
|
}
|
||||||
|
|
||||||
bool _ownsFile(String path) =>
|
bool _ownsFile(String path) =>
|
||||||
|
@ -85,7 +85,7 @@ class MoorDriver {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Attempt to load the appropriate [MoorOptions] by reading the `build.yaml`
|
/// Attempt to load the appropriate [DriftOptions] by reading the `build.yaml`
|
||||||
/// located in the context root.
|
/// located in the context root.
|
||||||
///
|
///
|
||||||
/// When something fails, the default options will be used an an error message
|
/// When something fails, the default options will be used an an error message
|
||||||
|
|
|
@ -7,7 +7,7 @@ var _initialized = false;
|
||||||
/// Configures the [Logger.root] logger to work with the plugin. Sadly, we don't
|
/// Configures the [Logger.root] logger to work with the plugin. Sadly, we don't
|
||||||
/// really have a way to view [print] outputs from plugins, so we use the
|
/// really have a way to view [print] outputs from plugins, so we use the
|
||||||
/// diagnostics notification for that.
|
/// diagnostics notification for that.
|
||||||
void setupLogger(MoorPlugin plugin) {
|
void setupLogger(DriftPlugin plugin) {
|
||||||
assert(!_initialized, 'Logger initialized multiple times');
|
assert(!_initialized, 'Logger initialized multiple times');
|
||||||
|
|
||||||
Logger.root.level = Level.ALL;
|
Logger.root.level = Level.ALL;
|
||||||
|
|
|
@ -25,18 +25,18 @@ import 'package:drift_dev/src/services/ide/moor_ide.dart';
|
||||||
|
|
||||||
import 'logger.dart';
|
import 'logger.dart';
|
||||||
|
|
||||||
class MoorPlugin extends ServerPlugin
|
class DriftPlugin extends ServerPlugin
|
||||||
with OutlineMixin, FoldingMixin, CompletionMixin, NavigationMixin {
|
with OutlineMixin, FoldingMixin, CompletionMixin, NavigationMixin {
|
||||||
final Map<AnalysisContext, MoorDriver> drivers = {};
|
final Map<AnalysisContext, MoorDriver> drivers = {};
|
||||||
|
|
||||||
late final ErrorService errorService = ErrorService(this);
|
late final ErrorService errorService = ErrorService(this);
|
||||||
|
|
||||||
MoorPlugin(ResourceProvider provider) : super(resourceProvider: provider) {
|
DriftPlugin(ResourceProvider provider) : super(resourceProvider: provider) {
|
||||||
setupLogger(this);
|
setupLogger(this);
|
||||||
}
|
}
|
||||||
|
|
||||||
factory MoorPlugin.forProduction() {
|
factory DriftPlugin.forProduction() {
|
||||||
return MoorPlugin(PhysicalResourceProvider.INSTANCE);
|
return DriftPlugin(PhysicalResourceProvider.INSTANCE);
|
||||||
}
|
}
|
||||||
|
|
||||||
@override
|
@override
|
||||||
|
@ -136,7 +136,7 @@ class MoorPlugin extends ServerPlugin
|
||||||
}
|
}
|
||||||
|
|
||||||
void _checkIsMoorFile(FoundFile file) {
|
void _checkIsMoorFile(FoundFile file) {
|
||||||
if (file.type != FileType.moor) {
|
if (file.type != FileType.drift) {
|
||||||
throw RequestFailure(
|
throw RequestFailure(
|
||||||
plugin.RequestError(plugin.RequestErrorCode.INVALID_PARAMETER,
|
plugin.RequestError(plugin.RequestErrorCode.INVALID_PARAMETER,
|
||||||
'Not a moor file: ${file.uri}'),
|
'Not a moor file: ${file.uri}'),
|
||||||
|
|
|
@ -9,7 +9,7 @@ const _genericError = 'moor.errorGeneric';
|
||||||
/// Sends information about errors, lints and warnings encountered in a `.moor`
|
/// Sends information about errors, lints and warnings encountered in a `.moor`
|
||||||
/// file to the analyzer.
|
/// file to the analyzer.
|
||||||
class ErrorService {
|
class ErrorService {
|
||||||
final MoorPlugin plugin;
|
final DriftPlugin plugin;
|
||||||
|
|
||||||
ErrorService(this.plugin);
|
ErrorService(this.plugin);
|
||||||
|
|
||||||
|
@ -39,8 +39,8 @@ class ErrorService {
|
||||||
plugin.channel.sendNotification(params.toNotification());
|
plugin.channel.sendNotification(params.toNotification());
|
||||||
}
|
}
|
||||||
|
|
||||||
Location _findLocationForError(MoorError error, String path) {
|
Location _findLocationForError(DriftError error, String path) {
|
||||||
if (error is ErrorInMoorFile) {
|
if (error is ErrorInDriftFile) {
|
||||||
final span = error.span;
|
final span = error.span;
|
||||||
final start = span.start;
|
final start = span.start;
|
||||||
final end = span.end;
|
final end = span.end;
|
||||||
|
|
|
@ -83,7 +83,7 @@ class _NavigationVisitor extends RecursiveVisitor<void, void> {
|
||||||
}
|
}
|
||||||
|
|
||||||
Iterable<Location?> _locationOfColumn(Column column) sync* {
|
Iterable<Location?> _locationOfColumn(Column column) sync* {
|
||||||
final declaration = column.meta<MoorColumn>()?.declaration;
|
final declaration = column.meta<DriftColumn>()?.declaration;
|
||||||
if (declaration != null) {
|
if (declaration != null) {
|
||||||
// the column was declared in a table and we happen to know where the
|
// the column was declared in a table and we happen to know where the
|
||||||
// declaration is - point to that declaration.
|
// declaration is - point to that declaration.
|
||||||
|
@ -110,7 +110,7 @@ class _NavigationVisitor extends RecursiveVisitor<void, void> {
|
||||||
final resolved = e.resolved;
|
final resolved = e.resolved;
|
||||||
|
|
||||||
if (resolved is Table) {
|
if (resolved is Table) {
|
||||||
final declaration = resolved.meta<MoorTable>()?.declaration;
|
final declaration = resolved.meta<DriftTable>()?.declaration;
|
||||||
if (declaration != null) {
|
if (declaration != null) {
|
||||||
_reportForSpan(
|
_reportForSpan(
|
||||||
e.span, ElementKind.CLASS, locationOfDeclaration(declaration)!);
|
e.span, ElementKind.CLASS, locationOfDeclaration(declaration)!);
|
||||||
|
|
|
@ -12,15 +12,15 @@ import 'package:source_span/source_span.dart';
|
||||||
mixin _MoorBaseRequest {
|
mixin _MoorBaseRequest {
|
||||||
FoundFile get file;
|
FoundFile get file;
|
||||||
|
|
||||||
bool get isMoor => file.type == FileType.moor;
|
bool get isMoor => file.type == FileType.drift;
|
||||||
bool get isMoorAndParsed => isMoor && file.isParsed;
|
bool get isMoorAndParsed => isMoor && file.isParsed;
|
||||||
bool get isMoorAndAnalyzed => isMoor && file.isAnalyzed;
|
bool get isMoorAndAnalyzed => isMoor && file.isAnalyzed;
|
||||||
|
|
||||||
String get path => file.uri.path;
|
String get path => file.uri.path;
|
||||||
|
|
||||||
ParsedMoorFile get parsedMoor {
|
ParsedDriftFile get parsedMoor {
|
||||||
assert(isMoorAndParsed);
|
assert(isMoorAndParsed);
|
||||||
return file.currentResult as ParsedMoorFile;
|
return file.currentResult as ParsedDriftFile;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -33,7 +33,7 @@ Location? locationOfDeclaration(Declaration declaration) {
|
||||||
final file = declaration.declaration.file;
|
final file = declaration.declaration.file;
|
||||||
if (declaration is DartDeclaration) {
|
if (declaration is DartDeclaration) {
|
||||||
return _locationForSpan(spanForElement(declaration.element), file);
|
return _locationForSpan(spanForElement(declaration.element), file);
|
||||||
} else if (declaration is MoorDeclaration) {
|
} else if (declaration is DriftFileDeclaration) {
|
||||||
return locationOfNode(file, declaration.node);
|
return locationOfNode(file, declaration.node);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -78,9 +78,9 @@ class GenerateUtilsCommand extends Command {
|
||||||
'Wrote ${schema.length + 1} files into ${p.relative(outputDir.path)}');
|
'Wrote ${schema.length + 1} files into ${p.relative(outputDir.path)}');
|
||||||
}
|
}
|
||||||
|
|
||||||
Future<Map<int, List<MoorSchemaEntity>>> _parseSchema(
|
Future<Map<int, List<DriftSchemaEntity>>> _parseSchema(
|
||||||
Directory directory) async {
|
Directory directory) async {
|
||||||
final results = <int, List<MoorSchemaEntity>>{};
|
final results = <int, List<DriftSchemaEntity>>{};
|
||||||
|
|
||||||
await for (final entity in directory.list()) {
|
await for (final entity in directory.list()) {
|
||||||
final basename = p.basename(entity.path);
|
final basename = p.basename(entity.path);
|
||||||
|
@ -101,7 +101,7 @@ class GenerateUtilsCommand extends Command {
|
||||||
Future<void> _writeSchemaFile(
|
Future<void> _writeSchemaFile(
|
||||||
Directory output,
|
Directory output,
|
||||||
int version,
|
int version,
|
||||||
List<MoorSchemaEntity> entities,
|
List<DriftSchemaEntity> entities,
|
||||||
bool dataClasses,
|
bool dataClasses,
|
||||||
bool companions,
|
bool companions,
|
||||||
bool isForMoor,
|
bool isForMoor,
|
||||||
|
|
|
@ -11,7 +11,7 @@ import 'package:stream_transform/stream_transform.dart';
|
||||||
class MoorProject {
|
class MoorProject {
|
||||||
/// The build configuration for this project.
|
/// The build configuration for this project.
|
||||||
final BuildConfig buildConfig;
|
final BuildConfig buildConfig;
|
||||||
final MoorOptions moorOptions;
|
final DriftOptions moorOptions;
|
||||||
|
|
||||||
final Directory directory;
|
final Directory directory;
|
||||||
|
|
||||||
|
|
|
@ -7,7 +7,7 @@ import 'package:drift_dev/writer.dart';
|
||||||
/// Some schema entity found.
|
/// Some schema entity found.
|
||||||
///
|
///
|
||||||
/// Most commonly a table, but it can also be a trigger.
|
/// Most commonly a table, but it can also be a trigger.
|
||||||
abstract class MoorSchemaEntity implements HasDeclaration {
|
abstract class DriftSchemaEntity implements HasDeclaration {
|
||||||
/// All entities that have to be created before this entity can be created.
|
/// All entities that have to be created before this entity can be created.
|
||||||
///
|
///
|
||||||
/// For tables, this can be contents of a `REFERENCES` clause. For triggers,
|
/// For tables, this can be contents of a `REFERENCES` clause. For triggers,
|
||||||
|
@ -18,7 +18,7 @@ abstract class MoorSchemaEntity implements HasDeclaration {
|
||||||
///
|
///
|
||||||
/// The generator will verify that the graph of entities and [references]
|
/// The generator will verify that the graph of entities and [references]
|
||||||
/// is acyclic and sort them topologically.
|
/// is acyclic and sort them topologically.
|
||||||
Iterable<MoorSchemaEntity> get references;
|
Iterable<DriftSchemaEntity> get references;
|
||||||
|
|
||||||
/// A human readable name of this entity, like the table name.
|
/// A human readable name of this entity, like the table name.
|
||||||
String get displayName;
|
String get displayName;
|
||||||
|
@ -29,9 +29,9 @@ abstract class MoorSchemaEntity implements HasDeclaration {
|
||||||
String? get dbGetterName;
|
String? get dbGetterName;
|
||||||
}
|
}
|
||||||
|
|
||||||
abstract class MoorEntityWithResultSet extends MoorSchemaEntity {
|
abstract class DriftEntityWithResultSet extends DriftSchemaEntity {
|
||||||
/// The columns declared in this table or view.
|
/// The columns declared in this table or view.
|
||||||
List<MoorColumn> get columns;
|
List<DriftColumn> get columns;
|
||||||
|
|
||||||
/// The name of the Dart row class for this result set.
|
/// The name of the Dart row class for this result set.
|
||||||
@Deprecated('Use dartTypeCode instead')
|
@Deprecated('Use dartTypeCode instead')
|
||||||
|
@ -70,7 +70,7 @@ class ExistingRowClass {
|
||||||
/// The Dart types that should be used to instantiate the [targetClass].
|
/// The Dart types that should be used to instantiate the [targetClass].
|
||||||
final List<DartType> typeInstantiation;
|
final List<DartType> typeInstantiation;
|
||||||
final ConstructorElement constructor;
|
final ConstructorElement constructor;
|
||||||
final Map<MoorColumn, ParameterElement> mapping;
|
final Map<DriftColumn, ParameterElement> mapping;
|
||||||
|
|
||||||
/// Generate toCompanion for data class
|
/// Generate toCompanion for data class
|
||||||
final bool generateInsertable;
|
final bool generateInsertable;
|
||||||
|
|
|
@ -45,7 +45,7 @@ class ColumnName {
|
||||||
}
|
}
|
||||||
|
|
||||||
/// A column, as specified by a getter in a table.
|
/// A column, as specified by a getter in a table.
|
||||||
class MoorColumn implements HasDeclaration, HasType {
|
class DriftColumn implements HasDeclaration, HasType {
|
||||||
/// The getter name of this column in the table class. It will also be used
|
/// The getter name of this column in the table class. It will also be used
|
||||||
/// as getter name in the TableInfo class (as it needs to override the field)
|
/// as getter name in the TableInfo class (as it needs to override the field)
|
||||||
/// and in the generated data class that will be generated for each table.
|
/// and in the generated data class that will be generated for each table.
|
||||||
|
@ -68,7 +68,7 @@ class MoorColumn implements HasDeclaration, HasType {
|
||||||
|
|
||||||
/// An (optional) name to use as a json key instead of the [dartGetterName].
|
/// An (optional) name to use as a json key instead of the [dartGetterName].
|
||||||
final String? overriddenJsonName;
|
final String? overriddenJsonName;
|
||||||
String getJsonKey([MoorOptions options = const MoorOptions.defaults()]) {
|
String getJsonKey([DriftOptions options = const DriftOptions.defaults()]) {
|
||||||
if (overriddenJsonName != null) return overriddenJsonName!;
|
if (overriddenJsonName != null) return overriddenJsonName!;
|
||||||
|
|
||||||
final useColumnName = options.useColumnNameAsJsonKeyWhenDefinedInMoorFile &&
|
final useColumnName = options.useColumnNameAsJsonKeyWhenDefinedInMoorFile &&
|
||||||
|
@ -112,7 +112,7 @@ class MoorColumn implements HasDeclaration, HasType {
|
||||||
bool get isGenerated => generatedAs != null;
|
bool get isGenerated => generatedAs != null;
|
||||||
|
|
||||||
/// Parent table
|
/// Parent table
|
||||||
MoorTable? table;
|
DriftTable? table;
|
||||||
|
|
||||||
/// The column type from the dsl library. For instance, if a table has
|
/// 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
|
/// declared an `IntColumn`, the matching dsl column name would also be an
|
||||||
|
@ -186,7 +186,7 @@ class MoorColumn implements HasDeclaration, HasType {
|
||||||
@override
|
@override
|
||||||
bool get isArray => false;
|
bool get isArray => false;
|
||||||
|
|
||||||
MoorColumn({
|
DriftColumn({
|
||||||
required this.type,
|
required this.type,
|
||||||
required this.dartGetterName,
|
required this.dartGetterName,
|
||||||
required this.name,
|
required this.name,
|
||||||
|
@ -273,8 +273,8 @@ class UnresolvedDartForeignKeyReference extends ColumnFeature {
|
||||||
}
|
}
|
||||||
|
|
||||||
class ResolvedDartForeignKeyReference extends ColumnFeature {
|
class ResolvedDartForeignKeyReference extends ColumnFeature {
|
||||||
final MoorTable otherTable;
|
final DriftTable otherTable;
|
||||||
final MoorColumn otherColumn;
|
final DriftColumn otherColumn;
|
||||||
final ReferenceAction? onUpdate;
|
final ReferenceAction? onUpdate;
|
||||||
final ReferenceAction? onDelete;
|
final ReferenceAction? onDelete;
|
||||||
|
|
||||||
|
|
|
@ -4,7 +4,7 @@ import 'package:drift_dev/moor_generator.dart';
|
||||||
import 'package:drift_dev/src/analyzer/runner/file_graph.dart';
|
import 'package:drift_dev/src/analyzer/runner/file_graph.dart';
|
||||||
|
|
||||||
/// Abstract class for database and dao elements.
|
/// Abstract class for database and dao elements.
|
||||||
abstract class BaseMoorAccessor implements HasDeclaration {
|
abstract class BaseDriftAccessor implements HasDeclaration {
|
||||||
@override
|
@override
|
||||||
final DatabaseOrDaoDeclaration? declaration;
|
final DatabaseOrDaoDeclaration? declaration;
|
||||||
|
|
||||||
|
@ -16,7 +16,7 @@ abstract class BaseMoorAccessor implements HasDeclaration {
|
||||||
/// This contains the `tables` field from a `UseMoor` or `UseDao` annotation,
|
/// This contains the `tables` field from a `UseMoor` or `UseDao` annotation,
|
||||||
/// but not tables that are declared in imported moor files. Use [tables] for
|
/// but not tables that are declared in imported moor files. Use [tables] for
|
||||||
/// that.
|
/// that.
|
||||||
final List<MoorTable> declaredTables;
|
final List<DriftTable> declaredTables;
|
||||||
|
|
||||||
/// All views that have been declared on this accessor directly.
|
/// All views that have been declared on this accessor directly.
|
||||||
///
|
///
|
||||||
|
@ -33,11 +33,11 @@ abstract class BaseMoorAccessor implements HasDeclaration {
|
||||||
|
|
||||||
/// All entities for this database accessor. This contains [declaredTables]
|
/// All entities for this database accessor. This contains [declaredTables]
|
||||||
/// and all tables, triggers and other entities available through includes.
|
/// and all tables, triggers and other entities available through includes.
|
||||||
List<MoorSchemaEntity> entities = [];
|
List<DriftSchemaEntity> entities = [];
|
||||||
|
|
||||||
/// All tables for this database accessor. This contains the [declaredTables]
|
/// All tables for this database accessor. This contains the [declaredTables]
|
||||||
/// and all tables that are reachable through includes.
|
/// and all tables that are reachable through includes.
|
||||||
Iterable<MoorTable> get tables => entities.whereType();
|
Iterable<DriftTable> get tables => entities.whereType();
|
||||||
|
|
||||||
/// All views for this database accesssor.
|
/// All views for this database accesssor.
|
||||||
Iterable<MoorView> get views => entities.whereType();
|
Iterable<MoorView> get views => entities.whereType();
|
||||||
|
@ -51,12 +51,12 @@ abstract class BaseMoorAccessor implements HasDeclaration {
|
||||||
/// Resolved imports from this file.
|
/// Resolved imports from this file.
|
||||||
List<FoundFile>? imports = [];
|
List<FoundFile>? imports = [];
|
||||||
|
|
||||||
BaseMoorAccessor._(this.declaration, this.declaredTables, this.declaredViews,
|
BaseDriftAccessor._(this.declaration, this.declaredTables, this.declaredViews,
|
||||||
this.declaredIncludes, this.declaredQueries);
|
this.declaredIncludes, this.declaredQueries);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// A database, declared via a `UseMoor` annotation on a Dart class.
|
/// A database, declared via a `UseMoor` annotation on a Dart class.
|
||||||
class Database extends BaseMoorAccessor {
|
class Database extends BaseDriftAccessor {
|
||||||
final List<DartType> daos;
|
final List<DartType> daos;
|
||||||
|
|
||||||
/// If the source database class overrides `schemaVersion` and returns a
|
/// If the source database class overrides `schemaVersion` and returns a
|
||||||
|
@ -70,7 +70,7 @@ class Database extends BaseMoorAccessor {
|
||||||
this.daos = const [],
|
this.daos = const [],
|
||||||
this.schemaVersion,
|
this.schemaVersion,
|
||||||
DatabaseOrDaoDeclaration? declaration,
|
DatabaseOrDaoDeclaration? declaration,
|
||||||
List<MoorTable> declaredTables = const [],
|
List<DriftTable> declaredTables = const [],
|
||||||
List<MoorView> declaredViews = const [],
|
List<MoorView> declaredViews = const [],
|
||||||
List<String> declaredIncludes = const [],
|
List<String> declaredIncludes = const [],
|
||||||
List<DeclaredQuery> declaredQueries = const [],
|
List<DeclaredQuery> declaredQueries = const [],
|
||||||
|
@ -79,14 +79,14 @@ class Database extends BaseMoorAccessor {
|
||||||
}
|
}
|
||||||
|
|
||||||
/// A dao, declared via an `UseDao` annotation on a Dart class.
|
/// A dao, declared via an `UseDao` annotation on a Dart class.
|
||||||
class Dao extends BaseMoorAccessor {
|
class Dao extends BaseDriftAccessor {
|
||||||
/// The database class this dao belongs to.
|
/// The database class this dao belongs to.
|
||||||
final DartType dbClass;
|
final DartType dbClass;
|
||||||
|
|
||||||
Dao({
|
Dao({
|
||||||
required this.dbClass,
|
required this.dbClass,
|
||||||
DatabaseOrDaoDeclaration? declaration,
|
DatabaseOrDaoDeclaration? declaration,
|
||||||
required List<MoorTable> declaredTables,
|
required List<DriftTable> declaredTables,
|
||||||
List<MoorView> declaredViews = const [],
|
List<MoorView> declaredViews = const [],
|
||||||
required List<String> declaredIncludes,
|
required List<String> declaredIncludes,
|
||||||
required List<DeclaredQuery> declaredQueries,
|
required List<DeclaredQuery> declaredQueries,
|
||||||
|
|
|
@ -27,17 +27,18 @@ class DartColumnDeclaration implements DartDeclaration, ColumnDeclaration {
|
||||||
bool get isDefinedInMoorFile => false;
|
bool get isDefinedInMoorFile => false;
|
||||||
}
|
}
|
||||||
|
|
||||||
class MoorColumnDeclaration implements MoorDeclaration, ColumnDeclaration {
|
class DriftColumnDeclaration
|
||||||
|
implements DriftFileDeclaration, ColumnDeclaration {
|
||||||
@override
|
@override
|
||||||
final SourceRange declaration;
|
final SourceRange declaration;
|
||||||
|
|
||||||
@override
|
@override
|
||||||
final AstNode node;
|
final AstNode node;
|
||||||
|
|
||||||
MoorColumnDeclaration._(this.declaration, this.node);
|
DriftColumnDeclaration._(this.declaration, this.node);
|
||||||
|
|
||||||
factory MoorColumnDeclaration(AstNode node, FoundFile file) {
|
factory DriftColumnDeclaration(AstNode node, FoundFile file) {
|
||||||
return MoorColumnDeclaration._(
|
return DriftColumnDeclaration._(
|
||||||
SourceRange.fromNodeAndFile(node, file),
|
SourceRange.fromNodeAndFile(node, file),
|
||||||
node,
|
node,
|
||||||
);
|
);
|
||||||
|
|
|
@ -34,22 +34,22 @@ abstract class DartDeclaration extends Declaration {
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Declaration for elements that are declared in a `.moor` file.
|
/// Declaration for elements that are declared in a `.moor` file.
|
||||||
abstract class MoorDeclaration extends Declaration {
|
abstract class DriftFileDeclaration extends Declaration {
|
||||||
/// The ast node from a moor file for this declaration.
|
/// The ast node from a moor file for this declaration.
|
||||||
AstNode get node;
|
AstNode get node;
|
||||||
}
|
}
|
||||||
|
|
||||||
extension ToSql on MoorDeclaration {
|
extension ToSql on DriftFileDeclaration {
|
||||||
String exportSql(MoorOptions options) {
|
String exportSql(DriftOptions options) {
|
||||||
final writer = SqlWriter(options, escapeForDart: false);
|
final writer = SqlWriter(options, escapeForDart: false);
|
||||||
return writer.writeSql(node);
|
return writer.writeSql(node);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
extension ToSqlIfAvailable on Declaration {
|
extension ToSqlIfAvailable on Declaration {
|
||||||
String? formatSqlIfAvailable(MoorOptions options) {
|
String? formatSqlIfAvailable(DriftOptions options) {
|
||||||
final $this = this;
|
final $this = this;
|
||||||
if ($this is MoorDeclaration) {
|
if ($this is DriftFileDeclaration) {
|
||||||
return $this.exportSql(options);
|
return $this.exportSql(options);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -60,5 +60,5 @@ extension ToSqlIfAvailable on Declaration {
|
||||||
extension DeclarationUtils on HasDeclaration {
|
extension DeclarationUtils on HasDeclaration {
|
||||||
bool get isDeclaredInDart => declaration is DartDeclaration;
|
bool get isDeclaredInDart => declaration is DartDeclaration;
|
||||||
|
|
||||||
bool get isDeclaredInDriftFile => declaration is MoorDeclaration;
|
bool get isDeclaredInDriftFile => declaration is DriftFileDeclaration;
|
||||||
}
|
}
|
||||||
|
|
|
@ -2,14 +2,14 @@ part of 'declaration.dart';
|
||||||
|
|
||||||
abstract class IndexDeclaration extends Declaration {}
|
abstract class IndexDeclaration extends Declaration {}
|
||||||
|
|
||||||
class MoorIndexDeclaration implements MoorDeclaration, IndexDeclaration {
|
class DriftIndexDeclaration implements DriftFileDeclaration, IndexDeclaration {
|
||||||
@override
|
@override
|
||||||
final SourceRange declaration;
|
final SourceRange declaration;
|
||||||
|
|
||||||
@override
|
@override
|
||||||
final CreateIndexStatement node;
|
final CreateIndexStatement node;
|
||||||
|
|
||||||
MoorIndexDeclaration.fromNodeAndFile(this.node, FoundFile file)
|
DriftIndexDeclaration.fromNodeAndFile(this.node, FoundFile file)
|
||||||
: declaration = SourceRange.fromNodeAndFile(node, file);
|
: declaration = SourceRange.fromNodeAndFile(node, file);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -2,14 +2,14 @@ part of 'declaration.dart';
|
||||||
|
|
||||||
abstract class SpecialQueryDeclaration extends Declaration {}
|
abstract class SpecialQueryDeclaration extends Declaration {}
|
||||||
|
|
||||||
class MoorSpecialQueryDeclaration
|
class DriftSpecialQueryDeclaration
|
||||||
implements MoorDeclaration, SpecialQueryDeclaration {
|
implements DriftFileDeclaration, SpecialQueryDeclaration {
|
||||||
@override
|
@override
|
||||||
final SourceRange declaration;
|
final SourceRange declaration;
|
||||||
|
|
||||||
@override
|
@override
|
||||||
final DeclaredStatement node;
|
final DeclaredStatement node;
|
||||||
|
|
||||||
MoorSpecialQueryDeclaration.fromNodeAndFile(this.node, FoundFile file)
|
DriftSpecialQueryDeclaration.fromNodeAndFile(this.node, FoundFile file)
|
||||||
: declaration = SourceRange.fromNodeAndFile(node, file);
|
: declaration = SourceRange.fromNodeAndFile(node, file);
|
||||||
}
|
}
|
||||||
|
|
|
@ -33,18 +33,18 @@ class DartTableDeclaration implements TableDeclaration, DartDeclaration {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
class MoorTableDeclaration
|
class DriftTableDeclaration
|
||||||
implements TableDeclaration, MoorDeclaration, TableDeclarationWithSql {
|
implements TableDeclaration, DriftFileDeclaration, TableDeclarationWithSql {
|
||||||
@override
|
@override
|
||||||
final SourceRange declaration;
|
final SourceRange declaration;
|
||||||
|
|
||||||
@override
|
@override
|
||||||
final TableInducingStatement node;
|
final TableInducingStatement node;
|
||||||
|
|
||||||
MoorTableDeclaration._(this.declaration, this.node);
|
DriftTableDeclaration._(this.declaration, this.node);
|
||||||
|
|
||||||
factory MoorTableDeclaration(TableInducingStatement node, FoundFile file) {
|
factory DriftTableDeclaration(TableInducingStatement node, FoundFile file) {
|
||||||
return MoorTableDeclaration._(
|
return DriftTableDeclaration._(
|
||||||
SourceRange.fromNodeAndFile(node, file),
|
SourceRange.fromNodeAndFile(node, file),
|
||||||
node,
|
node,
|
||||||
);
|
);
|
||||||
|
|
|
@ -5,14 +5,15 @@ abstract class TriggerDeclaration extends Declaration {
|
||||||
String get createSql;
|
String get createSql;
|
||||||
}
|
}
|
||||||
|
|
||||||
class MoorTriggerDeclaration implements MoorDeclaration, TriggerDeclaration {
|
class DriftTriggerDeclaration
|
||||||
|
implements DriftFileDeclaration, TriggerDeclaration {
|
||||||
@override
|
@override
|
||||||
final SourceRange declaration;
|
final SourceRange declaration;
|
||||||
|
|
||||||
@override
|
@override
|
||||||
final CreateTriggerStatement node;
|
final CreateTriggerStatement node;
|
||||||
|
|
||||||
MoorTriggerDeclaration.fromNodeAndFile(this.node, FoundFile file)
|
DriftTriggerDeclaration.fromNodeAndFile(this.node, FoundFile file)
|
||||||
: declaration = SourceRange.fromNodeAndFile(node, file);
|
: declaration = SourceRange.fromNodeAndFile(node, file);
|
||||||
|
|
||||||
@override
|
@override
|
||||||
|
|
|
@ -32,24 +32,24 @@ class DartViewDeclaration implements ViewDeclaration, DartDeclaration {
|
||||||
}
|
}
|
||||||
|
|
||||||
class TableReferenceInDartView {
|
class TableReferenceInDartView {
|
||||||
final MoorTable table;
|
final DriftTable table;
|
||||||
final String name;
|
final String name;
|
||||||
|
|
||||||
TableReferenceInDartView(this.table, this.name);
|
TableReferenceInDartView(this.table, this.name);
|
||||||
}
|
}
|
||||||
|
|
||||||
class MoorViewDeclaration
|
class DriftViewDeclaration
|
||||||
implements ViewDeclaration, MoorDeclaration, ViewDeclarationWithSql {
|
implements ViewDeclaration, DriftFileDeclaration, ViewDeclarationWithSql {
|
||||||
@override
|
@override
|
||||||
final SourceRange declaration;
|
final SourceRange declaration;
|
||||||
|
|
||||||
@override
|
@override
|
||||||
final CreateViewStatement node;
|
final CreateViewStatement node;
|
||||||
|
|
||||||
MoorViewDeclaration._(this.declaration, this.node);
|
DriftViewDeclaration._(this.declaration, this.node);
|
||||||
|
|
||||||
factory MoorViewDeclaration(CreateViewStatement node, FoundFile file) {
|
factory DriftViewDeclaration(CreateViewStatement node, FoundFile file) {
|
||||||
return MoorViewDeclaration._(
|
return DriftViewDeclaration._(
|
||||||
SourceRange.fromNodeAndFile(node, file),
|
SourceRange.fromNodeAndFile(node, file),
|
||||||
node,
|
node,
|
||||||
);
|
);
|
||||||
|
|
|
@ -7,11 +7,11 @@ import 'model.dart';
|
||||||
/// An sql index.
|
/// An sql index.
|
||||||
///
|
///
|
||||||
/// Indices can only be declared in moor files at the moment.
|
/// Indices can only be declared in moor files at the moment.
|
||||||
class MoorIndex extends MoorSchemaEntity {
|
class MoorIndex extends DriftSchemaEntity {
|
||||||
/// The table on which this index is created.
|
/// The table on which this index is created.
|
||||||
///
|
///
|
||||||
/// This field can be null in case the table wasn't resolved.
|
/// This field can be null in case the table wasn't resolved.
|
||||||
MoorTable? table;
|
DriftTable? table;
|
||||||
final String name;
|
final String name;
|
||||||
|
|
||||||
/// The sql statement creating this index.
|
/// The sql statement creating this index.
|
||||||
|
@ -25,7 +25,7 @@ class MoorIndex extends MoorSchemaEntity {
|
||||||
factory MoorIndex.fromMoor(CreateIndexStatement stmt, FoundFile file) {
|
factory MoorIndex.fromMoor(CreateIndexStatement stmt, FoundFile file) {
|
||||||
return MoorIndex(
|
return MoorIndex(
|
||||||
stmt.indexName,
|
stmt.indexName,
|
||||||
MoorIndexDeclaration.fromNodeAndFile(stmt, file),
|
DriftIndexDeclaration.fromNodeAndFile(stmt, file),
|
||||||
stmt.span!.text,
|
stmt.span!.text,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
@ -40,12 +40,12 @@ class MoorIndex extends MoorSchemaEntity {
|
||||||
///
|
///
|
||||||
/// Unlike [createStmt], this can be formatted to exclude comments and
|
/// Unlike [createStmt], this can be formatted to exclude comments and
|
||||||
/// unnecessary whitespace depending on the [options].
|
/// unnecessary whitespace depending on the [options].
|
||||||
String createSql(MoorOptions options) {
|
String createSql(DriftOptions options) {
|
||||||
return declaration.formatSqlIfAvailable(options) ?? createStmt;
|
return declaration.formatSqlIfAvailable(options) ?? createStmt;
|
||||||
}
|
}
|
||||||
|
|
||||||
@override
|
@override
|
||||||
Iterable<MoorSchemaEntity> get references {
|
Iterable<DriftSchemaEntity> get references {
|
||||||
if (table == null) {
|
if (table == null) {
|
||||||
return const Iterable.empty();
|
return const Iterable.empty();
|
||||||
}
|
}
|
||||||
|
|
|
@ -12,7 +12,7 @@ enum SpecialQueryMode {
|
||||||
/// A special query, such as the ones executes when the database was created.
|
/// A special query, such as the ones executes when the database was created.
|
||||||
///
|
///
|
||||||
/// Those are generated from `@created:` queries in moor files.
|
/// Those are generated from `@created:` queries in moor files.
|
||||||
class SpecialQuery implements MoorSchemaEntity {
|
class SpecialQuery implements DriftSchemaEntity {
|
||||||
final String sql;
|
final String sql;
|
||||||
final SpecialQueryMode mode;
|
final SpecialQueryMode mode;
|
||||||
@override
|
@override
|
||||||
|
@ -23,7 +23,7 @@ class SpecialQuery implements MoorSchemaEntity {
|
||||||
|
|
||||||
factory SpecialQuery.fromMoor(DeclaredStatement stmt, FoundFile file) {
|
factory SpecialQuery.fromMoor(DeclaredStatement stmt, FoundFile file) {
|
||||||
return SpecialQuery(stmt.statement.span!.text,
|
return SpecialQuery(stmt.statement.span!.text,
|
||||||
MoorSpecialQueryDeclaration.fromNodeAndFile(stmt, file));
|
DriftSpecialQueryDeclaration.fromNodeAndFile(stmt, file));
|
||||||
}
|
}
|
||||||
|
|
||||||
@override
|
@override
|
||||||
|
@ -34,11 +34,11 @@ class SpecialQuery implements MoorSchemaEntity {
|
||||||
throw UnsupportedError("Special queries don't have a name");
|
throw UnsupportedError("Special queries don't have a name");
|
||||||
|
|
||||||
@override
|
@override
|
||||||
List<MoorTable> references = [];
|
List<DriftTable> references = [];
|
||||||
|
|
||||||
String formattedSql(MoorOptions options) {
|
String formattedSql(DriftOptions options) {
|
||||||
final decl = declaration;
|
final decl = declaration;
|
||||||
if (decl is MoorSpecialQueryDeclaration) {
|
if (decl is DriftSpecialQueryDeclaration) {
|
||||||
final writer = SqlWriter(options, escapeForDart: false);
|
final writer = SqlWriter(options, escapeForDart: false);
|
||||||
return writer.writeSql(decl.node.statement);
|
return writer.writeSql(decl.node.statement);
|
||||||
}
|
}
|
||||||
|
|
|
@ -35,7 +35,7 @@ class DeclaredDartQuery extends DeclaredQuery {
|
||||||
/// available.
|
/// available.
|
||||||
class DeclaredMoorQuery extends DeclaredQuery {
|
class DeclaredMoorQuery extends DeclaredQuery {
|
||||||
final DeclaredStatement astNode;
|
final DeclaredStatement astNode;
|
||||||
ParsedMoorFile? file;
|
ParsedDriftFile? file;
|
||||||
|
|
||||||
DeclaredMoorQuery(String name, this.astNode) : super(name);
|
DeclaredMoorQuery(String name, this.astNode) : super(name);
|
||||||
|
|
||||||
|
@ -176,7 +176,7 @@ abstract class SqlQuery {
|
||||||
}
|
}
|
||||||
|
|
||||||
class SqlSelectQuery extends SqlQuery {
|
class SqlSelectQuery extends SqlQuery {
|
||||||
final List<MoorSchemaEntity> readsFrom;
|
final List<DriftSchemaEntity> readsFrom;
|
||||||
@override
|
@override
|
||||||
final InferredResultSet resultSet;
|
final InferredResultSet resultSet;
|
||||||
@override
|
@override
|
||||||
|
@ -205,10 +205,10 @@ class SqlSelectQuery extends SqlQuery {
|
||||||
this.nestedContainer,
|
this.nestedContainer,
|
||||||
) : super(name, elements, hasMultipleTables: readsFrom.length > 1);
|
) : super(name, elements, hasMultipleTables: readsFrom.length > 1);
|
||||||
|
|
||||||
Set<MoorTable> get readsFromTables {
|
Set<DriftTable> get readsFromTables {
|
||||||
return {
|
return {
|
||||||
for (final entity in readsFrom)
|
for (final entity in readsFrom)
|
||||||
if (entity is MoorTable)
|
if (entity is DriftTable)
|
||||||
entity
|
entity
|
||||||
else if (entity is MoorView)
|
else if (entity is MoorView)
|
||||||
...entity.transitiveTableReferences,
|
...entity.transitiveTableReferences,
|
||||||
|
@ -435,8 +435,8 @@ class InferredResultSet {
|
||||||
///
|
///
|
||||||
/// We still need to handle column aliases.
|
/// We still need to handle column aliases.
|
||||||
class MatchingMoorTable {
|
class MatchingMoorTable {
|
||||||
final MoorEntityWithResultSet table;
|
final DriftEntityWithResultSet table;
|
||||||
final Map<String, MoorColumn> aliasToColumn;
|
final Map<String, DriftColumn> aliasToColumn;
|
||||||
|
|
||||||
MatchingMoorTable(this.table, this.aliasToColumn);
|
MatchingMoorTable(this.table, this.aliasToColumn);
|
||||||
|
|
||||||
|
@ -524,7 +524,7 @@ class NestedResultTable extends NestedResult {
|
||||||
final bool isNullable;
|
final bool isNullable;
|
||||||
final NestedStarResultColumn from;
|
final NestedStarResultColumn from;
|
||||||
final String name;
|
final String name;
|
||||||
final MoorEntityWithResultSet table;
|
final DriftEntityWithResultSet table;
|
||||||
|
|
||||||
NestedResultTable(this.from, this.name, this.table, {this.isNullable = true});
|
NestedResultTable(this.from, this.name, this.table, {this.isNullable = true});
|
||||||
|
|
||||||
|
@ -747,7 +747,7 @@ class ExpressionDartPlaceholderType extends DartPlaceholderType {
|
||||||
}
|
}
|
||||||
|
|
||||||
class InsertableDartPlaceholderType extends DartPlaceholderType {
|
class InsertableDartPlaceholderType extends DartPlaceholderType {
|
||||||
final MoorTable? table;
|
final DriftTable? table;
|
||||||
|
|
||||||
InsertableDartPlaceholderType(this.table);
|
InsertableDartPlaceholderType(this.table);
|
||||||
|
|
||||||
|
@ -838,7 +838,7 @@ class FoundDartPlaceholder extends FoundElement {
|
||||||
|
|
||||||
/// Whether we should write this parameter as a function having available
|
/// Whether we should write this parameter as a function having available
|
||||||
/// result sets as parameters.
|
/// result sets as parameters.
|
||||||
bool writeAsScopedFunction(MoorOptions options) {
|
bool writeAsScopedFunction(DriftOptions options) {
|
||||||
return options.scopedDartComponents &&
|
return options.scopedDartComponents &&
|
||||||
availableResultSets.isNotEmpty &&
|
availableResultSets.isNotEmpty &&
|
||||||
// Don't generate scoped functions for insertables, where the Dart type
|
// Don't generate scoped functions for insertables, where the Dart type
|
||||||
|
@ -856,7 +856,7 @@ class AvailableMoorResultSet {
|
||||||
final String name;
|
final String name;
|
||||||
|
|
||||||
/// The table or view that is available.
|
/// The table or view that is available.
|
||||||
final MoorEntityWithResultSet entity;
|
final DriftEntityWithResultSet entity;
|
||||||
|
|
||||||
final ResultSetAvailableInStatement? source;
|
final ResultSetAvailableInStatement? source;
|
||||||
|
|
||||||
|
|
|
@ -12,7 +12,7 @@ import 'declarations/declaration.dart';
|
||||||
|
|
||||||
/// A parsed table, declared in code by extending `Table` and referencing that
|
/// A parsed table, declared in code by extending `Table` and referencing that
|
||||||
/// table in `@UseMoor` or `@UseDao`.
|
/// table in `@UseMoor` or `@UseDao`.
|
||||||
class MoorTable extends MoorEntityWithResultSet {
|
class DriftTable extends DriftEntityWithResultSet {
|
||||||
/// The [ClassElement] for the class that declares this table or null if
|
/// The [ClassElement] for the class that declares this table or null if
|
||||||
/// the table was inferred from a `CREATE TABLE` statement.
|
/// the table was inferred from a `CREATE TABLE` statement.
|
||||||
final ClassElement? fromClass;
|
final ClassElement? fromClass;
|
||||||
|
@ -45,7 +45,7 @@ class MoorTable extends MoorEntityWithResultSet {
|
||||||
|
|
||||||
/// The columns declared in this table.
|
/// The columns declared in this table.
|
||||||
@override
|
@override
|
||||||
final List<MoorColumn> columns;
|
final List<DriftColumn> columns;
|
||||||
|
|
||||||
/// The (unescaped) name of this table when stored in the database
|
/// The (unescaped) name of this table when stored in the database
|
||||||
final String sqlName;
|
final String sqlName;
|
||||||
|
@ -79,7 +79,7 @@ class MoorTable extends MoorEntityWithResultSet {
|
||||||
return existingRowClass?.dartType(options) ?? dartTypeName;
|
return existingRowClass?.dartType(options) ?? dartTypeName;
|
||||||
}
|
}
|
||||||
|
|
||||||
String getNameForCompanionClass(MoorOptions options) {
|
String getNameForCompanionClass(DriftOptions options) {
|
||||||
final baseName =
|
final baseName =
|
||||||
options.useDataClassNameForCompanions ? dartTypeName : _baseName;
|
options.useDataClassNameForCompanions ? dartTypeName : _baseName;
|
||||||
return '${baseName}Companion';
|
return '${baseName}Companion';
|
||||||
|
@ -90,17 +90,17 @@ class MoorTable extends MoorEntityWithResultSet {
|
||||||
/// not been defined that way.
|
/// not been defined that way.
|
||||||
///
|
///
|
||||||
/// For the full primary key, see [fullPrimaryKey].
|
/// For the full primary key, see [fullPrimaryKey].
|
||||||
final Set<MoorColumn>? primaryKey;
|
final Set<DriftColumn>? primaryKey;
|
||||||
|
|
||||||
/// The set of unique keys if they have been explicitly defined by
|
/// The set of unique keys if they have been explicitly defined by
|
||||||
/// overriding `uniqueKeys` in the table class.
|
/// overriding `uniqueKeys` in the table class.
|
||||||
final List<Set<MoorColumn>>? uniqueKeys;
|
final List<Set<DriftColumn>>? uniqueKeys;
|
||||||
|
|
||||||
/// The primary key for this table.
|
/// The primary key for this table.
|
||||||
///
|
///
|
||||||
/// Unlikely [primaryKey], this method is not limited to the `primaryKey`
|
/// Unlikely [primaryKey], this method is not limited to the `primaryKey`
|
||||||
/// override in Dart table declarations.
|
/// override in Dart table declarations.
|
||||||
Set<MoorColumn> get fullPrimaryKey {
|
Set<DriftColumn> get fullPrimaryKey {
|
||||||
if (primaryKey != null) return primaryKey!;
|
if (primaryKey != null) return primaryKey!;
|
||||||
|
|
||||||
return columns.where((c) => c.features.any((f) => f is PrimaryKey)).toSet();
|
return columns.where((c) => c.features.any((f) => f is PrimaryKey)).toSet();
|
||||||
|
@ -123,7 +123,7 @@ class MoorTable extends MoorEntityWithResultSet {
|
||||||
final List<String>? overrideTableConstraints;
|
final List<String>? overrideTableConstraints;
|
||||||
|
|
||||||
@override
|
@override
|
||||||
final Set<MoorTable> references = {};
|
final Set<DriftTable> references = {};
|
||||||
|
|
||||||
/// Returns whether this table was created from a `CREATE VIRTUAL TABLE`
|
/// Returns whether this table was created from a `CREATE VIRTUAL TABLE`
|
||||||
/// statement in a moor file
|
/// statement in a moor file
|
||||||
|
@ -144,7 +144,7 @@ class MoorTable extends MoorEntityWithResultSet {
|
||||||
return (declaration as TableDeclarationWithSql).createSql;
|
return (declaration as TableDeclarationWithSql).createSql;
|
||||||
}
|
}
|
||||||
|
|
||||||
MoorTable({
|
DriftTable({
|
||||||
this.fromClass,
|
this.fromClass,
|
||||||
this.columns = const [],
|
this.columns = const [],
|
||||||
required this.sqlName,
|
required this.sqlName,
|
||||||
|
@ -178,7 +178,7 @@ class MoorTable extends MoorEntityWithResultSet {
|
||||||
|
|
||||||
/// Determines whether [column] would be required for inserts performed via
|
/// Determines whether [column] would be required for inserts performed via
|
||||||
/// companions.
|
/// companions.
|
||||||
bool isColumnRequiredForInsert(MoorColumn column) {
|
bool isColumnRequiredForInsert(DriftColumn column) {
|
||||||
assert(columns.contains(column));
|
assert(columns.contains(column));
|
||||||
|
|
||||||
if (column.defaultArgument != null ||
|
if (column.defaultArgument != null ||
|
||||||
|
@ -217,7 +217,7 @@ class MoorTable extends MoorEntityWithResultSet {
|
||||||
}
|
}
|
||||||
|
|
||||||
class WrittenMoorTable {
|
class WrittenMoorTable {
|
||||||
final MoorTable table;
|
final DriftTable table;
|
||||||
final UpdateKind kind;
|
final UpdateKind kind;
|
||||||
|
|
||||||
WrittenMoorTable(this.table, this.kind);
|
WrittenMoorTable(this.table, this.kind);
|
||||||
|
|
|
@ -4,7 +4,7 @@ import 'package:sqlparser/sqlparser.dart';
|
||||||
|
|
||||||
import 'model.dart';
|
import 'model.dart';
|
||||||
|
|
||||||
class MoorTrigger implements MoorSchemaEntity {
|
class MoorTrigger implements DriftSchemaEntity {
|
||||||
@override
|
@override
|
||||||
final String displayName;
|
final String displayName;
|
||||||
|
|
||||||
|
@ -14,16 +14,16 @@ class MoorTrigger implements MoorSchemaEntity {
|
||||||
/// The table on which this trigger operates.
|
/// The table on which this trigger operates.
|
||||||
///
|
///
|
||||||
/// This field can be null in case the table wasn't resolved.
|
/// This field can be null in case the table wasn't resolved.
|
||||||
MoorTable? on;
|
DriftTable? on;
|
||||||
List<WrittenMoorTable> bodyUpdates = [];
|
List<WrittenMoorTable> bodyUpdates = [];
|
||||||
List<MoorTable> bodyReferences = [];
|
List<DriftTable> bodyReferences = [];
|
||||||
|
|
||||||
MoorTrigger(this.displayName, this.declaration, this.on);
|
MoorTrigger(this.displayName, this.declaration, this.on);
|
||||||
|
|
||||||
factory MoorTrigger.fromMoor(CreateTriggerStatement stmt, FoundFile file) {
|
factory MoorTrigger.fromMoor(CreateTriggerStatement stmt, FoundFile file) {
|
||||||
return MoorTrigger(
|
return MoorTrigger(
|
||||||
stmt.triggerName,
|
stmt.triggerName,
|
||||||
MoorTriggerDeclaration.fromNodeAndFile(stmt, file),
|
DriftTriggerDeclaration.fromNodeAndFile(stmt, file),
|
||||||
null, // must be resolved later
|
null, // must be resolved later
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
@ -35,11 +35,11 @@ class MoorTrigger implements MoorSchemaEntity {
|
||||||
}
|
}
|
||||||
|
|
||||||
@override
|
@override
|
||||||
Iterable<MoorSchemaEntity> get references =>
|
Iterable<DriftSchemaEntity> get references =>
|
||||||
{if (on != null) on!, ...bodyReferences};
|
{if (on != null) on!, ...bodyReferences};
|
||||||
|
|
||||||
/// The `CREATE TRIGGER` statement that can be used to create this trigger.
|
/// The `CREATE TRIGGER` statement that can be used to create this trigger.
|
||||||
String createSql(MoorOptions options) {
|
String createSql(DriftOptions options) {
|
||||||
return declaration.formatSqlIfAvailable(options) ?? declaration.createSql;
|
return declaration.formatSqlIfAvailable(options) ?? declaration.createSql;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -13,7 +13,7 @@ class UsedTypeConverter {
|
||||||
int? index;
|
int? index;
|
||||||
|
|
||||||
/// The table using this type converter.
|
/// The table using this type converter.
|
||||||
MoorTable? table;
|
DriftTable? table;
|
||||||
|
|
||||||
/// The expression that will construct the type converter at runtime. The
|
/// The expression that will construct the type converter at runtime. The
|
||||||
/// type converter constructed will map a [dartType] to the [sqlType] and
|
/// type converter constructed will map a [dartType] to the [sqlType] and
|
||||||
|
|
|
@ -9,7 +9,7 @@ import '../../writer.dart';
|
||||||
import 'model.dart';
|
import 'model.dart';
|
||||||
|
|
||||||
/// A parsed view
|
/// A parsed view
|
||||||
class MoorView extends MoorEntityWithResultSet {
|
class MoorView extends DriftEntityWithResultSet {
|
||||||
@override
|
@override
|
||||||
final ViewDeclaration? declaration;
|
final ViewDeclaration? declaration;
|
||||||
|
|
||||||
|
@ -17,15 +17,15 @@ class MoorView extends MoorEntityWithResultSet {
|
||||||
/// sql queries. Note that this field is set lazily.
|
/// sql queries. Note that this field is set lazily.
|
||||||
View? parserView;
|
View? parserView;
|
||||||
|
|
||||||
ParsedMoorFile? file;
|
ParsedDriftFile? file;
|
||||||
|
|
||||||
final String name;
|
final String name;
|
||||||
|
|
||||||
@override
|
@override
|
||||||
List<MoorSchemaEntity> references = [];
|
List<DriftSchemaEntity> references = [];
|
||||||
|
|
||||||
@override
|
@override
|
||||||
late List<MoorColumn> columns;
|
late List<DriftColumn> columns;
|
||||||
|
|
||||||
@override
|
@override
|
||||||
String dartTypeName;
|
String dartTypeName;
|
||||||
|
@ -61,10 +61,10 @@ class MoorView extends MoorEntityWithResultSet {
|
||||||
///
|
///
|
||||||
/// This includes all tables in [references]. If this view references other
|
/// This includes all tables in [references]. If this view references other
|
||||||
/// views, their [transitiveTableReferences] will be included as well.
|
/// views, their [transitiveTableReferences] will be included as well.
|
||||||
Set<MoorTable> get transitiveTableReferences {
|
Set<DriftTable> get transitiveTableReferences {
|
||||||
return {
|
return {
|
||||||
for (final reference in references)
|
for (final reference in references)
|
||||||
if (reference is MoorTable)
|
if (reference is DriftTable)
|
||||||
reference
|
reference
|
||||||
else if (reference is MoorView)
|
else if (reference is MoorView)
|
||||||
...reference.transitiveTableReferences,
|
...reference.transitiveTableReferences,
|
||||||
|
@ -76,7 +76,7 @@ class MoorView extends MoorEntityWithResultSet {
|
||||||
final dataClassName = dataClassNameForClassName(entityInfoName);
|
final dataClassName = dataClassNameForClassName(entityInfoName);
|
||||||
|
|
||||||
return MoorView(
|
return MoorView(
|
||||||
declaration: MoorViewDeclaration(stmt, file),
|
declaration: DriftViewDeclaration(stmt, file),
|
||||||
name: stmt.viewName,
|
name: stmt.viewName,
|
||||||
dartTypeName: dataClassName,
|
dartTypeName: dataClassName,
|
||||||
entityInfoName: entityInfoName,
|
entityInfoName: entityInfoName,
|
||||||
|
@ -84,8 +84,8 @@ class MoorView extends MoorEntityWithResultSet {
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The `CREATE VIEW` statement that can be used to create this view.
|
/// The `CREATE VIEW` statement that can be used to create this view.
|
||||||
String createSql(MoorOptions options) {
|
String createSql(DriftOptions options) {
|
||||||
final decl = declaration as MoorViewDeclaration?;
|
final decl = declaration as DriftViewDeclaration?;
|
||||||
if (decl == null) {
|
if (decl == null) {
|
||||||
throw StateError('Cannot show SQL for views without a declaration');
|
throw StateError('Cannot show SQL for views without a declaration');
|
||||||
}
|
}
|
||||||
|
@ -103,7 +103,7 @@ class MoorView extends MoorEntityWithResultSet {
|
||||||
class ViewQueryInformation {
|
class ViewQueryInformation {
|
||||||
/// All columns from this Dart-defined view, in the order in which they were
|
/// All columns from this Dart-defined view, in the order in which they were
|
||||||
/// added to the `query` getter.
|
/// added to the `query` getter.
|
||||||
final List<MapEntry<String, MoorColumn>> columns;
|
final List<MapEntry<String, DriftColumn>> columns;
|
||||||
final String from;
|
final String from;
|
||||||
final String query;
|
final String query;
|
||||||
|
|
||||||
|
|
|
@ -14,7 +14,7 @@ class FindStreamUpdateRules {
|
||||||
for (final entity in db.entities) {
|
for (final entity in db.entities) {
|
||||||
if (entity is MoorTrigger) {
|
if (entity is MoorTrigger) {
|
||||||
_writeRulesForTrigger(entity, rules);
|
_writeRulesForTrigger(entity, rules);
|
||||||
} else if (entity is MoorTable) {
|
} else if (entity is DriftTable) {
|
||||||
_writeRulesForTable(entity, rules);
|
_writeRulesForTable(entity, rules);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -22,11 +22,11 @@ class FindStreamUpdateRules {
|
||||||
return StreamQueryUpdateRules(rules);
|
return StreamQueryUpdateRules(rules);
|
||||||
}
|
}
|
||||||
|
|
||||||
void _writeRulesForTable(MoorTable table, List<UpdateRule> rules) {
|
void _writeRulesForTable(DriftTable table, List<UpdateRule> rules) {
|
||||||
final declaration = table.declaration;
|
final declaration = table.declaration;
|
||||||
|
|
||||||
// We only know about foreign key clauses from tables in moor files
|
// We only know about foreign key clauses from tables in moor files
|
||||||
if (declaration is! MoorTableDeclaration) return;
|
if (declaration is! DriftTableDeclaration) return;
|
||||||
|
|
||||||
if (declaration.node is! CreateTableStatement) return;
|
if (declaration.node is! CreateTableStatement) return;
|
||||||
|
|
||||||
|
@ -74,7 +74,7 @@ class FindStreamUpdateRules {
|
||||||
void _writeRulesForTrigger(MoorTrigger trigger, List<UpdateRule> rules) {
|
void _writeRulesForTrigger(MoorTrigger trigger, List<UpdateRule> rules) {
|
||||||
final declaration = trigger.declaration;
|
final declaration = trigger.declaration;
|
||||||
|
|
||||||
if (declaration is! MoorTriggerDeclaration) return;
|
if (declaration is! DriftTriggerDeclaration) return;
|
||||||
|
|
||||||
final target = declaration.node.target;
|
final target = declaration.node.target;
|
||||||
UpdateKind targetKind;
|
UpdateKind targetKind;
|
||||||
|
|
|
@ -2,9 +2,9 @@ import 'package:drift_dev/src/analyzer/runner/file_graph.dart';
|
||||||
import 'package:drift_dev/src/analyzer/runner/results.dart';
|
import 'package:drift_dev/src/analyzer/runner/results.dart';
|
||||||
|
|
||||||
extension CurrentResults on FoundFile {
|
extension CurrentResults on FoundFile {
|
||||||
ParsedMoorFile? get parsedMoorOrNull {
|
ParsedDriftFile? get parsedMoorOrNull {
|
||||||
final result = currentResult;
|
final result = currentResult;
|
||||||
if (result is ParsedMoorFile && isParsed) {
|
if (result is ParsedDriftFile && isParsed) {
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
return null;
|
return null;
|
||||||
|
|
|
@ -1,4 +1,4 @@
|
||||||
import 'package:drift_dev/src/analyzer/moor/moor_ffi_extension.dart';
|
import 'package:drift_dev/src/analyzer/drift/moor_ffi_extension.dart';
|
||||||
import 'package:sqlparser/sqlparser.dart';
|
import 'package:sqlparser/sqlparser.dart';
|
||||||
// ignore: implementation_imports
|
// ignore: implementation_imports
|
||||||
import 'package:sqlparser/src/utils/ast_equality.dart';
|
import 'package:sqlparser/src/utils/ast_equality.dart';
|
||||||
|
|
|
@ -9,17 +9,17 @@ const _infoVersion = '0.1.0-dev-preview';
|
||||||
|
|
||||||
/// Utilities to transform moor schema entities to json.
|
/// Utilities to transform moor schema entities to json.
|
||||||
class SchemaWriter {
|
class SchemaWriter {
|
||||||
static const _exportOptions = MoorOptions.defaults();
|
static const _exportOptions = DriftOptions.defaults();
|
||||||
|
|
||||||
/// The parsed and resolved database for which the schema should be written.
|
/// The parsed and resolved database for which the schema should be written.
|
||||||
final Database db;
|
final Database db;
|
||||||
|
|
||||||
final Map<MoorSchemaEntity, int> _entityIds = {};
|
final Map<DriftSchemaEntity, int> _entityIds = {};
|
||||||
int _maxId = 0;
|
int _maxId = 0;
|
||||||
|
|
||||||
SchemaWriter(this.db);
|
SchemaWriter(this.db);
|
||||||
|
|
||||||
int _idOf(MoorSchemaEntity entity) {
|
int _idOf(DriftSchemaEntity entity) {
|
||||||
return _entityIds.putIfAbsent(entity, () => _maxId++);
|
return _entityIds.putIfAbsent(entity, () => _maxId++);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -36,11 +36,11 @@ class SchemaWriter {
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
Map _entityToJson(MoorSchemaEntity entity) {
|
Map _entityToJson(DriftSchemaEntity entity) {
|
||||||
String type;
|
String type;
|
||||||
Map data;
|
Map data;
|
||||||
|
|
||||||
if (entity is MoorTable) {
|
if (entity is DriftTable) {
|
||||||
type = 'table';
|
type = 'table';
|
||||||
data = _tableData(entity);
|
data = _tableData(entity);
|
||||||
} else if (entity is MoorTrigger) {
|
} else if (entity is MoorTrigger) {
|
||||||
|
@ -61,7 +61,7 @@ class SchemaWriter {
|
||||||
'sql': entity.createStmt,
|
'sql': entity.createStmt,
|
||||||
};
|
};
|
||||||
} else if (entity is MoorView) {
|
} else if (entity is MoorView) {
|
||||||
if (entity.declaration is! MoorViewDeclaration) {
|
if (entity.declaration is! DriftViewDeclaration) {
|
||||||
throw UnsupportedError(
|
throw UnsupportedError(
|
||||||
'Exporting Dart-defined views into a schema is not '
|
'Exporting Dart-defined views into a schema is not '
|
||||||
'currently supported');
|
'currently supported');
|
||||||
|
@ -70,7 +70,7 @@ class SchemaWriter {
|
||||||
type = 'view';
|
type = 'view';
|
||||||
data = {
|
data = {
|
||||||
'name': entity.name,
|
'name': entity.name,
|
||||||
'sql': entity.createSql(const MoorOptions.defaults()),
|
'sql': entity.createSql(const DriftOptions.defaults()),
|
||||||
'dart_data_name': entity.dartTypeName,
|
'dart_data_name': entity.dartTypeName,
|
||||||
'dart_info_name': entity.entityInfoName,
|
'dart_info_name': entity.entityInfoName,
|
||||||
'columns': [for (final column in entity.columns) _columnData(column)],
|
'columns': [for (final column in entity.columns) _columnData(column)],
|
||||||
|
@ -96,7 +96,7 @@ class SchemaWriter {
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
Map _tableData(MoorTable table) {
|
Map _tableData(DriftTable table) {
|
||||||
return {
|
return {
|
||||||
'name': table.sqlName,
|
'name': table.sqlName,
|
||||||
'was_declared_in_moor': table.isFromSql,
|
'was_declared_in_moor': table.isFromSql,
|
||||||
|
@ -112,7 +112,7 @@ class SchemaWriter {
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
Map _columnData(MoorColumn column) {
|
Map _columnData(DriftColumn column) {
|
||||||
final constraints = defaultConstraints(column);
|
final constraints = defaultConstraints(column);
|
||||||
|
|
||||||
return {
|
return {
|
||||||
|
@ -154,7 +154,7 @@ class SchemaWriter {
|
||||||
|
|
||||||
/// Reads files generated by [SchemaWriter].
|
/// Reads files generated by [SchemaWriter].
|
||||||
class SchemaReader {
|
class SchemaReader {
|
||||||
final Map<int, MoorSchemaEntity> _entitiesById = {};
|
final Map<int, DriftSchemaEntity> _entitiesById = {};
|
||||||
final Map<int, Map<String, dynamic>> _rawById = {};
|
final Map<int, Map<String, dynamic>> _rawById = {};
|
||||||
|
|
||||||
final Set<int> _currentlyProcessing = {};
|
final Set<int> _currentlyProcessing = {};
|
||||||
|
@ -167,7 +167,7 @@ class SchemaReader {
|
||||||
return SchemaReader._().._read(json);
|
return SchemaReader._().._read(json);
|
||||||
}
|
}
|
||||||
|
|
||||||
Iterable<MoorSchemaEntity> get entities => _entitiesById.values;
|
Iterable<DriftSchemaEntity> get entities => _entitiesById.values;
|
||||||
|
|
||||||
void _read(Map<String, dynamic> json) {
|
void _read(Map<String, dynamic> json) {
|
||||||
final entities = json['entities'] as List<dynamic>;
|
final entities = json['entities'] as List<dynamic>;
|
||||||
|
@ -182,7 +182,7 @@ class SchemaReader {
|
||||||
_rawById.keys.forEach(_processById);
|
_rawById.keys.forEach(_processById);
|
||||||
}
|
}
|
||||||
|
|
||||||
T _existingEntity<T extends MoorSchemaEntity>(dynamic id) {
|
T _existingEntity<T extends DriftSchemaEntity>(dynamic id) {
|
||||||
return _entitiesById[id as int] as T;
|
return _entitiesById[id as int] as T;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -204,7 +204,7 @@ class SchemaReader {
|
||||||
final content = rawData?['data'] as Map<String, dynamic>;
|
final content = rawData?['data'] as Map<String, dynamic>;
|
||||||
final type = rawData?['type'] as String;
|
final type = rawData?['type'] as String;
|
||||||
|
|
||||||
MoorSchemaEntity entity;
|
DriftSchemaEntity entity;
|
||||||
switch (type) {
|
switch (type) {
|
||||||
case 'index':
|
case 'index':
|
||||||
entity = _readIndex(content);
|
entity = _readIndex(content);
|
||||||
|
@ -230,7 +230,7 @@ class SchemaReader {
|
||||||
}
|
}
|
||||||
|
|
||||||
MoorIndex _readIndex(Map<String, dynamic> content) {
|
MoorIndex _readIndex(Map<String, dynamic> content) {
|
||||||
final on = _existingEntity<MoorTable>(content['on']);
|
final on = _existingEntity<DriftTable>(content['on']);
|
||||||
final name = content['name'] as String;
|
final name = content['name'] as String;
|
||||||
final sql = content['sql'] as String;
|
final sql = content['sql'] as String;
|
||||||
|
|
||||||
|
@ -238,7 +238,7 @@ class SchemaReader {
|
||||||
}
|
}
|
||||||
|
|
||||||
MoorTrigger _readTrigger(Map<String, dynamic> content) {
|
MoorTrigger _readTrigger(Map<String, dynamic> content) {
|
||||||
final on = _existingEntity<MoorTable>(content['on']);
|
final on = _existingEntity<DriftTable>(content['on']);
|
||||||
final name = content['name'] as String;
|
final name = content['name'] as String;
|
||||||
final sql = content['sql'] as String;
|
final sql = content['sql'] as String;
|
||||||
|
|
||||||
|
@ -249,7 +249,7 @@ class SchemaReader {
|
||||||
return trigger;
|
return trigger;
|
||||||
}
|
}
|
||||||
|
|
||||||
MoorTable _readTable(Map<String, dynamic> content) {
|
DriftTable _readTable(Map<String, dynamic> content) {
|
||||||
final sqlName = content['name'] as String;
|
final sqlName = content['name'] as String;
|
||||||
final isVirtual = content['is_virtual'] as bool;
|
final isVirtual = content['is_virtual'] as bool;
|
||||||
final withoutRowId = content['without_rowid'] as bool?;
|
final withoutRowId = content['without_rowid'] as bool?;
|
||||||
|
@ -259,7 +259,7 @@ class SchemaReader {
|
||||||
final parsed =
|
final parsed =
|
||||||
_engine.parse(create).rootNode as CreateVirtualTableStatement;
|
_engine.parse(create).rootNode as CreateVirtualTableStatement;
|
||||||
|
|
||||||
return MoorTable(
|
return DriftTable(
|
||||||
sqlName: sqlName,
|
sqlName: sqlName,
|
||||||
dartTypeName: sqlName,
|
dartTypeName: sqlName,
|
||||||
overriddenName: sqlName,
|
overriddenName: sqlName,
|
||||||
|
@ -279,7 +279,7 @@ class SchemaReader {
|
||||||
tableConstraints = (content['constraints'] as List<dynamic>).cast();
|
tableConstraints = (content['constraints'] as List<dynamic>).cast();
|
||||||
}
|
}
|
||||||
|
|
||||||
Set<MoorColumn>? explicitPk;
|
Set<DriftColumn>? explicitPk;
|
||||||
if (content.containsKey('explicit_pk')) {
|
if (content.containsKey('explicit_pk')) {
|
||||||
explicitPk = {
|
explicitPk = {
|
||||||
for (final columnName in content['explicit_pk'] as List<dynamic>)
|
for (final columnName in content['explicit_pk'] as List<dynamic>)
|
||||||
|
@ -289,7 +289,7 @@ class SchemaReader {
|
||||||
|
|
||||||
final pascalCase = ReCase(sqlName).pascalCase;
|
final pascalCase = ReCase(sqlName).pascalCase;
|
||||||
|
|
||||||
return MoorTable(
|
return DriftTable(
|
||||||
sqlName: sqlName,
|
sqlName: sqlName,
|
||||||
overriddenName: pascalCase,
|
overriddenName: pascalCase,
|
||||||
columns: columns,
|
columns: columns,
|
||||||
|
@ -314,7 +314,7 @@ class SchemaReader {
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
MoorColumn _readColumn(Map<String, dynamic> data) {
|
DriftColumn _readColumn(Map<String, dynamic> data) {
|
||||||
final name = data['name'] as String;
|
final name = data['name'] as String;
|
||||||
final moorType = ColumnType.values
|
final moorType = ColumnType.values
|
||||||
.firstWhere((type) => type.toString() == data['moor_type']);
|
.firstWhere((type) => type.toString() == data['moor_type']);
|
||||||
|
@ -331,7 +331,7 @@ class SchemaReader {
|
||||||
|
|
||||||
// Note: Not including client default code because that usually depends on
|
// Note: Not including client default code because that usually depends on
|
||||||
// imports from the database.
|
// imports from the database.
|
||||||
return MoorColumn(
|
return DriftColumn(
|
||||||
name: ColumnName.explicitly(name),
|
name: ColumnName.explicitly(name),
|
||||||
dartGetterName: getterName ?? ReCase(name).camelCase,
|
dartGetterName: getterName ?? ReCase(name).camelCase,
|
||||||
type: moorType,
|
type: moorType,
|
||||||
|
|
|
@ -1,15 +1,15 @@
|
||||||
import 'package:drift_dev/moor_generator.dart';
|
import 'package:drift_dev/moor_generator.dart';
|
||||||
|
|
||||||
/// Topologically sorts a list of [MoorSchemaEntity]s by their
|
/// Topologically sorts a list of [DriftSchemaEntity]s by their
|
||||||
/// [MoorSchemaEntity.references] relationship: Tables appearing first in the
|
/// [DriftSchemaEntity.references] relationship: Tables appearing first in the
|
||||||
/// output have to be created first so the table creation script doesn't crash
|
/// output have to be created first so the table creation script doesn't crash
|
||||||
/// because of tables not existing.
|
/// because of tables not existing.
|
||||||
///
|
///
|
||||||
/// If there is a circular reference between [MoorTable]s, an error will
|
/// If there is a circular reference between [DriftTable]s, an error will
|
||||||
/// be added that contains the name of the tables in question. Self-references
|
/// be added that contains the name of the tables in question. Self-references
|
||||||
/// in tables are allowed.
|
/// in tables are allowed.
|
||||||
List<MoorSchemaEntity> sortEntitiesTopologically(
|
List<DriftSchemaEntity> sortEntitiesTopologically(
|
||||||
Iterable<MoorSchemaEntity> tables) {
|
Iterable<DriftSchemaEntity> tables) {
|
||||||
final run = _SortRun();
|
final run = _SortRun();
|
||||||
|
|
||||||
for (final entity in tables) {
|
for (final entity in tables) {
|
||||||
|
@ -22,7 +22,7 @@ List<MoorSchemaEntity> sortEntitiesTopologically(
|
||||||
return run.result;
|
return run.result;
|
||||||
}
|
}
|
||||||
|
|
||||||
void _visit(MoorSchemaEntity entity, _SortRun run) {
|
void _visit(DriftSchemaEntity entity, _SortRun run) {
|
||||||
for (final reference in entity.references) {
|
for (final reference in entity.references) {
|
||||||
if (run.result.contains(reference) || reference == entity) {
|
if (run.result.contains(reference) || reference == entity) {
|
||||||
// When the target entity has already been added there's nothing to do.
|
// When the target entity has already been added there's nothing to do.
|
||||||
|
@ -48,19 +48,19 @@ class _SortRun {
|
||||||
///
|
///
|
||||||
/// This means that, when an entity references another entity that is present
|
/// This means that, when an entity references another entity that is present
|
||||||
/// in `previous.keys`, that's a circular reference.
|
/// in `previous.keys`, that's a circular reference.
|
||||||
final Map<MoorSchemaEntity, MoorSchemaEntity?> previous = {};
|
final Map<DriftSchemaEntity, DriftSchemaEntity?> previous = {};
|
||||||
|
|
||||||
/// Entities that have already been fully handled, in topological order.
|
/// Entities that have already been fully handled, in topological order.
|
||||||
///
|
///
|
||||||
/// If an entity is in [result], all of it's references are in [result] as
|
/// If an entity is in [result], all of it's references are in [result] as
|
||||||
/// well and it's safe to reference it.
|
/// well and it's safe to reference it.
|
||||||
final List<MoorSchemaEntity> result = [];
|
final List<DriftSchemaEntity> result = [];
|
||||||
|
|
||||||
/// Throws a [CircularReferenceException] because the [last] table depends on
|
/// Throws a [CircularReferenceException] because the [last] table depends on
|
||||||
/// [first], which (transitively) depends on [last] as well. The path in the
|
/// [first], which (transitively) depends on [last] as well. The path in the
|
||||||
/// thrown exception will go from [first] to [last].
|
/// thrown exception will go from [first] to [last].
|
||||||
void throwCircularException(MoorSchemaEntity last, MoorSchemaEntity first) {
|
void throwCircularException(DriftSchemaEntity last, DriftSchemaEntity first) {
|
||||||
final constructedPath = <MoorSchemaEntity>[];
|
final constructedPath = <DriftSchemaEntity>[];
|
||||||
for (var current = last; current != first; current = previous[current]!) {
|
for (var current = last; current != first; current = previous[current]!) {
|
||||||
constructedPath.insert(0, current);
|
constructedPath.insert(0, current);
|
||||||
}
|
}
|
||||||
|
@ -69,18 +69,18 @@ class _SortRun {
|
||||||
throw CircularReferenceException._(constructedPath);
|
throw CircularReferenceException._(constructedPath);
|
||||||
}
|
}
|
||||||
|
|
||||||
bool didVisitAlready(MoorSchemaEntity table) {
|
bool didVisitAlready(DriftSchemaEntity table) {
|
||||||
return previous[table] != null || result.contains(table);
|
return previous[table] != null || result.contains(table);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Thrown by [sortEntitiesTopologically] when the graph formed by
|
/// Thrown by [sortEntitiesTopologically] when the graph formed by
|
||||||
/// [MoorSchemaEntity.references] is not acyclic except for self-references.
|
/// [DriftSchemaEntity.references] is not acyclic except for self-references.
|
||||||
class CircularReferenceException implements Exception {
|
class CircularReferenceException implements Exception {
|
||||||
/// The list of entities forming a circular reference, so that the first
|
/// The list of entities forming a circular reference, so that the first
|
||||||
/// entity in this list references the second one and so on. The last entity
|
/// entity in this list references the second one and so on. The last entity
|
||||||
/// in this list references the first one, thus forming a cycle.
|
/// in this list references the first one, thus forming a cycle.
|
||||||
final List<MoorSchemaEntity> affected;
|
final List<DriftSchemaEntity> affected;
|
||||||
|
|
||||||
CircularReferenceException._(this.affected);
|
CircularReferenceException._(this.affected);
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,20 +1,20 @@
|
||||||
import 'package:build_config/build_config.dart';
|
import 'package:build_config/build_config.dart';
|
||||||
import 'package:drift_dev/src/analyzer/options.dart';
|
import 'package:drift_dev/src/analyzer/options.dart';
|
||||||
|
|
||||||
Future<MoorOptions> fromRootDir(String path) async {
|
Future<DriftOptions> fromRootDir(String path) async {
|
||||||
final options = await BuildConfig.fromPackageDir(path);
|
final options = await BuildConfig.fromPackageDir(path);
|
||||||
return readOptionsFromConfig(options);
|
return readOptionsFromConfig(options);
|
||||||
}
|
}
|
||||||
|
|
||||||
MoorOptions readOptionsFromConfig(BuildConfig config) {
|
DriftOptions readOptionsFromConfig(BuildConfig config) {
|
||||||
final options = config.buildTargets.values
|
final options = config.buildTargets.values
|
||||||
.map((t) {
|
.map((t) {
|
||||||
return t.builders['moor_generator:moor_generator']?.options ??
|
return t.builders['moor_generator:moor_generator']?.options ??
|
||||||
t.builders['drift_dev:drift_dev']?.options;
|
t.builders['drift_dev:drift_dev']?.options;
|
||||||
})
|
})
|
||||||
.whereType<Map>()
|
.whereType<Map>()
|
||||||
.map((json) => MoorOptions.fromJson(json));
|
.map((json) => DriftOptions.fromJson(json));
|
||||||
|
|
||||||
final iterator = options.iterator;
|
final iterator = options.iterator;
|
||||||
return iterator.moveNext() ? iterator.current : const MoorOptions.defaults();
|
return iterator.moveNext() ? iterator.current : const DriftOptions.defaults();
|
||||||
}
|
}
|
||||||
|
|
|
@ -54,7 +54,7 @@ class DatabaseWriter {
|
||||||
'$className.connect(DatabaseConnection c): super.connect(c); \n');
|
'$className.connect(DatabaseConnection c): super.connect(c); \n');
|
||||||
}
|
}
|
||||||
|
|
||||||
final entityGetters = <MoorSchemaEntity, String>{};
|
final entityGetters = <DriftSchemaEntity, String>{};
|
||||||
|
|
||||||
for (final entity in db.entities) {
|
for (final entity in db.entities) {
|
||||||
final getterName = entity.dbGetterName;
|
final getterName = entity.dbGetterName;
|
||||||
|
@ -62,7 +62,7 @@ class DatabaseWriter {
|
||||||
entityGetters[entity] = getterName;
|
entityGetters[entity] = getterName;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (entity is MoorTable) {
|
if (entity is DriftTable) {
|
||||||
final tableClassName = entity.entityInfoName;
|
final tableClassName = entity.entityInfoName;
|
||||||
|
|
||||||
writeMemoizedGetter(
|
writeMemoizedGetter(
|
||||||
|
|
|
@ -19,7 +19,7 @@ class QueryWriter {
|
||||||
late final ExplicitAliasTransformer _transformer;
|
late final ExplicitAliasTransformer _transformer;
|
||||||
final StringBuffer _buffer;
|
final StringBuffer _buffer;
|
||||||
|
|
||||||
MoorOptions get options => scope.writer.options;
|
DriftOptions get options => scope.writer.options;
|
||||||
|
|
||||||
QueryWriter(this.scope) : _buffer = scope.leaf();
|
QueryWriter(this.scope) : _buffer = scope.leaf();
|
||||||
|
|
||||||
|
@ -159,7 +159,7 @@ class QueryWriter {
|
||||||
/// in the same scope, reads the [column] from that row and brings it into a
|
/// in the same scope, reads the [column] from that row and brings it into a
|
||||||
/// suitable type.
|
/// suitable type.
|
||||||
String readingCode(ResultColumn column, GenerationOptions generationOptions,
|
String readingCode(ResultColumn column, GenerationOptions generationOptions,
|
||||||
MoorOptions moorOptions) {
|
DriftOptions moorOptions) {
|
||||||
var rawDartType = dartTypeNames[column.type];
|
var rawDartType = dartTypeNames[column.type];
|
||||||
if (column.nullable) {
|
if (column.nullable) {
|
||||||
rawDartType = '$rawDartType?';
|
rawDartType = '$rawDartType?';
|
||||||
|
@ -489,7 +489,7 @@ String _converter(UsedTypeConverter converter) {
|
||||||
|
|
||||||
class _ExpandedDeclarationWriter {
|
class _ExpandedDeclarationWriter {
|
||||||
final SqlQuery query;
|
final SqlQuery query;
|
||||||
final MoorOptions options;
|
final DriftOptions options;
|
||||||
final StringBuffer _buffer;
|
final StringBuffer _buffer;
|
||||||
|
|
||||||
bool indexCounterWasDeclared = false;
|
bool indexCounterWasDeclared = false;
|
||||||
|
|
|
@ -27,7 +27,7 @@ String placeholderContextName(FoundDartPlaceholder placeholder) {
|
||||||
class SqlWriter extends NodeSqlBuilder {
|
class SqlWriter extends NodeSqlBuilder {
|
||||||
final StringBuffer _out;
|
final StringBuffer _out;
|
||||||
final SqlQuery? query;
|
final SqlQuery? query;
|
||||||
final MoorOptions options;
|
final DriftOptions options;
|
||||||
final Map<NestedStarResultColumn, NestedResultTable> _starColumnToResolved;
|
final Map<NestedStarResultColumn, NestedResultTable> _starColumnToResolved;
|
||||||
|
|
||||||
bool get _isPostgres => options.effectiveDialect == SqlDialect.postgres;
|
bool get _isPostgres => options.effectiveDialect == SqlDialect.postgres;
|
||||||
|
@ -37,7 +37,7 @@ class SqlWriter extends NodeSqlBuilder {
|
||||||
: _out = out,
|
: _out = out,
|
||||||
super(escapeForDart ? _DartEscapingSink(out) : out);
|
super(escapeForDart ? _DartEscapingSink(out) : out);
|
||||||
|
|
||||||
factory SqlWriter(MoorOptions options,
|
factory SqlWriter(DriftOptions options,
|
||||||
{SqlQuery? query, bool escapeForDart = true}) {
|
{SqlQuery? query, bool escapeForDart = true}) {
|
||||||
// Index nested results by their syntactic origin for faster lookups later
|
// Index nested results by their syntactic origin for faster lookups later
|
||||||
var doubleStarColumnToResolvedTable =
|
var doubleStarColumnToResolvedTable =
|
||||||
|
|
|
@ -5,11 +5,11 @@ import 'package:drift_dev/src/writer/utils/override_toString.dart';
|
||||||
import 'package:drift_dev/writer.dart';
|
import 'package:drift_dev/writer.dart';
|
||||||
|
|
||||||
class DataClassWriter {
|
class DataClassWriter {
|
||||||
final MoorEntityWithResultSet table;
|
final DriftEntityWithResultSet table;
|
||||||
final Scope scope;
|
final Scope scope;
|
||||||
final columns = <MoorColumn>[];
|
final columns = <DriftColumn>[];
|
||||||
|
|
||||||
bool get isInsertable => table is MoorTable;
|
bool get isInsertable => table is DriftTable;
|
||||||
|
|
||||||
late StringBuffer _buffer;
|
late StringBuffer _buffer;
|
||||||
|
|
||||||
|
@ -102,7 +102,7 @@ class DataClassWriter {
|
||||||
// The GeneratedDatabase db parameter is not actually used, but we need to
|
// The GeneratedDatabase db parameter is not actually used, but we need to
|
||||||
// keep it on tables for backwards compatibility.
|
// keep it on tables for backwards compatibility.
|
||||||
final includeUnusedDbColumn =
|
final includeUnusedDbColumn =
|
||||||
scope.generationOptions.writeForMoorPackage && table is MoorTable;
|
scope.generationOptions.writeForMoorPackage && table is DriftTable;
|
||||||
|
|
||||||
_buffer
|
_buffer
|
||||||
..write('factory $dataClassName.fromData')
|
..write('factory $dataClassName.fromData')
|
||||||
|
@ -296,7 +296,7 @@ class DataClassWriter {
|
||||||
}
|
}
|
||||||
|
|
||||||
void _writeToCompanion() {
|
void _writeToCompanion() {
|
||||||
final asTable = table as MoorTable;
|
final asTable = table as DriftTable;
|
||||||
|
|
||||||
_buffer
|
_buffer
|
||||||
..write(asTable.getNameForCompanionClass(scope.options))
|
..write(asTable.getNameForCompanionClass(scope.options))
|
||||||
|
@ -353,17 +353,17 @@ class DataClassWriter {
|
||||||
/// Generates code mapping a row (represented as a `Map`) to positional and
|
/// Generates code mapping a row (represented as a `Map`) to positional and
|
||||||
/// named Dart arguments.
|
/// named Dart arguments.
|
||||||
class RowMappingWriter {
|
class RowMappingWriter {
|
||||||
final List<MoorColumn> positional;
|
final List<DriftColumn> positional;
|
||||||
final Map<MoorColumn, String> named;
|
final Map<DriftColumn, String> named;
|
||||||
final MoorEntityWithResultSet table;
|
final DriftEntityWithResultSet table;
|
||||||
final GenerationOptions options;
|
final GenerationOptions options;
|
||||||
final MoorOptions moorOptions;
|
final DriftOptions moorOptions;
|
||||||
|
|
||||||
RowMappingWriter(
|
RowMappingWriter(
|
||||||
this.positional, this.named, this.table, this.options, this.moorOptions);
|
this.positional, this.named, this.table, this.options, this.moorOptions);
|
||||||
|
|
||||||
void writeArguments(StringBuffer buffer) {
|
void writeArguments(StringBuffer buffer) {
|
||||||
String readAndMap(MoorColumn column) {
|
String readAndMap(DriftColumn column) {
|
||||||
final columnName = column.name.name;
|
final columnName = column.name.name;
|
||||||
final rawData = "data['\${effectivePrefix}$columnName']";
|
final rawData = "data['\${effectivePrefix}$columnName']";
|
||||||
final sqlType = 'const ${sqlTypes[column.type]}()';
|
final sqlType = 'const ${sqlTypes[column.type]}()';
|
||||||
|
|
|
@ -9,11 +9,11 @@ import '../utils/column_constraints.dart';
|
||||||
///
|
///
|
||||||
/// Both classes need to generate column getters and a mapping function.
|
/// Both classes need to generate column getters and a mapping function.
|
||||||
abstract class TableOrViewWriter {
|
abstract class TableOrViewWriter {
|
||||||
MoorEntityWithResultSet get tableOrView;
|
DriftEntityWithResultSet get tableOrView;
|
||||||
StringBuffer get buffer;
|
StringBuffer get buffer;
|
||||||
|
|
||||||
void writeColumnGetter(
|
void writeColumnGetter(
|
||||||
MoorColumn column, GenerationOptions options, bool isOverride) {
|
DriftColumn column, GenerationOptions options, bool isOverride) {
|
||||||
final isNullable = column.nullable;
|
final isNullable = column.nullable;
|
||||||
final additionalParams = <String, String>{};
|
final additionalParams = <String, String>{};
|
||||||
final expressionBuffer = StringBuffer();
|
final expressionBuffer = StringBuffer();
|
||||||
|
@ -41,8 +41,8 @@ abstract class TableOrViewWriter {
|
||||||
|
|
||||||
additionalParams['type'] = 'const ${column.sqlType().runtimeType}()';
|
additionalParams['type'] = 'const ${column.sqlType().runtimeType}()';
|
||||||
|
|
||||||
if (tableOrView is MoorTable) {
|
if (tableOrView is DriftTable) {
|
||||||
additionalParams['requiredDuringInsert'] = (tableOrView as MoorTable)
|
additionalParams['requiredDuringInsert'] = (tableOrView as DriftTable)
|
||||||
.isColumnRequiredForInsert(column)
|
.isColumnRequiredForInsert(column)
|
||||||
.toString();
|
.toString();
|
||||||
}
|
}
|
||||||
|
@ -144,8 +144,8 @@ abstract class TableOrViewWriter {
|
||||||
"tablePrefix != null ? '\$tablePrefix.' : '';");
|
"tablePrefix != null ? '\$tablePrefix.' : '';");
|
||||||
|
|
||||||
final info = tableOrView.existingRowClass!;
|
final info = tableOrView.existingRowClass!;
|
||||||
final positionalToIndex = <MoorColumn, int>{};
|
final positionalToIndex = <DriftColumn, int>{};
|
||||||
final named = <MoorColumn, String>{};
|
final named = <DriftColumn, String>{};
|
||||||
|
|
||||||
final parameters = info.constructor.parameters;
|
final parameters = info.constructor.parameters;
|
||||||
info.mapping.forEach((column, parameter) {
|
info.mapping.forEach((column, parameter) {
|
||||||
|
@ -186,7 +186,7 @@ abstract class TableOrViewWriter {
|
||||||
} else {
|
} else {
|
||||||
// Use default .fromData constructor in the moor-generated data class
|
// Use default .fromData constructor in the moor-generated data class
|
||||||
final hasDbParameter = scope.generationOptions.writeForMoorPackage &&
|
final hasDbParameter = scope.generationOptions.writeForMoorPackage &&
|
||||||
tableOrView is MoorTable;
|
tableOrView is DriftTable;
|
||||||
if (hasDbParameter) {
|
if (hasDbParameter) {
|
||||||
buffer.write('return $dataClassName.fromData(data, attachedDatabase, '
|
buffer.write('return $dataClassName.fromData(data, attachedDatabase, '
|
||||||
"prefix: tablePrefix != null ? '\$tablePrefix.' : null);\n");
|
"prefix: tablePrefix != null ? '\$tablePrefix.' : null);\n");
|
||||||
|
@ -213,14 +213,14 @@ abstract class TableOrViewWriter {
|
||||||
}
|
}
|
||||||
|
|
||||||
class TableWriter extends TableOrViewWriter {
|
class TableWriter extends TableOrViewWriter {
|
||||||
final MoorTable table;
|
final DriftTable table;
|
||||||
final Scope scope;
|
final Scope scope;
|
||||||
|
|
||||||
@override
|
@override
|
||||||
late StringBuffer buffer;
|
late StringBuffer buffer;
|
||||||
|
|
||||||
@override
|
@override
|
||||||
MoorTable get tableOrView => table;
|
DriftTable get tableOrView => table;
|
||||||
|
|
||||||
TableWriter(this.table, this.scope);
|
TableWriter(this.table, this.scope);
|
||||||
|
|
||||||
|
@ -340,7 +340,7 @@ class TableWriter extends TableOrViewWriter {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
void _writeColumnVerificationMeta(MoorColumn column) {
|
void _writeColumnVerificationMeta(DriftColumn column) {
|
||||||
if (!_skipVerification) {
|
if (!_skipVerification) {
|
||||||
buffer
|
buffer
|
||||||
..write('final VerificationMeta ${_fieldNameForColumnMeta(column)} = ')
|
..write('final VerificationMeta ${_fieldNameForColumnMeta(column)} = ')
|
||||||
|
@ -392,7 +392,7 @@ class TableWriter extends TableOrViewWriter {
|
||||||
buffer.write('return context;\n}\n');
|
buffer.write('return context;\n}\n');
|
||||||
}
|
}
|
||||||
|
|
||||||
String _fieldNameForColumnMeta(MoorColumn column) {
|
String _fieldNameForColumnMeta(DriftColumn column) {
|
||||||
return '_${column.dartGetterName}Meta';
|
return '_${column.dartGetterName}Meta';
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -5,12 +5,12 @@ import 'package:drift_dev/src/writer/utils/override_toString.dart';
|
||||||
import 'package:drift_dev/writer.dart';
|
import 'package:drift_dev/writer.dart';
|
||||||
|
|
||||||
class UpdateCompanionWriter {
|
class UpdateCompanionWriter {
|
||||||
final MoorTable table;
|
final DriftTable table;
|
||||||
final Scope scope;
|
final Scope scope;
|
||||||
|
|
||||||
late StringBuffer _buffer;
|
late StringBuffer _buffer;
|
||||||
|
|
||||||
late final List<MoorColumn> columns = [
|
late final List<DriftColumn> columns = [
|
||||||
for (final column in table.columns)
|
for (final column in table.columns)
|
||||||
if (!column.isGenerated) column,
|
if (!column.isGenerated) column,
|
||||||
];
|
];
|
||||||
|
@ -65,7 +65,7 @@ class UpdateCompanionWriter {
|
||||||
/// absent during insert are marked `@required` here. Also, we don't need to
|
/// absent during insert are marked `@required` here. Also, we don't need to
|
||||||
/// use value wrappers here - `Value.absent` simply isn't an option.
|
/// use value wrappers here - `Value.absent` simply isn't an option.
|
||||||
void _writeInsertConstructor() {
|
void _writeInsertConstructor() {
|
||||||
final requiredColumns = <MoorColumn>{};
|
final requiredColumns = <DriftColumn>{};
|
||||||
|
|
||||||
// can't be constant because we use initializers (this.a = Value(a)).
|
// can't be constant because we use initializers (this.a = Value(a)).
|
||||||
// for a parameter a which is only potentially constant.
|
// for a parameter a which is only potentially constant.
|
||||||
|
|
|
@ -77,7 +77,7 @@ class ViewWriter extends TableOrViewWriter {
|
||||||
..write('@override\n String get entityName=>'
|
..write('@override\n String get entityName=>'
|
||||||
' ${asDartLiteral(view.name)};\n');
|
' ${asDartLiteral(view.name)};\n');
|
||||||
|
|
||||||
if (view.declaration is MoorViewDeclaration) {
|
if (view.declaration is DriftViewDeclaration) {
|
||||||
buffer.write('@override\n String get createViewStmt =>'
|
buffer.write('@override\n String get createViewStmt =>'
|
||||||
' ${asDartLiteral(view.createSql(scope.options))};\n');
|
' ${asDartLiteral(view.createSql(scope.options))};\n');
|
||||||
} else {
|
} else {
|
||||||
|
@ -96,7 +96,7 @@ class ViewWriter extends TableOrViewWriter {
|
||||||
// Dart, but it wasn't defined by the user. Instead, the column is
|
// Dart, but it wasn't defined by the user. Instead, the column is
|
||||||
// implicitly generated from a entry in the `select()` query clause.
|
// implicitly generated from a entry in the `select()` query clause.
|
||||||
// We can drop all information from it since only the name is relevant.
|
// We can drop all information from it since only the name is relevant.
|
||||||
final shortColumn = MoorColumn(
|
final shortColumn = DriftColumn(
|
||||||
type: column.type,
|
type: column.type,
|
||||||
dartGetterName: column.dartGetterName,
|
dartGetterName: column.dartGetterName,
|
||||||
name: column.name);
|
name: column.name);
|
||||||
|
|
|
@ -3,7 +3,7 @@ import 'package:sqlparser/sqlparser.dart';
|
||||||
|
|
||||||
import '../../model/column.dart';
|
import '../../model/column.dart';
|
||||||
|
|
||||||
String defaultConstraints(MoorColumn column) {
|
String defaultConstraints(DriftColumn column) {
|
||||||
final defaultConstraints = <String>[];
|
final defaultConstraints = <String>[];
|
||||||
|
|
||||||
var wrotePkConstraint = false;
|
var wrotePkConstraint = false;
|
||||||
|
|
|
@ -11,7 +11,7 @@ import 'package:drift_dev/src/analyzer/options.dart';
|
||||||
/// passing a [Scope] we will always be able to write code in a parent scope.
|
/// passing a [Scope] we will always be able to write code in a parent scope.
|
||||||
class Writer {
|
class Writer {
|
||||||
late final Scope _root;
|
late final Scope _root;
|
||||||
final MoorOptions options;
|
final DriftOptions options;
|
||||||
final GenerationOptions generationOptions;
|
final GenerationOptions generationOptions;
|
||||||
|
|
||||||
Writer(this.options, {this.generationOptions = const GenerationOptions()}) {
|
Writer(this.options, {this.generationOptions = const GenerationOptions()}) {
|
||||||
|
@ -62,7 +62,7 @@ class Scope extends _Node {
|
||||||
writer = writer ?? parent!.writer,
|
writer = writer ?? parent!.writer,
|
||||||
super(parent);
|
super(parent);
|
||||||
|
|
||||||
MoorOptions get options => writer.options;
|
DriftOptions get options => writer.options;
|
||||||
|
|
||||||
GenerationOptions get generationOptions => writer.generationOptions;
|
GenerationOptions get generationOptions => writer.generationOptions;
|
||||||
|
|
||||||
|
@ -160,11 +160,11 @@ class DartScope {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
extension WriterUtilsForOptions on MoorOptions {
|
extension WriterUtilsForOptions on DriftOptions {
|
||||||
String get fieldModifier => generateMutableClasses ? '' : 'final';
|
String get fieldModifier => generateMutableClasses ? '' : 'final';
|
||||||
}
|
}
|
||||||
|
|
||||||
extension WriterUtilsForColumns on MoorColumn {
|
extension WriterUtilsForColumns on DriftColumn {
|
||||||
/// Adds an `this.` prefix is the [dartGetterName] is in [locals].
|
/// Adds an `this.` prefix is the [dartGetterName] is in [locals].
|
||||||
String thisIfNeeded(Set<String> locals) {
|
String thisIfNeeded(Set<String> locals) {
|
||||||
if (locals.contains(dartGetterName)) {
|
if (locals.contains(dartGetterName)) {
|
||||||
|
|
|
@ -130,7 +130,7 @@ class Database {}
|
||||||
|
|
||||||
expect(
|
expect(
|
||||||
foo.references,
|
foo.references,
|
||||||
contains(isA<MoorTable>()
|
contains(isA<DriftTable>()
|
||||||
.having((tbl) => tbl.sqlName, 'sqlName', 'other_table')));
|
.having((tbl) => tbl.sqlName, 'sqlName', 'other_table')));
|
||||||
|
|
||||||
final column = foo.columns.single;
|
final column = foo.columns.single;
|
||||||
|
|
|
@ -30,7 +30,7 @@ void main() {
|
||||||
final task = session.startTask(backendTask);
|
final task = session.startTask(backendTask);
|
||||||
|
|
||||||
final library = await backendTask.resolveDart(input);
|
final library = await backendTask.resolveDart(input);
|
||||||
final parser = MoorDartParser(ParseDartStep(
|
final parser = DriftDartParser(ParseDartStep(
|
||||||
task, session.registerFile(input), library, await task.helper));
|
task, session.registerFile(input), library, await task.helper));
|
||||||
|
|
||||||
Future<MethodDeclaration> _loadDeclaration(Element element) async {
|
Future<MethodDeclaration> _loadDeclaration(Element element) async {
|
||||||
|
|
|
@ -55,7 +55,7 @@ void main() {
|
||||||
|
|
||||||
expect(
|
expect(
|
||||||
errors,
|
errors,
|
||||||
contains(isA<MoorError>().having((e) => e.message, 'message',
|
contains(isA<DriftError>().having((e) => e.message, 'message',
|
||||||
allOf(contains('Not an enum'), contains('NotAnEnum')))),
|
allOf(contains('Not an enum'), contains('NotAnEnum')))),
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|
|
@ -15,7 +15,7 @@ import '../utils.dart';
|
||||||
void main() {
|
void main() {
|
||||||
late TestBackend backend;
|
late TestBackend backend;
|
||||||
late ParseDartStep dartStep;
|
late ParseDartStep dartStep;
|
||||||
late MoorDartParser parser;
|
late DriftDartParser parser;
|
||||||
|
|
||||||
setUpAll(() {
|
setUpAll(() {
|
||||||
backend = TestBackend({
|
backend = TestBackend({
|
||||||
|
@ -142,10 +142,10 @@ void main() {
|
||||||
|
|
||||||
dartStep = ParseDartStep(
|
dartStep = ParseDartStep(
|
||||||
moorTask, file, await task.resolveDart(uri), await moorTask.helper);
|
moorTask, file, await task.resolveDart(uri), await moorTask.helper);
|
||||||
parser = MoorDartParser(dartStep);
|
parser = DriftDartParser(dartStep);
|
||||||
});
|
});
|
||||||
|
|
||||||
Future<MoorTable?> parse(String name) async {
|
Future<DriftTable?> parse(String name) async {
|
||||||
return parser.parseTable(dartStep.library.getType(name)!);
|
return parser.parseTable(dartStep.library.getType(name)!);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -281,7 +281,7 @@ void main() {
|
||||||
final c = table.columns.singleWhere((c) => c.name.name == 'c');
|
final c = table.columns.singleWhere((c) => c.name.name == 'c');
|
||||||
|
|
||||||
void expectType(
|
void expectType(
|
||||||
MoorColumn column, bool hasOverriddenSource, String toString) {
|
DriftColumn column, bool hasOverriddenSource, String toString) {
|
||||||
expect(
|
expect(
|
||||||
column.typeConverter,
|
column.typeConverter,
|
||||||
isA<UsedTypeConverter>()
|
isA<UsedTypeConverter>()
|
||||||
|
|
|
@ -47,7 +47,7 @@ CREATE TABLE users (
|
||||||
|
|
||||||
Future<void> testWith(String fileName) async {
|
Future<void> testWith(String fileName) async {
|
||||||
final result = await state.analyze(fileName);
|
final result = await state.analyze(fileName);
|
||||||
final table = result.currentResult!.declaredEntities.single as MoorTable;
|
final table = result.currentResult!.declaredEntities.single as DriftTable;
|
||||||
|
|
||||||
final foo = table.columns[0];
|
final foo = table.columns[0];
|
||||||
final bar = table.columns[1];
|
final bar = table.columns[1];
|
||||||
|
|
|
@ -56,7 +56,7 @@ WITH alias("first", second) AS (SELECT * FROM foo) SELECT * FROM alias;
|
||||||
expect(file.state, FileState.analyzed);
|
expect(file.state, FileState.analyzed);
|
||||||
expect(file.errors.errors, isEmpty);
|
expect(file.errors.errors, isEmpty);
|
||||||
|
|
||||||
final result = file.currentResult as ParsedMoorFile;
|
final result = file.currentResult as ParsedDriftFile;
|
||||||
final query = result.resolvedQueries!.firstWhere((q) => q.name == 'test')
|
final query = result.resolvedQueries!.firstWhere((q) => q.name == 'test')
|
||||||
as SqlSelectQuery;
|
as SqlSelectQuery;
|
||||||
|
|
||||||
|
@ -73,7 +73,7 @@ WITH alias("first", second) AS (SELECT * FROM foo) SELECT * FROM alias;
|
||||||
|
|
||||||
test('finds the underlying table when aliased through CFE', () {
|
test('finds the underlying table when aliased through CFE', () {
|
||||||
final file = session.registerFile(Uri.parse('package:foo/test.moor'));
|
final file = session.registerFile(Uri.parse('package:foo/test.moor'));
|
||||||
final result = file.currentResult as ParsedMoorFile;
|
final result = file.currentResult as ParsedDriftFile;
|
||||||
final query = result.resolvedQueries!.firstWhere((q) => q.name == 'test2')
|
final query = result.resolvedQueries!.firstWhere((q) => q.name == 'test2')
|
||||||
as SqlSelectQuery;
|
as SqlSelectQuery;
|
||||||
|
|
|
@ -48,7 +48,7 @@ void main() {
|
||||||
expect(
|
expect(
|
||||||
file.errors.errors,
|
file.errors.errors,
|
||||||
contains(
|
contains(
|
||||||
isA<MoorError>().having(
|
isA<DriftError>().having(
|
||||||
(e) => e.message,
|
(e) => e.message,
|
||||||
'message',
|
'message',
|
||||||
contains('Type DoesNotExist could not be found'),
|
contains('Type DoesNotExist could not be found'),
|
||||||
|
@ -83,7 +83,7 @@ void main() {
|
||||||
expect(
|
expect(
|
||||||
file.errors.errors,
|
file.errors.errors,
|
||||||
contains(
|
contains(
|
||||||
isA<MoorError>().having(
|
isA<DriftError>().having(
|
||||||
(e) => e.message,
|
(e) => e.message,
|
||||||
'message',
|
'message',
|
||||||
contains("can't apply another converter"),
|
contains("can't apply another converter"),
|
||||||
|
@ -112,7 +112,7 @@ void main() {
|
||||||
expect(
|
expect(
|
||||||
file.errors.errors,
|
file.errors.errors,
|
||||||
contains(
|
contains(
|
||||||
isA<ErrorInMoorFile>()
|
isA<ErrorInDriftFile>()
|
||||||
.having(
|
.having(
|
||||||
(e) => e.message,
|
(e) => e.message,
|
||||||
'message',
|
'message',
|
|
@ -28,7 +28,7 @@ void main() {
|
||||||
|
|
||||||
expect(column.type!.type, BasicType.text);
|
expect(column.type!.type, BasicType.text);
|
||||||
expect(view.references,
|
expect(view.references,
|
||||||
contains(isA<MoorTable>().having((t) => t.sqlName, 'sqlName', 't')));
|
contains(isA<DriftTable>().having((t) => t.sqlName, 'sqlName', 't')));
|
||||||
expect(file.errors.errors, isEmpty);
|
expect(file.errors.errors, isEmpty);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
@ -82,7 +82,7 @@ void main() {
|
||||||
|
|
||||||
expect(
|
expect(
|
||||||
file.errors.errors,
|
file.errors.errors,
|
||||||
contains(isA<MoorError>().having(
|
contains(isA<DriftError>().having(
|
||||||
(e) => e.message,
|
(e) => e.message,
|
||||||
'message',
|
'message',
|
||||||
contains('Could not find t.'),
|
contains('Could not find t.'),
|
||||||
|
@ -104,7 +104,7 @@ void main() {
|
||||||
|
|
||||||
expect(
|
expect(
|
||||||
file.errors.errors,
|
file.errors.errors,
|
||||||
contains(isA<MoorError>().having(
|
contains(isA<DriftError>().having(
|
||||||
(e) => e.message,
|
(e) => e.message,
|
||||||
'message',
|
'message',
|
||||||
contains('Nested star columns may only appear in a top-level select '
|
contains('Nested star columns may only appear in a top-level select '
|
|
@ -39,11 +39,11 @@ class ExistingForView {
|
||||||
final file = await state.analyze('package:a/db.moor');
|
final file = await state.analyze('package:a/db.moor');
|
||||||
expect(file.errors.errors, isEmpty);
|
expect(file.errors.errors, isEmpty);
|
||||||
|
|
||||||
final result = file.currentResult as ParsedMoorFile;
|
final result = file.currentResult as ParsedDriftFile;
|
||||||
final customName = result.declaredEntities
|
final customName = result.declaredEntities
|
||||||
.singleWhere((e) => e.displayName == 'custom_name') as MoorTable;
|
.singleWhere((e) => e.displayName == 'custom_name') as DriftTable;
|
||||||
final existing = result.declaredEntities
|
final existing = result.declaredEntities
|
||||||
.singleWhere((e) => e.displayName == 'existing') as MoorTable;
|
.singleWhere((e) => e.displayName == 'existing') as DriftTable;
|
||||||
final existingView = result.declaredEntities
|
final existingView = result.declaredEntities
|
||||||
.singleWhere((e) => e.displayName == 'existing_view') as MoorView;
|
.singleWhere((e) => e.displayName == 'existing_view') as MoorView;
|
||||||
|
|
||||||
|
@ -86,7 +86,7 @@ CREATE TABLE moor_ints (
|
||||||
final file = await state.analyze('package:a/generic.moor');
|
final file = await state.analyze('package:a/generic.moor');
|
||||||
expect(file.errors.errors, isEmpty);
|
expect(file.errors.errors, isEmpty);
|
||||||
|
|
||||||
final tables = (file.currentResult as ParsedMoorFile).declaredTables;
|
final tables = (file.currentResult as ParsedDriftFile).declaredTables;
|
||||||
final strings = tables.singleWhere((e) => e.sqlName == 'moor_strings');
|
final strings = tables.singleWhere((e) => e.sqlName == 'moor_strings');
|
||||||
final ints = tables.singleWhere((e) => e.sqlName == 'moor_ints');
|
final ints = tables.singleWhere((e) => e.sqlName == 'moor_ints');
|
||||||
|
|
|
@ -41,7 +41,7 @@ CREATE TABLE friendships (
|
||||||
expect(
|
expect(
|
||||||
table.references,
|
table.references,
|
||||||
[
|
[
|
||||||
const TypeMatcher<MoorTable>()
|
const TypeMatcher<DriftTable>()
|
||||||
.having((table) => table.displayName, 'displayName', 'users'),
|
.having((table) => table.displayName, 'displayName', 'users'),
|
||||||
],
|
],
|
||||||
);
|
);
|
||||||
|
@ -75,9 +75,9 @@ END;
|
||||||
expect(
|
expect(
|
||||||
trigger.references,
|
trigger.references,
|
||||||
{
|
{
|
||||||
const TypeMatcher<MoorTable>().having(
|
const TypeMatcher<DriftTable>().having(
|
||||||
(table) => table.displayName, 'displayName', 'friendships'),
|
(table) => table.displayName, 'displayName', 'friendships'),
|
||||||
const TypeMatcher<MoorTable>()
|
const TypeMatcher<DriftTable>()
|
||||||
.having((table) => table.displayName, 'displayName', 'users'),
|
.having((table) => table.displayName, 'displayName', 'users'),
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
@ -102,7 +102,7 @@ CREATE INDEX idx ON users (name);
|
||||||
|
|
||||||
final trigger = file.currentResult!.declaredEntities.single as MoorIndex;
|
final trigger = file.currentResult!.declaredEntities.single as MoorIndex;
|
||||||
expect(trigger.references, {
|
expect(trigger.references, {
|
||||||
const TypeMatcher<MoorTable>()
|
const TypeMatcher<DriftTable>()
|
||||||
.having((table) => table.displayName, 'displayName', 'users'),
|
.having((table) => table.displayName, 'displayName', 'users'),
|
||||||
});
|
});
|
||||||
});
|
});
|
|
@ -37,7 +37,7 @@ void main() {
|
||||||
expect(file.errors.errors, hasLength(1));
|
expect(file.errors.errors, hasLength(1));
|
||||||
expect(
|
expect(
|
||||||
file.errors.errors.single,
|
file.errors.errors.single,
|
||||||
isA<ErrorInMoorFile>()
|
isA<ErrorInDriftFile>()
|
||||||
.having(
|
.having(
|
||||||
(e) => e.message,
|
(e) => e.message,
|
||||||
'message',
|
'message',
|
|
@ -1,6 +1,6 @@
|
||||||
import 'package:drift_dev/moor_generator.dart';
|
import 'package:drift_dev/moor_generator.dart';
|
||||||
|
import 'package:drift_dev/src/analyzer/drift/moor_ffi_extension.dart';
|
||||||
import 'package:drift_dev/src/analyzer/errors.dart';
|
import 'package:drift_dev/src/analyzer/errors.dart';
|
||||||
import 'package:drift_dev/src/analyzer/moor/moor_ffi_extension.dart';
|
|
||||||
import 'package:drift_dev/src/analyzer/options.dart';
|
import 'package:drift_dev/src/analyzer/options.dart';
|
||||||
import 'package:drift_dev/src/analyzer/runner/results.dart';
|
import 'package:drift_dev/src/analyzer/runner/results.dart';
|
||||||
import 'package:sqlparser/sqlparser.dart' hide ResultColumn;
|
import 'package:sqlparser/sqlparser.dart' hide ResultColumn;
|
||||||
|
@ -98,14 +98,14 @@ import 'a.moor';
|
||||||
wrongArgs: SELECT sin(oid, foo) FROM numbers;
|
wrongArgs: SELECT sin(oid, foo) FROM numbers;
|
||||||
'''
|
'''
|
||||||
},
|
},
|
||||||
options: const MoorOptions.defaults(modules: [SqlModule.moor_ffi]),
|
options: const DriftOptions.defaults(modules: [SqlModule.moor_ffi]),
|
||||||
);
|
);
|
||||||
addTearDown(state.close);
|
addTearDown(state.close);
|
||||||
|
|
||||||
final fileA = await state.analyze('package:foo/a.moor');
|
final fileA = await state.analyze('package:foo/a.moor');
|
||||||
|
|
||||||
expect(fileA.errors.errors, isEmpty);
|
expect(fileA.errors.errors, isEmpty);
|
||||||
final resultA = fileA.currentResult as ParsedMoorFile;
|
final resultA = fileA.currentResult as ParsedDriftFile;
|
||||||
|
|
||||||
final queryInA = resultA.resolvedQueries!.single as SqlSelectQuery;
|
final queryInA = resultA.resolvedQueries!.single as SqlSelectQuery;
|
||||||
expect(
|
expect(
|
||||||
|
@ -116,7 +116,7 @@ wrongArgs: SELECT sin(oid, foo) FROM numbers;
|
||||||
|
|
||||||
final fileB = await state.analyze('package:foo/b.moor');
|
final fileB = await state.analyze('package:foo/b.moor');
|
||||||
expect(fileB.errors.errors, [
|
expect(fileB.errors.errors, [
|
||||||
const TypeMatcher<ErrorInMoorFile>()
|
const TypeMatcher<ErrorInDriftFile>()
|
||||||
.having((e) => e.span.text, 'span.text', 'sin(oid, foo)')
|
.having((e) => e.span.text, 'span.text', 'sin(oid, foo)')
|
||||||
]);
|
]);
|
||||||
});
|
});
|
|
@ -68,7 +68,7 @@ usersWithLongName: SELECT * FROM users WHERE LENGTH(name) > 25;
|
||||||
|
|
||||||
final result = await state.analyze('package:foo/a.moor');
|
final result = await state.analyze('package:foo/a.moor');
|
||||||
state.close();
|
state.close();
|
||||||
final file = result.currentResult as ParsedMoorFile;
|
final file = result.currentResult as ParsedDriftFile;
|
||||||
|
|
||||||
final users1 = file.declaredTables.singleWhere((t) => t.sqlName == 'users');
|
final users1 = file.declaredTables.singleWhere((t) => t.sqlName == 'users');
|
||||||
final users2 =
|
final users2 =
|
|
@ -25,7 +25,7 @@ CREATE TRIGGER tbl_au AFTER UPDATE ON tbl BEGIN
|
||||||
INSERT INTO fts_idx(rowid, b, c) VALUES (new.a, new.b, new.c);
|
INSERT INTO fts_idx(rowid, b, c) VALUES (new.a, new.b, new.c);
|
||||||
END;
|
END;
|
||||||
''',
|
''',
|
||||||
}, options: const MoorOptions.defaults(modules: [SqlModule.fts5]));
|
}, options: const DriftOptions.defaults(modules: [SqlModule.fts5]));
|
||||||
|
|
||||||
final result = await state.analyze('package:foo/a.moor');
|
final result = await state.analyze('package:foo/a.moor');
|
||||||
|
|
|
@ -29,7 +29,7 @@ void main() {
|
||||||
expect(file.errors.errors, hasLength(1));
|
expect(file.errors.errors, hasLength(1));
|
||||||
expect(
|
expect(
|
||||||
file.errors.errors.single,
|
file.errors.errors.single,
|
||||||
isA<ErrorInMoorFile>().having(
|
isA<ErrorInDriftFile>().having(
|
||||||
(e) => e.message,
|
(e) => e.message,
|
||||||
'message',
|
'message',
|
||||||
allOf(
|
allOf(
|
||||||
|
@ -46,7 +46,7 @@ void main() {
|
||||||
const {
|
const {
|
||||||
'a|lib/main.moor': _moorFile,
|
'a|lib/main.moor': _moorFile,
|
||||||
},
|
},
|
||||||
options: const MoorOptions.defaults(
|
options: const DriftOptions.defaults(
|
||||||
sqliteAnalysisOptions: SqliteAnalysisOptions(
|
sqliteAnalysisOptions: SqliteAnalysisOptions(
|
||||||
version: SqliteVersion.v3_35,
|
version: SqliteVersion.v3_35,
|
||||||
),
|
),
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue