Collect documentation for 2.0 release

This commit is contained in:
Simon Binder 2022-08-13 14:18:17 +02:00
parent 721b894141
commit a4fe582f25
No known key found for this signature in database
GPG Key ID: 7891917E4147B8C0
8 changed files with 105 additions and 145 deletions

View File

@ -68,13 +68,13 @@ At the moment, drift supports these options:
* `mutable_classes` (defaults to `false`): The fields generated in generated data, companion and result set classes are final
by default. You can make them mutable by setting `mutable_classes: true`.
* `raw_result_set_data`: The generator will expose the underlying `QueryRow` for generated result set classes
* `apply_converters_on_variables`: Applies type converters to variables in compiled statements.
* `generate_values_in_copy_with`: Generates a `Value<T?>` instead of `T?` for nullable columns in `copyWith`. This allows to set
* `apply_converters_on_variables` (defaults to `true`): Applies type converters to variables in compiled statements.
* `generate_values_in_copy_with` (defaults to `true`): Generates a `Value<T?>` instead of `T?` for nullable columns in `copyWith`. This allows to set
columns back to null (by using `Value(null)`). Passing `null` was ignored before, making it impossible to set columns
to `null`.
* `named_parameters`: Generates named parameters for named variables in SQL queries.
* `named_parameters_always_required`: All named parameters (generated if `named_parameters` option is `true`) will be required in Dart.
* `scoped_dart_components`: Generates a function parameter for [Dart placeholders]({{ '../Using SQL/drift_files.md#dart-components-in-sql' | pageUrl }}) in SQL.
* `scoped_dart_components` (defaults to `true`): Generates a function parameter for [Dart placeholders]({{ '../Using SQL/drift_files.md#dart-components-in-sql' | pageUrl }}) in SQL.
The function has a parameter for each table that is available in the query, making it easier to get aliases right when using
Dart placeholders.
* `store_date_time_values_as_text`: Whether date-time columns should be stored as ISO 8601 string instead of a unix timestamp.
@ -104,7 +104,8 @@ targets:
version: "3.34"
```
With that option, the generator will emit warnings when using newer sqlite version.
With that option, the generator will emit warnings when using features introduced
in more recent sqlite versions.
For instance, using more than one [upsert clause](https://sqlite.org/lang_upsert.html) is not supported
in 3.34, so an error would be reported.
Currently, the generator can't provide compatibility checks for versions below 3.34, which is the
@ -144,16 +145,17 @@ We currently support the following extensions:
## Recommended options
In general, we recommend using the default options. However, some options will be enabled by default in a future drift release.
In general, we recommend using the default options.
{%- comment %}
However, some options will be enabled by default in a future drift release.
At the moment, they're opt-in to not break existing users. These options are:
- `apply_converters_on_variables`
- `generate_values_in_copy_with`
- `scoped_dart_components`
(Currently all recommended options are also the default)
We recommend enabling these options.
You can disable some default drift features and reduce the amount of generated code with the following options:
{% endcomment %}
However, you can disable some default drift features and reduce the amount of generated code with the following options:
- `skip_verification_code: true`: You can remove a significant portion of generated code with this option. The
downside is that error messages when inserting invalid data will be less specific.

View File

@ -1,12 +1,74 @@
---
data:
title: "Moor and Drift"
title: "Upgrading"
description: >-
Information about the name change from `moor` to `drift`
How to upgrade between major drift versions
template: layouts/docs/single
path: /name
aliases: ["/name"]
---
## Migrating from drift 1.x to drift 2.x
The first major upgrade from drift 1 to drift 2 involves a number of breaking
changes and the removal of legacy features. These changes make drift easier to
maintain and easier to use.
This overview describes important breaking changes and how to apply them to your
project. For a full list of updates, see the [changelog](https://pub.dev/packages/drift/changelog).
1. __Null-safety only__: Drift will always emit null-safe code now. To use drift
2.x, please migrate your application (or at least the parts defining the
database) to Dart 2.12 or later.
2. Instances of `Expression` __always have a non-nullable type parameter__ now.
That is, use `Expression<int>` instead of `Expression<int?>`.
The old distinction was an attempt to embed SQL's behavior around `NULL`
values into Dart's typesystem. This didn't work, and so expressions no longer
have associated nullability in their types.
3. __Reading nullable expressions__: `QueryRow.read` (used to read columns from
a complex select in Dart) only supports non-nullable values now. To read
nullable values, use `readNullable`.
4. __Updated type converters__: The `mapToSql` and `mapToDart` methods have been
renamed to simply `toSql` and `toDart`, respectively.
Also, a type converter only needs to support the exact types that it was
declared with. In particular, a `TypeConverter<MyObject, String>` no longer
needs to deal with `null` values in either direction.
Type converters that are declared as nullable (e.g. `TypeConverter<Foo?, int?>`)
can no longer be applied to non-nullable columns. These changes bring proper
null-safety support to type converters and make their behavior around null
values more intuitive.
5. __Changed builder options__: To reduce the complexity of `drift_dev`, and to
make some long-recommended builder options the default, some options have been
removed or had their defaults changed.
- The following options are no longer available:
- `new_sql_code_generation`: Always enabled now. If this changes the behavior
of your queries, please open an issue!
- `null_aware_type_converters`: This is always enabled now with the new
semantics for type converters.
- `compact_query_method`: Has been enabled by default before, can no longer
be disabled now.
- `eagerly_load_dart_ast`: This option used to not do anything for a while
and has been removed entirely now.
- In addition, the defaults for these options has changed (but the existing
behavior can be restored if desired):
- `apply_converters_on_variables` is enabled by default now.
- `generate_values_in_copy_with` is enabled by default now.
- `scoped_dart_components` is enabled by default now.
6. The generated `fromData` factory on data classes is no longer generated. Use
the `map` methods on the table instance instead (e.g. `database.users.map`
instead of `User.fromData`).
The breaking changes in drift 2.0 are motivated by making drift easier to
maintain and to unblock upcoming new features. This release also provides some
new features, like nested transactions or support for `RETURNING` for updates
and deletes in the Dart API.
We hope the upgrade is worthwhile. If you run into any issues, please do not
hesistate to [start a new discussion](https://github.com/simolus3/drift/discussions)
or to [open an issue](https://github.com/simolus3/drift/issues).
Thanks for using drift!
## Migrating from `moor` to `drift` {#name}
Moor has been renamed to `drift`. The reason for this is that, in some parts of the world, moor may be used as a derogatory term.
I have not been aware of this when starting this project, but we believe that the current name does not reflect the inclusivity of the Dart and Flutter communities.
Despite the associated effort, I'm convinced that renaming the project is the right decision.
@ -14,13 +76,13 @@ Thank you for your understanding!
Until version `5.0.0`, the current `moor`, `moor_flutter` and `moor_generator` packages will continue to work - __no urgent action is necessary__.
All features and fixes to the new `drift` packages will be mirrored in `moor` as well.
At the next breaking release, the `moor` set of packages will be discontinued in favor of `drift` and `drift_dev`.
With the release of drift 2.0.0, the `moor` set of packages have been discontinued in favor of `drift` and `drift_dev`.
This page describes how to migrate from the old `moor` package to the new `drift` package.
This process can be automated, and we hope that the migration is a matter of minutes for you.
In case of issues with the tool, this page also describes how to manually migrate to the new `drift` packages.
## Automatic migration
### Automatic migration
To make the name change as easy as possible for you, drift comes with an automatic migration tool for your
project.
@ -55,7 +117,7 @@ Congratulations, your project is now using drift!
If you run into any issues with the automatic migration tool, please [open an issue](https://github.com/simolus3/drift/issues/new/).
## Manual migration
### Manual migration
To migrate from `moor` to `drift`, you may have to update:
@ -66,7 +128,7 @@ To migrate from `moor` to `drift`, you may have to update:
The following sections will describe each of the steps.
### New dependencies
#### New dependencies
{% assign versions = 'package:drift_docs/versions.json' | readString | json_decode %}
@ -83,7 +145,7 @@ If you've been using `moor_flutter`, also add a dependency on `drift_sqflite: ^1
Run `pub get` to get the new packages.
### Changing Dart imports
#### Changing Dart imports
This table compares the old imports from `moor` and the new imports for `drift`:
@ -100,7 +162,7 @@ This table compares the old imports from `moor` and the new imports for `drift`:
| `package:moor/sqlite_keywords.dart` | `package:drift/sqlite_keywords.dart` |
| `package:moor_flutter/moor_flutter.dart` | `package:drift_sqflite/drift_sqflite.dart` |
### Changing Dart code
#### Changing Dart code
This table compares old moor-specific API names and new names as provided by `drift`:
@ -118,14 +180,14 @@ This table compares old moor-specific API names and new names as provided by `dr
| `MoorServer` | `DriftServer` |
| `FlutterQueryExecutor` | `SqfliteQueryExecutor` |
### (Optional: Rename moor files)
#### (Optional: Rename moor files)
For consistency, you can rename your `.moor` files to `.drift`.
The drift generator will continue to accept `.moor` files though.
If you opt for a rename, also update your imports and `include:` parameters in database and DAO classes.
### Build configuration
#### Build configuration
When configuring moor builders for [options]({{ 'Advanced Features/builder_options.md' | pageUrl }}), you have to update your `build.yaml` files to reflect the new builder keys:

View File

@ -1,34 +0,0 @@
<!doctype html>
<html lang="{{ site.language }}" class="no-js">
<head>
{% include "partials/head" %}
</head>
<body class="td-{{ kind }}">
<header>
{% include "partials/navbar" %}
</header>
<div class="container-fluid td-outer">
<div class="td-main">
<div class="row flex-xl-nowrap">
<aside class="col-12 col-md-3 col-xl-2 td-sidebar d-print-none">
{% include "partials/sidebar" %}
</aside>
<aside class="d-none d-xl-block col-xl-2 td-sidebar-toc d-print-none">
{% include "partials/toc" %}
</aside>
<main class="col-12 col-md-9 col-xl-8 pl-md-5" role="main">
{% if page.path != '/name' %}
<div class="renamed">
<b>Important notice: </b>Moor has been renamed to Drift.
Learn more <a href="{{ '/name/' | relUrl }}">here</a>.
</div>
{% endif %}
{% include "partials/breadcrumb" %}
{{ main }}
</main>
</div>
</div>
{% include "partials/footer" %}
</div>
</body>
</html>

View File

@ -25,13 +25,6 @@ class DriftOptions {
@JsonKey(name: 'override_hash_and_equals_in_result_sets', defaultValue: false)
final bool overrideHashAndEqualsInResultSets;
/// Also enable the compact query methods from moor files on queries defined
/// in a `UseMoor` annotation. Compact queries return a `Selectable` instead
/// of generating two methods (with one returning a stream and another
/// returning a future)
@JsonKey(name: 'compact_query_methods', defaultValue: true)
final bool compactQueryMethods;
/// Remove verification logic in the generated code.
@JsonKey(name: 'skip_verification_code', defaultValue: false)
final bool skipVerificationCode;
@ -63,9 +56,6 @@ class DriftOptions {
@JsonKey(name: 'sql')
final DialectOptions? dialect;
@JsonKey(name: 'eagerly_load_dart_ast', defaultValue: false)
final bool eagerlyLoadDartAst;
@JsonKey(name: 'data_class_to_companions', defaultValue: true)
final bool dataClassToCompanions;
@ -77,10 +67,10 @@ class DriftOptions {
@JsonKey(name: 'raw_result_set_data', defaultValue: false)
final bool rawResultSetData;
@JsonKey(name: 'apply_converters_on_variables', defaultValue: false)
@JsonKey(name: 'apply_converters_on_variables', defaultValue: true)
final bool applyConvertersOnVariables;
@JsonKey(name: 'generate_values_in_copy_with', defaultValue: false)
@JsonKey(name: 'generate_values_in_copy_with', defaultValue: true)
final bool generateValuesInCopyWith;
@JsonKey(name: 'named_parameters', defaultValue: false)
@ -89,7 +79,7 @@ class DriftOptions {
@JsonKey(name: 'named_parameters_always_required', defaultValue: false)
final bool namedParametersAlwaysRequired;
@JsonKey(name: 'scoped_dart_components', defaultValue: false)
@JsonKey(name: 'scoped_dart_components', defaultValue: true)
final bool scopedDartComponents;
/// Whether `DateTime` columns should be stored as text (via
@ -101,20 +91,18 @@ class DriftOptions {
const DriftOptions.defaults({
this.generateFromJsonStringConstructor = false,
this.overrideHashAndEqualsInResultSets = false,
this.compactQueryMethods = false,
this.skipVerificationCode = false,
this.useDataClassNameForCompanions = false,
this.useColumnNameAsJsonKeyWhenDefinedInMoorFile = false,
this.generateConnectConstructor = false,
this.eagerlyLoadDartAst = false,
this.dataClassToCompanions = true,
this.generateMutableClasses = false,
this.rawResultSetData = false,
this.applyConvertersOnVariables = false,
this.generateValuesInCopyWith = false,
this.applyConvertersOnVariables = true,
this.generateValuesInCopyWith = true,
this.generateNamedParameters = false,
this.namedParametersAlwaysRequired = false,
this.scopedDartComponents = false,
this.scopedDartComponents = true,
this.modules = const [],
this.sqliteAnalysisOptions,
this.storeDateTimeValuesAsText = false,
@ -124,12 +112,10 @@ class DriftOptions {
DriftOptions({
required this.generateFromJsonStringConstructor,
required this.overrideHashAndEqualsInResultSets,
required this.compactQueryMethods,
required this.skipVerificationCode,
required this.useDataClassNameForCompanions,
required this.useColumnNameAsJsonKeyWhenDefinedInMoorFile,
required this.generateConnectConstructor,
required this.eagerlyLoadDartAst,
required this.dataClassToCompanions,
required this.generateMutableClasses,
required this.rawResultSetData,
@ -177,7 +163,10 @@ class DriftOptions {
bool hasModule(SqlModule module) => effectiveModules.contains(module);
/// Checks whether a deprecated option is enabled.
bool get enabledDeprecatedOption => eagerlyLoadDartAst;
///
/// At this time, all deprecated options have been removed, meaning that this
/// getter always returns `false`.
bool get enabledDeprecatedOption => false;
SqlDialect get effectiveDialect => dialect?.dialect ?? SqlDialect.sqlite;

View File

@ -15,7 +15,6 @@ DriftOptions _$DriftOptionsFromJson(Map json) => $checkedCreate(
allowedKeys: const [
'write_from_json_string_constructor',
'override_hash_and_equals_in_result_sets',
'compact_query_methods',
'skip_verification_code',
'use_data_class_name_for_companions',
'use_column_name_as_json_key_when_defined_in_moor_file',
@ -23,7 +22,6 @@ DriftOptions _$DriftOptionsFromJson(Map json) => $checkedCreate(
'sqlite_modules',
'sqlite',
'sql',
'eagerly_load_dart_ast',
'data_class_to_companions',
'mutable_classes',
'raw_result_set_data',
@ -41,8 +39,6 @@ DriftOptions _$DriftOptionsFromJson(Map json) => $checkedCreate(
overrideHashAndEqualsInResultSets: $checkedConvert(
'override_hash_and_equals_in_result_sets',
(v) => v as bool? ?? false),
compactQueryMethods: $checkedConvert(
'compact_query_methods', (v) => v as bool? ?? true),
skipVerificationCode: $checkedConvert(
'skip_verification_code', (v) => v as bool? ?? false),
useDataClassNameForCompanions: $checkedConvert(
@ -52,8 +48,6 @@ DriftOptions _$DriftOptionsFromJson(Map json) => $checkedCreate(
(v) => v as bool? ?? true),
generateConnectConstructor: $checkedConvert(
'generate_connect_constructor', (v) => v as bool? ?? false),
eagerlyLoadDartAst: $checkedConvert(
'eagerly_load_dart_ast', (v) => v as bool? ?? false),
dataClassToCompanions: $checkedConvert(
'data_class_to_companions', (v) => v as bool? ?? true),
generateMutableClasses:
@ -61,15 +55,15 @@ DriftOptions _$DriftOptionsFromJson(Map json) => $checkedCreate(
rawResultSetData: $checkedConvert(
'raw_result_set_data', (v) => v as bool? ?? false),
applyConvertersOnVariables: $checkedConvert(
'apply_converters_on_variables', (v) => v as bool? ?? false),
'apply_converters_on_variables', (v) => v as bool? ?? true),
generateValuesInCopyWith: $checkedConvert(
'generate_values_in_copy_with', (v) => v as bool? ?? false),
'generate_values_in_copy_with', (v) => v as bool? ?? true),
generateNamedParameters:
$checkedConvert('named_parameters', (v) => v as bool? ?? false),
namedParametersAlwaysRequired: $checkedConvert(
'named_parameters_always_required', (v) => v as bool? ?? false),
scopedDartComponents: $checkedConvert(
'scoped_dart_components', (v) => v as bool? ?? false),
'scoped_dart_components', (v) => v as bool? ?? true),
modules: $checkedConvert(
'sqlite_modules',
(v) =>
@ -93,13 +87,11 @@ DriftOptions _$DriftOptionsFromJson(Map json) => $checkedCreate(
'write_from_json_string_constructor',
'overrideHashAndEqualsInResultSets':
'override_hash_and_equals_in_result_sets',
'compactQueryMethods': 'compact_query_methods',
'skipVerificationCode': 'skip_verification_code',
'useDataClassNameForCompanions': 'use_data_class_name_for_companions',
'useColumnNameAsJsonKeyWhenDefinedInMoorFile':
'use_column_name_as_json_key_when_defined_in_moor_file',
'generateConnectConstructor': 'generate_connect_constructor',
'eagerlyLoadDartAst': 'eagerly_load_dart_ast',
'dataClassToCompanions': 'data_class_to_companions',
'generateMutableClasses': 'mutable_classes',
'rawResultSetData': 'raw_result_set_data',
@ -121,7 +113,6 @@ Map<String, dynamic> _$DriftOptionsToJson(DriftOptions instance) =>
instance.generateFromJsonStringConstructor,
'override_hash_and_equals_in_result_sets':
instance.overrideHashAndEqualsInResultSets,
'compact_query_methods': instance.compactQueryMethods,
'skip_verification_code': instance.skipVerificationCode,
'use_data_class_name_for_companions':
instance.useDataClassNameForCompanions,
@ -132,7 +123,6 @@ Map<String, dynamic> _$DriftOptionsToJson(DriftOptions instance) =>
instance.modules.map((e) => _$SqlModuleEnumMap[e]!).toList(),
'sqlite': instance.sqliteAnalysisOptions?.toJson(),
'sql': instance.dialect?.toJson(),
'eagerly_load_dart_ast': instance.eagerlyLoadDartAst,
'data_class_to_companions': instance.dataClassToCompanions,
'mutable_classes': instance.generateMutableClasses,
'raw_result_set_data': instance.rawResultSetData,

View File

@ -4,7 +4,6 @@ import 'package:drift_dev/src/analyzer/sql_queries/explicit_alias_transformer.da
import 'package:drift_dev/src/analyzer/sql_queries/nested_queries.dart';
import 'package:drift_dev/src/utils/string_escaper.dart';
import 'package:drift_dev/writer.dart';
import 'package:recase/recase.dart';
import 'package:sqlparser/sqlparser.dart' hide ResultColumn;
import 'sql_writer.dart';
@ -65,20 +64,9 @@ class QueryWriter {
void _writeSelect(SqlSelectQuery select) {
_writeSelectStatementCreator(select);
if (!select.declaredInMoorFile && !options.compactQueryMethods) {
_writeOneTimeReader(select);
_writeStreamReader(select);
}
}
String _nameOfCreationMethod(SqlSelectQuery select) {
if (!select.declaredInMoorFile && !options.compactQueryMethods) {
return '${select.name}Query';
} else {
return select.name;
}
}
String _nameOfCreationMethod(SqlSelectQuery select) => select.name;
/// Writes the function literal that turns a "QueryRow" into the desired
/// custom return type of a query.
@ -215,41 +203,6 @@ class QueryWriter {
_buffer.write(')');
}
void _writeOneTimeReader(SqlSelectQuery select) {
final returnType =
'Future<List<${select.resultTypeCode(scope.generationOptions)}>>';
_buffer.write('$returnType ${select.name}(');
_writeParameters(select);
_buffer
..write(') {\n')
..write('return ${_nameOfCreationMethod(select)}(');
_writeUseParameters(select);
_buffer.write(').get();\n}\n');
}
void _writeStreamReader(SqlSelectQuery select) {
final upperQueryName = ReCase(select.name).pascalCase;
String methodName;
// turning the query name into pascal case will remove underscores, add the
// "private" modifier back in
if (select.name.startsWith('_')) {
methodName = '_watch$upperQueryName';
} else {
methodName = 'watch$upperQueryName';
}
final returnType =
'Stream<List<${select.resultTypeCode(scope.generationOptions)}>>';
_buffer.write('$returnType $methodName(');
_writeParameters(select);
_buffer
..write(') {\n')
..write('return ${_nameOfCreationMethod(select)}(');
_writeUseParameters(select);
_buffer.write(').watch();\n}\n');
}
void _writeUpdatingQueryWithReturning(UpdatingQuery update) {
final type = update.resultTypeCode(scope.generationOptions);
_buffer.write('Future<List<$type>> ${update.name}(');
@ -428,14 +381,6 @@ class QueryWriter {
}
}
/// Writes code that uses the parameters as declared by [_writeParameters],
/// assuming that for each parameter, a variable with the same name exists
/// in the current scope.
void _writeUseParameters(SqlQuery query) {
final parameters = query.elements.map((e) => e.dartParameterName);
_buffer.write(parameters.join(', '));
}
void _writeExpandedDeclarations(SqlQuery query) {
_ExpandedDeclarationWriter(query, options, _buffer)
.writeExpandedDeclarations();

View File

@ -1,6 +1,6 @@
name: drift_dev
description: Dev-dependency for users of drift. Contains a the generator and development tools.
version: 1.7.0
version: 2.0.0-dev
repository: https://github.com/simolus3/drift
homepage: https://drift.simonbinder.eu/
issue_tracker: https://github.com/simolus3/drift/issues

View File

@ -15,6 +15,12 @@
status = 301
force = true
[[redirects]]
from = "/name"
to = "/docs/upgrading/#name"
status = 301
force = true
[context.production]
environment = { BUILD_RELEASE="release" }