Delete old getting started guide

This commit is contained in:
Simon Binder 2023-09-16 18:54:40 +02:00
parent 2403da5b98
commit 10725d98fb
No known key found for this signature in database
GPG Key ID: 7891917E4147B8C0
23 changed files with 120 additions and 220 deletions

View File

@ -76,5 +76,9 @@ class TableWithCustomConstraints extends Table {
// #enddocregion custom-constraint-table
// #docregion index
class Users extends Table {}
// #enddocregion index
@TableIndex(name: 'user_name', columns: {#name})
class Users extends Table {
IntColumn get id => integer().autoIncrement()();
TextColumn get name => text()();
}
// #enddocregion index

View File

@ -0,0 +1,33 @@
import 'package:drift/drift.dart';
class Todos extends Table {
IntColumn get id => integer().autoIncrement()();
TextColumn get title => text().withLength(min: 6, max: 32)();
TextColumn get content => text().named('body')();
IntColumn get category => integer().nullable()();
}
@DataClassName('Category')
class Categories extends Table {
IntColumn get id => integer().autoIncrement()();
TextColumn get description => text()();
}
// #docregion view
abstract class CategoryTodoCount extends View {
// Getters define the tables that this view is reading from.
Todos get todos;
Categories get categories;
// Custom expressions can be given a name by defining them as a getter:.
Expression<int> get itemCount => todos.id.count();
@override
Query as() =>
// Views can select columns defined as expression getters on the class, or
// they can reference columns from other tables.
select([categories.description, itemCount])
.from(categories)
.join([innerJoin(todos, todos.category.equalsExp(categories.id))]);
}
// #enddocregion view

View File

@ -71,7 +71,7 @@ At the moment, drift supports these options:
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.
For more information on these modes, see [datetime options]({{ '../Getting started/advanced_dart_tables#datetime-options' | pageUrl }}).
For more information on these modes, see [datetime options]({{ '../Dart API/tables.md#datetime-options' | pageUrl }}).
* `case_from_dart_to_sql` (defaults to `snake_case`): Controls how the table and column names are re-cased from the Dart identifiers.
The possible values are `preserve`, `camelCase`, `CONSTANT_CASE`, `snake_case`, `PascalCase`, `lowercase` and `UPPERCASE` (default: `snake_case`).
* `write_to_columns_mixins`: Whether the `toColumns` method should be written as a mixin instead of being added directly to the data class.

View File

@ -155,7 +155,7 @@ __Note__: We're using `selectOnly` instead of `select` because we're not interes
### Counting
Sometimes, it's useful to count how many rows are present in a group. By using the
[table layout from the example]({{ "../Getting started/index.md" | pageUrl }}), this
[table layout from the example]({{ "../setup.md" | pageUrl }}), this
query will report how many todo entries are associated to each category:
```dart

View File

@ -10,7 +10,7 @@ As sqlite3 is a synchronous C library, accessing the database from the main isol
can cause blocking IO operations that lead to reduced responsiveness of your
application.
To resolve this problem, drift can spawn a long-running isolate to run SQL statements.
When following the recommended [getting started guide]({{ '../Getting started/index.md' | pageUrl }})
When following the recommended [getting started guide]({{ '../setup.md' | pageUrl }})
and using `NativeDatabase.createInBackground`, you automatically benefit from an isolate
drift manages for you without needing additional setup.
This page describes when advanced isolate setups are necessary, and how to approach them.

View File

@ -15,7 +15,7 @@ template: layouts/docs/single
Drift supports sql joins to write queries that operate on more than one table. To use that feature, start
a select regular select statement with `select(table)` and then add a list of joins using `.join()`. For
inner and left outer joins, a `ON` expression needs to be specified. Here's an example using the tables
defined in the [example]({{ "../Getting started/index.md" | pageUrl }}).
defined in the [example]({{ "../setup.md" | pageUrl }}).
{% include "blocks/snippet" snippets = snippets name = 'joinIntro' %}

View File

@ -15,7 +15,7 @@ to access tables reflectively. Luckily, code generated by drift implements inter
Since this is a topic that most drift users will not need, this page mostly gives motivating examples and links to the documentation for relevant
drift classes.
For instance, you might have multiple independent tables that have an `id` column. And you might want to filter rows by their `id` column.
When writing this query against a single table, like the `Todos` table as seen in the [getting started]({{'../Getting started/index.md' | pageUrl }}) page,
When writing this query against a single table, like the `Todos` table as seen in the [getting started]({{'../setup.md' | pageUrl }}) page,
that's pretty straightforward:
{% include "blocks/snippet" snippets = snippets name = 'findTodoEntryById' %}

View File

@ -373,4 +373,14 @@ on columns, you can add those by overriding `customConstraints`:
{% include "blocks/snippet" snippets = snippets name="custom-constraint-table" %}
## Index
## Index
An [index](https://sqlite.org/lang_createindex.html) on columns in a table allows rows identified
by these columns to be identified more easily.
In drift, you can apply an index to a table with the `@TableIndex` annotation. More than one
index can be applied to the same table by repeating the annotation:
{% include "blocks/snippet" snippets = snippets name="index" %}
Each index needs to have its own unique name. Typically, the name of the table is part of the
index' name to ensure unique names.

View File

@ -4,3 +4,49 @@ data:
description: How to define SQL views as Dart classes
template: layouts/docs/single
---
It is also possible to define [SQL views](https://www.sqlite.org/lang_createview.html)
as Dart classes.
To do so, write an abstract class extending `View`. This example declares a view reading
the amount of todo-items added to a category in the schema from [the example]({{ 'index.md' | pageUrl }}):
{% assign snippets = 'package:drift_docs/snippets/dart_api/views.dart.excerpt.json' | readString | json_decode %}
{% include "blocks/snippet" snippets = snippets name = 'view' %}
Inside a Dart view, use
- abstract getters to declare tables that you'll read from (e.g. `TodosTable get todos`).
- `Expression` getters to add columns: (e.g. `itemCount => todos.id.count()`).
- the overridden `as` method to define the select statement backing the view.
The columns referenced in `select` may refer to two kinds of columns:
- Columns defined on the view itself (like `itemCount` in the example above).
- Columns defined on referenced tables (like `categories.description` in the example).
For these references, advanced drift features like [type converters]({{ '../Advanced Features/type_converters.md' | pageUrl }})
used in the column's definition from the table are also applied to the view's column.
Both kind of columns will be added to the data class for the view when selected.
Finally, a view needs to be added to a database or accessor by including it in the
`views` parameter:
```dart
@DriftDatabase(tables: [Todos, Categories], views: [CategoryTodoCount])
class MyDatabase extends _$MyDatabase {
```
### Nullability of columns in a view
For a Dart-defined views, expressions defined as an `Expression` getter are
_always_ nullable. This behavior matches `TypedResult.read`, the method used to
read results from a complex select statement with custom columns.
Columns that reference another table's column are nullable if the referenced
column is nullable, or if the selected table does not come from an inner join
(because the whole table could be `null` in that case).
Considering the view from the example above,
- the `itemCount` column is nullable because it is defined as a complex
`Expression`
- the `description` column, referencing `categories.description`, is non-nullable.
This is because it references `categories`, the primary table of the view's
select statement.

View File

@ -16,7 +16,7 @@ queries in drift. First, we need to store some items that can be bought:
We're going to define two tables for shopping carts: One for the cart
itself, and another one to store the entries in the cart.
The latter uses [references]({{ '../Getting started/advanced_dart_tables.md#references' | pageUrl }})
The latter uses [references]({{ '../Dart API/tables.md#references' | pageUrl }})
to express the foreign key constraints of referencing existing shopping
carts or product items.

View File

@ -1,97 +0,0 @@
---
data:
title: "Dart tables"
description: "Further information on defining tables in Dart. This page describes advanced features like constraints, nullability, references and views"
weight: 150
path: /old-tables
template: layouts/docs/single
---
{% block "blocks/pageinfo" %}
__Prefer sql?__ If you prefer, you can also declare tables via `CREATE TABLE` statements.
Drift's sql analyzer will generate matching Dart code. [Details]({{ "starting_with_sql.md" | pageUrl }}).
{% endblock %}
{% assign snippets = 'package:drift_docs/snippets/tables/advanced.dart.excerpt.json' | readString | json_decode %}
As shown in the [getting started guide]({{ "index.md" | pageUrl }}), sql tables can be written in Dart:
```dart
class Todos extends Table {
IntColumn get id => integer().autoIncrement()();
TextColumn get title => text().withLength(min: 6, max: 32)();
TextColumn get content => text().named('body')();
IntColumn get category => integer().nullable()();
}
```
In this article, we'll cover some advanced features of this syntax.
## Primary keys
If your table has an `IntColumn` with an `autoIncrement()` constraint, drift recognizes that as the default
primary key. If you want to specify a custom primary key for your table, you can override the `primaryKey`
getter in your table:
```dart
class GroupMemberships extends Table {
IntColumn get group => integer()();
IntColumn get user => integer()();
@override
Set<Column> get primaryKey => {group, user};
}
```
Note that the primary key must essentially be constant so that the generator can recognize it. That means:
- it must be defined with the `=>` syntax, function bodies aren't supported
- it must return a set literal without collection elements like `if`, `for` or spread operators
## Views
It is also possible to define [SQL views](https://www.sqlite.org/lang_createview.html)
as Dart classes.
To do so, write an abstract class extending `View`. This example declares a view reading
the amount of todo-items added to a category in the schema from [the example]({{ 'index.md' | pageUrl }}):
{% include "blocks/snippet" snippets = snippets name = 'view' %}
Inside a Dart view, use
- abstract getters to declare tables that you'll read from (e.g. `TodosTable get todos`).
- `Expression` getters to add columns: (e.g. `itemCount => todos.id.count()`).
- the overridden `as` method to define the select statement backing the view.
The columns referenced in `select` may refer to two kinds of columns:
- Columns defined on the view itself (like `itemCount` in the example above).
- Columns defined on referenced tables (like `categories.description` in the example).
For these references, advanced drift features like [type converters]({{ '../Advanced Features/type_converters.md' | pageUrl }})
used in the column's definition from the table are also applied to the view's column.
Both kind of columns will be added to the data class for the view when selected.
Finally, a view needs to be added to a database or accessor by including it in the
`views` parameter:
```dart
@DriftDatabase(tables: [Todos, Categories], views: [CategoryTodoCount])
class MyDatabase extends _$MyDatabase {
```
### Nullability of columns in a view
For a Dart-defined views, expressions defined as an `Expression` getter are
_always_ nullable. This behavior matches `TypedResult.read`, the method used to
read results from a complex select statement with custom columns.
Columns that reference another table's column are nullable if the referenced
column is nullable, or if the selected table does not come from an inner join
(because the whole table could be `null` in that case).
Considering the view from the example above,
- the `itemCount` column is nullable because it is defined as a complex
`Expression`
- the `description` column, referencing `categories.description`, is non-nullable.
This is because it references `categories`, the primary table of the view's
select statement.

View File

@ -1,102 +0,0 @@
---
data:
title: Getting started
description: Simple guide to get a drift project up and running.
weight: 1
hide_section_index: true
path: /docs/getting-started-old
template: layouts/docs/list
aliases:
- /getting-started-old/ # Used to have this url
---
In addition to this document, other resources on how to use drift also exist.
For instance, [this playlist](https://www.youtube.com/watch?v=8ESbEFC0z5Y&list=PLztm2TugcV9Tn6J_H5mtxYIBN40uMAZgO)
or [this older video by Reso Coder](https://www.youtube.com/watch?v=zpWsedYMczM&t=281s) might be for you
if you prefer a tutorial video.
If you want to look at an example app instead, a cross-platform Flutter app using drift is available
[as part of the drift repository](https://github.com/simolus3/drift/tree/develop/examples/app).
## Project setup
{% include "partials/dependencies" %}
{% assign snippets = 'package:drift_docs/snippets/tables/filename.dart.excerpt.json' | readString | json_decode %}
### Declaring tables
Using drift, you can model the structure of your tables with simple dart code.
Let's write a file (simply called `filename.dart` in this snippet) containing
two simple tables and a database class using drift to get started:
{% include "blocks/snippet" snippets = snippets name = "overview" %}
__⚠ Note:__ The column definitions, the table name and the primary key must be known at
compile time. For column definitions and the primary key, the function must use the `=>`
operator and can't contain anything more than what's included in the documentation and the
examples. Otherwise, the generator won't be able to know what's going on.
## Generating the code
Drift integrates with Dart's `build` system, so you can generate all the code needed with
`dart run build_runner build`. If you want to continuously rebuild the generated code
where you change your code, run `dart run build_runner watch` instead.
After running either command, drift's generator will have created the following classes for
you:
1. The `_$MyDatabase` class that your database is defined to extend. It provides access to all
tables and core drift APIs.
2. A data class, `Todo` (for `Todos`) and `Category` (for `Categories`) for each table. It is
used to hold the result of selecting rows from the table.
3. A class which drift calls a "companion" class (`TodosCompanion` and `CategoriesCompanion`
in this example here).
These classes are used to write inserts and updates into the table. These classes make drift
a great match for Dart's null safety feature: In a data class, columns (including those using
auto-incremented integers) can be non-nullable since they're coming from a select.
Since you don't know the value before running an insert though, the companion class makes these
columns optional.
With the generated code in place, the database can be opened by passing a connection to the superclass,
like this:
{% include "blocks/snippet" snippets = snippets name = "open" %}
That's it! You can now use drift by creating an instance of `MyDatabase`.
In a simple app from a `main` entrypoint, this may look like the following:
{% include "blocks/snippet" snippets = snippets name = "usage" %}
The articles linked below explain how to use the database in actual, complete
Flutter apps.
A complete example for a Flutter app using drift is also available [here](https://github.com/simolus3/drift/tree/develop/examples/app).
## Next steps
Congratulations! You're now ready to use all of drift. See the articles below for further reading.
The ["Writing queries"]({{ "writing_queries.md" | pageUrl }}) article contains everything you need
to know to write selects, updates and inserts in drift!
{% block "blocks/alert" title="Using the database" %}
The database class from this guide is ready to be used with your app.
For Flutter apps, a Drift database class is typically instantiated at the top of your widget tree
and then passed down with `provider` or `riverpod`.
See [using the database]({{ '../faq.md#using-the-database' | pageUrl }}) for ideas on how to integrate
Drift into your app's state management.
The setup in this guide uses [platform channels](https://flutter.dev/docs/development/platform-integration/platform-channels),
which are only available after running `runApp` by default.
When using drift before your app is initialized, please call `WidgetsFlutterBinding.ensureInitialized()` before using
the database to ensure that platform channels are ready.
{% endblock %}
- The articles on [writing queries]({{ 'writing_queries.md' | pageUrl }}) and [Dart tables]({{ 'advanced_dart_tables.md' | pageUrl }}) introduce important concepts of the Dart API used to write queries.
- You can use the same drift database on multiple isolates concurrently - see [Isolates]({{ '../Advanced Features/isolates.md' | pageUrl }}) for more on that.
- Drift has excellent support for custom SQL statements, including a static analyzer and code-generation tools. See [Getting started with sql]({{ 'starting_with_sql.md' | pageUrl }})
or [Using SQL]({{ '../Using SQL/index.md' | pageUrl }}) for everything there is to know about using drift's SQL-based APIs.
- Something to keep in mind for later: When you change the schema of your database and write migrations, drift can help you make sure they're
correct. Use [runtime checks], which don't require additional setup, or more involved [test utilities] if you want to test migrations between
any schema versions.
[runtime checks]: {{ '../Advanced Features/migrations.md#verifying-a-database-schema-at-runtime' | pageUrl }}
[test utilities]: {{ '../Advanced Features/migrations.md#verifying-migrations' | pageUrl }}

View File

@ -6,7 +6,7 @@ data:
template: layouts/docs/single
---
The regular [getting started guide]({{ "index.md" | pageUrl }}) explains how to get started with drift by
The regular [getting started guide]({{ "../setup.md" | pageUrl }}) explains how to get started with drift by
declaring both tables and queries in Dart. This version will focus on how to use drift with SQL instead.
A complete cross-platform Flutter app using drift is also available [here](https://github.com/simolus3/drift/tree/develop/examples/app).

View File

@ -10,7 +10,7 @@ template: layouts/docs/single
---
{% block "blocks/pageinfo" %}
__Note__: This assumes that you've already completed [the setup]({{ "index.md" | pageUrl }}).
__Note__: This assumes that you've already completed [the setup]({{ "../setup.md" | pageUrl }}).
{% endblock %}
For each table you've specified in the `@DriftDatabase` annotation on your database class,
@ -297,7 +297,7 @@ generated.
__Note:__ This uses the `RETURNING` syntax added in sqlite3 version 3.35, which is not available on most operating systems by default. When using this method, make sure that you have a recent sqlite3 version available. This is the case with `sqlite3_flutter_libs`.
For instance, consider this snippet using the tables from the [getting started guide]({{ 'index.md' | pageUrl }}):
For instance, consider this snippet using the tables from the [getting started guide]({{ '../setup.md' | pageUrl }}):
```dart
final row = await into(todos).insertReturning(TodosCompanion.insert(

View File

@ -128,7 +128,7 @@ to another (potentially slower) implementation in that case.
### Setup in Dart
From a perspective of the Dart code used, drift on the web is similar to drift on other platforms.
You can follow the [getting started guide]({{ '../Getting started/index.md' | pageUrl }}) as a general setup guide.
You can follow the [getting started guide]({{ '../setup.md' | pageUrl }}) as a general setup guide.
Instead of using a `NativeDatabase` in your database classes, you can use the `WasmDatabase` optimized for
the web:

View File

@ -72,7 +72,7 @@ If you don't want to use the statements with an generated api, you can
still send custom queries by calling `customSelect` for a one-time query or
`customSelectStream` for a query stream that automatically emits a new set of items when
the underlying data changes. Using the todo example introduced in the
[getting started guide]({{ "../Getting started/index.md" | pageUrl }}), we can
[getting started guide]({{ "../setup.md" | pageUrl }}), we can
write this query which will load the amount of todo entries in each category:
{% include "blocks/snippet" snippets = snippets name = "manual" %}

View File

@ -143,7 +143,7 @@ Instead of using an integer mapping enums by their index, you can also store the
by their name. For this, use `ENUMNAME(...)` instead of `ENUM(...)`.
For details on all supported types, and information on how to switch between the
datetime modes, see [this section]({{ '../Getting started/advanced_dart_tables.md#supported-column-types' | pageUrl }}).
datetime modes, see [this section]({{ '../Dart API/tables.md#supported-column-types' | pageUrl }}).
The additional drift-specific types (`BOOLEAN`, `DATETIME`, `ENUM` and `ENUMNAME`) are also supported in `CAST`
expressions, which is helpful for views:

View File

@ -7,7 +7,7 @@ template: layouts/docs/single
---
## Using the database
If you've created a `MyDatabase` class by following the [getting started guide]({{ "Getting started/index.md" | pageUrl }}), you
If you've created a `MyDatabase` class by following the [getting started guide]({{ "setup.md" | pageUrl }}), you
still need to somehow obtain an instance of it. It's recommended to only have one (singleton) instance of your database,
so you could store that instance in a global variable:

View File

@ -11,7 +11,7 @@ Drift is a reactive persistence library for Dart and Flutter applications. It's
of database libraries like [the sqlite3 package](https://pub.dev/packages/sqlite3), [sqflite](https://pub.dev/packages/sqflite) or [sql.js](https://github.com/sql-js/sql.js/)
and provides additional features, like:
- __Type safety__: Instead of writing sql queries manually and parsing the `List<Map<String, dynamic>>` that they
- __Type safety__: Instead of writing sql queries manually and parsing the `List<Map<String, dynamic>>` that they
return, drift turns rows into objects of your choice.
- __Stream queries__: Drift lets you "watch" your queries with zero additional effort. Any query can be turned into
an auto-updating stream that emits new items when the underlying data changes.

View File

@ -47,7 +47,7 @@ is maintaned and supported too.
### using `drift/native`
The new `package:drift/native.dart` implementation uses `dart:ffi` to bind to sqlite3's native C apis.
This is the recommended approach for newer projects as described in the [getting started]({{ "Getting started/index.md" | pageUrl }}) guide.
This is the recommended approach for newer projects as described in the [getting started]({{ "setup.md" | pageUrl }}) guide.
To ensure that your app ships with the latest sqlite3 version, also add a dependency to the `sqlite3_flutter_libs`
package when using `package:drift/native.dart`!

View File

@ -113,8 +113,14 @@ started with drift:
- Writing queries: Drift-generated classes support writing the most common SQL statements, like
[selects]({{ 'Dart API/select.md' | pageUrl }}) or [inserts, updates and deletes]({{ 'Dart API/writes.md' | pageUrl }}).
- General [notes on how to integrate drift with your app's architecture]({{ 'Dart API/architecture.md' | pageUrl }}).
- Something to keep in mind for later: When you change the schema of your database and write migrations, drift can help you make sure they're
correct. Use [runtime checks], which don't require additional setup, or more involved [test utilities] if you want to test migrations between
any schema versions.
Once you're familiar with the basics, the [overview here]({{ 'index.md' | pageUrl }}) shows what
more drift has to offer.
This includes transactions, automated tooling to help with migrations, multi-platform support
and more.
[runtime checks]: {{ 'Advanced Features/migrations.md#verifying-a-database-schema-at-runtime' | pageUrl }}
[test utilities]: {{ 'Advanced Features/migrations.md#verifying-migrations' | pageUrl }}

View File

@ -14,7 +14,7 @@ data:
Write type-safe queries in Dart or SQL, enjoy auto-updating streams, easily managed transactions
and so much more to make persistence fun.
</p>
<a class="btn btn-lg btn-secondary mr-3 mb-4" href="{{ 'docs/Getting started/index.md' | pageUrl }}">
<a class="btn btn-lg btn-secondary mr-3 mb-4" href="{{ 'docs/setup.md' | pageUrl }}">
Get started <i class="fas fa-code ml-2 "></i>
</a>
</div>
@ -28,7 +28,7 @@ With drift, you can declare your database tables and queries in pure Dart withou
advanced SQL features. Drift will take care of creating the tables and generate code
that allows you run fluent queries on your data.
[Get started now]({{ "docs/Getting started/index.md" | pageUrl }})
[Get started now]({{ "docs/setup.md" | pageUrl }})
{% endblock %}
{% endblock %}

View File

@ -109,7 +109,7 @@ _Please not that the package is still in preview_
{% block "blocks/section" color="dark" type="section" %} {% block "blocks/markdown" %}
## Try moor now
- To get started with moor, follow our [getting started guide]({{ "docs/Getting started/index.md" | pageUrl }}) here.
- To get started with moor, follow our [getting started guide]({{ "docs/setup.md" | pageUrl }}) here.
- To get started with SQL in moor, or to migrate an existing project to moor, follow our
[migration guide]({{ "docs/Getting started/starting_with_sql.md" | pageUrl }})