From fb7246654da6ff2c8ffb5eebfe12878c0ea81295 Mon Sep 17 00:00:00 2001 From: Simon Binder Date: Sun, 3 Apr 2022 12:44:02 +0200 Subject: [PATCH] Web documentation for unique Dart columns --- docs/lib/snippets/tables/advanced.dart | 17 +++++++++++++++++ .../Getting started/advanced_dart_tables.md | 17 ++++++++++++++++- 2 files changed, 33 insertions(+), 1 deletion(-) create mode 100644 docs/lib/snippets/tables/advanced.dart diff --git a/docs/lib/snippets/tables/advanced.dart b/docs/lib/snippets/tables/advanced.dart new file mode 100644 index 00000000..7508a47d --- /dev/null +++ b/docs/lib/snippets/tables/advanced.dart @@ -0,0 +1,17 @@ +import 'package:drift/drift.dart'; + +// #docregion unique +class WithUniqueConstraints extends Table { + IntColumn get a => integer().unique()(); + + IntColumn get b => integer()(); + IntColumn get c => integer()(); + + @override + List> get uniqueKeys => [ + {b, c} + ]; + + // Effectively, this table has two unique key sets: (a) and (b, c). +} +// #enddocregion unique diff --git a/docs/pages/docs/Getting started/advanced_dart_tables.md b/docs/pages/docs/Getting started/advanced_dart_tables.md index a68dccc2..d675962d 100644 --- a/docs/pages/docs/Getting started/advanced_dart_tables.md +++ b/docs/pages/docs/Getting started/advanced_dart_tables.md @@ -1,7 +1,7 @@ --- data: title: "Dart tables" - description: Further information on Dart tables + description: Further information on defining tables in Dart. weight: 150 template: layouts/docs/single --- @@ -11,6 +11,8 @@ __Prefer sql?__ If you prefer, you can also declare tables via `CREATE TABLE` st Drift's sql analyzer will generate matching Dart code. [Details]({{ "starting_with_sql.md" | pageUrl }}). {% endblock %} +{% assign snippets = 'package:moor_documentation/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 { @@ -128,6 +130,19 @@ Note that the primary key must essentially be constant so that the generator can - 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 +## Unique Constraints + +Starting from version 1.6.0, `UNIQUE` SQL constraints can be defined on Dart tables too. +A unique constraint contains one or more columns. The combination of all columns in a constraint +must be unique in the table, or the databas will report an error on inserts. + +With drift, a unique constraint can be added to a single column by marking it as `.unique()` in +the column builder. +A unique set spanning multiple columns can be added by overriding the `uniqueKeys` getter in the +`Table` class: + +{% include "blocks/snippet" snippets = snippets name = 'unique' %} + ## Supported column types Drift supports a variety of column types out of the box. You can store custom classes in columns by using