Skip to content
Browse files

Write more documentation about advanced features

  • Loading branch information...
simolus3 committed Aug 2, 2019
1 parent b2a06cb commit a19e3413e821b7aaa7a38fee4d4fbcd3dae43dcb
@@ -56,8 +56,8 @@ anchor = "smart"

title = "Goldydocs"
description = "A Docsy example site"
title = "Moor"
description = "A typesafe persistence library for Dart apps"
languageName ="English"
# Weight used for sorting.
weight = 1
@@ -69,6 +69,15 @@ weight = 1
#time_format_default = "02.01.2006"
#time_format_blog = "02.01.2006"

# Additional menu items to GitHub and pub
name = "Pub"
weight = 100
url = ""
name = "GitHub"
weight = 110
url = ""

# Everything below this are Site Params

@@ -103,34 +112,17 @@ navbar_logo = false
# End user relevant links. These will show up on left side of footer and in the community page if you have one.
name = "User mailing list"
url = ""
name = "Contact me via e-mail"
url = ""
icon = "fa fa-envelope"
desc = "Discussion and help from your fellow users"
name ="Twitter"
url = ""
icon = "fab fa-twitter"
desc = "Follow us on Twitter to get the latest news!"
name = "Contact me via gitter"
url = ""
icon = "fab fa-gitter"
name = "Stack Overflow"
url = ""
icon = "fab fa-stack-overflow"
desc = "Practical questions and curated answers"
# Developer relevant links. These will show up on right side of footer and in the community page if you have one.
name = "GitHub"
url = ""
url = ""
icon = "fab fa-github"
desc = "Development takes place here!"
name = "Slack"
url = ""
icon = "fab fa-slack"
desc = "Chat with other project developers"
name = "Developer mailing list"
url = ""
icon = "fa fa-envelope"
desc = "Discuss development issues around the project"

# could also add another with params.links.developer. They appear on the right

This file was deleted.

@@ -1,4 +1,5 @@
title: "Advanced features"
weight: 20
description: Learn about some advanced features of moor
@@ -1,5 +1,6 @@
title: "Joins"
weight: 1
description: >
Use joins to write queries that read from more than one table
@@ -9,7 +10,7 @@ aliases:
Moor 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]({{< ref "docs/Getting Started/" >}}).
defined in the [example]({{< ref "/docs/Getting Started/" >}}).

// we define a data class to contain both a todo entry and the associated category
@@ -1,5 +1,6 @@
title: "Migrations"
weight: 10
description: >
Define what happens when your database gets created or updated
@@ -0,0 +1,73 @@
title: "Type converters"
description: >
Store more complex data in columns with type converters

Moor supports a variety of types out of the box, but sometimes you need to store more complex data.
You can achieve this by using `TypeConverters`. In this example, we'll use the the
[json_serializable]( package to store a custom object in a
text column. Moor supports any Dart type for which you provide a `TypeConverter`, we're using that
package here to make the example simpler.
import 'dart:convert';
import 'package:json_annotation/json_annotation.dart' as j;
import 'package:moor/moor.dart';
part 'database.g.dart';
class Preferences {
bool receiveEmails;
String selectedTheme;
Preferences(this.receiveEmails, this.selectedTheme);
factory Preferences.fromJson(Map<String, dynamic> json) =>
Map<String, dynamic> toJson() => _$PreferencesToJson(this);

Next, we have to tell moor how to store a `Preferences` object in the database. We write
a `TypeConverter` for that:
// stores preferences as strings
class PreferenceConverter extends TypeConverter<Preferences, String> {
const PreferenceConverter();
Preferences mapToDart(String fromDb) {
if (fromDb == null) {
return null;
return Preferences.fromJson(json.decode(fromDb) as Map<String, dynamic>);
String mapToSql(Preferences value) {
if (value == null) {
return null;
return json.encode(value.toJson());

Finally, we can use that converter in a table declaration:
class Users extends Table {
IntColumn get id => integer().autoIncrement()();
TextColumn get name => text()();
TextColumn get preferences =>
text().map(const PreferenceConverter()).nullable()();

The generated `User` class will then have a `preferences` column of type
`Preferences`. Moor will automatically take care of storing and loading
the object in `select`, `update` and `insert` statements. This feature
also works with [compiled custom queries]({{ "/queries/custom" | absolute_url }}).

This file was deleted.

@@ -0,0 +1,10 @@
title: "Using SQL"
weight: 30
description: Write typesafe sql with moor

Moor let's you express a variety of queries in pure Dart. However, you don't have to miss out
on its features when you need more complex queries or simply prefer sql. Moor has a builtin
sql parser and analyzer, so it can generate a typesafe API for sql statements you write.
It can also warn about errors in your sql at build time.
@@ -0,0 +1,87 @@
title: "Custom queries"
weight: 10
description: Let moor generate Dart from your SQL statements
- /queries/custom

Altough moor includes a fluent api that can be used to model most statements, advanced
features like `GROUP BY` statements or window functions are not yet supported. You can
use these features with custom statements. You don't have to miss out on other benefits
moor brings, though: Moor helps you parse the result rows and qustom queries also
support auto-updating streams.

## Statements with a generated api
Starting from version `1.5`, you can instruct moor to automatically generate a typesafe
API for your select, update and delete statements. Of course, you can still write custom
sql manually. See the sections below for details.

To use this feature, all you need to is define your queries in your `UseMoor` annotation:
tables: [Todos, Categories],
queries: {
'SELECT *, (SELECT COUNT(*) FROM todos WHERE category = AS "amount" FROM categories c;'
class MyDatabase extends _$MyDatabase {
// rest of class stays the same
After running the build step again, moor will have written the `CategoriesWithCountResult` class for you -
it will hold the result of your query. Also, the `_$MyDatabase` class from which you inherit will have the
methods `categoriesWithCount` (which runs the query once) and `watchCategoriesWithCount` (which returns
an auto-updating stream).

Queries can have parameters in them by using the `?` or `:name` syntax. When your queries contains parameters,
moor will figure out an appropriate type for them and include them in the generated methods. For instance,
`'categoryById': 'SELECT * FROM categories WHERE id = :id'` will generate the method `categoryById(int id)`.

You can also use `UPDATE` or `DELETE` statements here. Of course, this feature is also available for
[daos]({{< ref "/docs/Advanced features/" >}}),
and it perfectly integrates with auto-updating streams by analyzing what tables you're reading from or
writing to.

## Custom select statements
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]({{< ref "/docs/Getting started/" >}}), we can
write this query which will load the amount of todo entries in each category:
class CategoryWithCount {
final Category category;
final int count; // amount of entries in this category
CategoryWithCount(this.category, this.count);
// then, in the database class:
Stream<List<CategoryWithCount>> categoriesWithCount() {
// select all categories and load how many associated entries there are for
// each category
return customSelectStream(
'SELECT *, (SELECT COUNT(*) FROM todos WHERE category = AS "amount" FROM categories c;',
readsFrom: {todos, categories}, // used for the stream: the stream will update when either table changes
).map((rows) {
// we get list of rows here. We just have to turn the raw data from the row into a
// CategoryWithCount. As we defined the Category table earlier, moor knows how to parse
// a category. The only thing left to do manually is extracting the amount
return rows
.map((row) => CategoryWithCount(Category.fromData(, this), row.readInt('amount')))
For custom selects, you should use the `readsFrom` parameter to specify from which tables the query is
reading. When using a `Stream`, moor will be able to know after which updates the stream should emit

## Custom update statements
For update and delete statements, you can use `customUpdate`. Just like `customSelect`, that method
also takes a sql statement and optional variables. You can also tell moor which tables will be
affected by your query using the optional `updates` parameter. That will help with other select
streams, which will then update automatically.
@@ -0,0 +1,42 @@
title: "Tables from SQL"
weight: 20
description: Generate tables from `CREATE TABLE` statements.

{{% alert title="Experimental feature" %}}
At the moment, creating table classes from `CREATE TABLE` statements is an experimental feature.
If you run into any issues, please create an issue and let us know, thanks!
{{% /alert %}}

With moor, you can specify your table classes in Dart and it will generate matching
`CREATE TABLE` statements for you. But if you prefer to write `CREATE TABLE` statements and have
moor generating fitting Dart classes, that works too.

To use this feature, create a (or multiple) `.moor` file somewhere in your project. You can fill
them with create table statements:
CREATE TABLE experiments (
description TEXT NOT NULL,

Then, import these tables to your database with:
@UseMoor(include: {'experiments.moor'})
class ExperimentsDb extends _$ExperimentsDb {

All the tables will then be available inside your database class, just like they
would be if you wrote them in Dart. If you want to use this feature on an DAO,
you'll also need to `include` the .moor file on that class. Moor supports both
relative imports (like above) and absolute imports (like `package:your_app/src/tables/experiments.moor`)
Of course, this feature works perfectly together with features like generated
custom queries and query-streams.

0 comments on commit a19e341

Please sign in to comment.
You can’t perform that action at this time.