---
title: Models & Code Generation
description: >-
  Annotate plain Dart classes with @Collection and let cocoon_generator write
  the adapter, typed query handles and canonical codec.
---
> ## Documentation Index
> Fetch the complete documentation index at: https://docs.page/redfieldchristabel/butterfly/llms.txt
> Use this file to discover all available pages before exploring further.

In Cocoon, your model class **is** the schema. Annotate plain Dart classes
and `cocoon_generator` (build_runner) generates the `CollectionAdapter`, the
typed query handles and the canonical protobuf codec for each. Field numbers
come from the committed `cocoon.lock`, never from field order — see
[Schema Migrations](/libraries/cocoon/migrations).

## The annotations

All annotations come from `package:cocoon/cocoon.dart`:

<Property
  name="@Collection(path, indexes: [])"
  type="class annotation"
>
  Marks a class as a collection model. `path` is the collection pattern —
  collection ids separated by `{param}` placeholders, e.g. `accounts` or
  `accounts/{accountId}/txns`. `indexes` declares indexes the same way the
  stacked `@Index` lines do — handy for a shared `const` list — and both
  together are one declaration space.
</Property>

<Property
  name="@Index(fields, unique: false)"
  type="class annotation"
>
  One index, stacked above the model's class declaration. Field (or path
  param) names in sort order; a `-` prefix sorts that part descending. The
  document id is always appended as the final tiebreaker so keyset pagination
  stays stable. `unique: true` creates a `UNIQUE` index. Dart allows the same
  annotation repeated — every `@Index` line on the class is read, in source
  order. For an index over ONE field prefer `@Indexed()` on the field itself;
  use `@Index` for composites (two or more parts) and for indexes over path
  params. Only valid on a `@Collection` class; anywhere else is a build error
  naming the class.
</Property>

<Property
  name="@Indexed(descending: false, unique: false)"
  type="field/getter annotation"
>
  Indexes a single field: it declares exactly `Index(['field'])` (or
  `Index(['-field'])` with `descending: true`, `Index(['field'],`
  `unique: true)` with `unique: true`) as if it were written in
  `@Collection(indexes: [...])` or stacked above the class. The generator
  merges field-level and class-level declarations into one list — an index
  declared in any mix of the three forms is one index — and the physical
  index name comes from the canonical form, so moving an index between
  `indexes:`, a stacked `@Index` and `@Indexed()` on the field changes
  nothing: no schema version bump, no rebuild, no lock change.
  Allowed on the same types an index field allows (`int`, `double`, `bool`,
  `String`, `DateTime`, `Uint8List`, enums); a list, a map or an embedded
  class is a build error, and so is the annotation inside an `@Embedded`
  class (embedded fields have no column). Not for path params — they are not
  fields and stay on the class. A field that is both `@Mirrored()` and
  `@Indexed()` is just indexed: one column, one index.
</Property>

<Property
  name="@Mirrored()"
  type="field/getter annotation"
>
  Copies the field into its own typed `f_` column **without creating an
  index**, so aggregates (`sum`, `average`, `minOf`, `maxOf`) and `groupBy`
  can read it while `where`/`orderBy` stay index-only. Same column type,
  nullability and CHECK as an index field; allowed on exactly the types an
  index field allows. A field that is both mirrored and indexed is just
  indexed — one column, one index. Adding the annotation to an existing
  collection adds and backfills the column on the next open; removing it
  drops the column. Use it for fields you total or group by but never
  filter or sort on. See [Aggregates & Group By](/libraries/cocoon/aggregates)
  for the query-side rules and the measured storage cost.
</Property>

<Property name="@Embedded()" type="class annotation">
  Marks a class as embeddable: it is stored inline inside a collection
  model's document, encoded as a nested protobuf message. Embedded classes
  follow the same constructor and type rules as models, and their field
  numbers are pinned in the lock under their type name.
</Property>

<Property name="@Ignore()" type="field/getter annotation">
  Excludes a field from storage; it is neither encoded nor tracked by the
  lock.
</Property>

## An example

```dart title="lib/models.dart"
import 'dart:typed_data';

import 'package:cocoon/cocoon.dart';

part 'models.cocoon.dart';

@Embedded()
class Address {
  const Address({required this.city, required this.postCode, this.line2});
  final String city;
  final String postCode;
  final String? line2;
}

enum TxnStatus { pending, posted, failed }

@Collection('accounts', indexes: [Index(['name'])])
class Account {
  const Account({
    required this.name,
    required this.openedAt,
    required this.balanceMinor, // minor units; may be negative
    required this.active,
    this.tags = const [],
    this.address,
    this.avatar,
  });
  final String name;
  final DateTime openedAt;
  final int balanceMinor;
  final bool active;
  final List<String> tags;
  final Address? address;
  final Uint8List? avatar;
}

@Collection('accounts/{accountId}/txns')
@Index(['accountId', '-bookedOn'])
@Index(['status', 'bookedOn'])
class Txn {
  const Txn({
    required this.bookedOn, // yyyymmdd
    required this.amountMinor, // minor units; may be negative
    required this.currency,
    required this.status,
    required this.createdAt,
    this.memo,
    this.meta = const {},
  });
  final int bookedOn;
  final int amountMinor;
  @Indexed() // same as Index(['currency']) anywhere on Txn
  final String currency;
  final TxnStatus status;
  final DateTime createdAt;
  final String? memo;

  /// Free-form tags from the importing bank, e.g. category ids.
  final Map<String, String> meta;

  // Methods are never stored; helpers like copyWith are yours to write.
  Txn copyWith({TxnStatus? status}) => Txn(
    bookedOn: bookedOn,
    amountMinor: amountMinor,
    currency: currency,
    status: status ?? this.status,
    createdAt: createdAt,
    memo: memo,
  );
}
```

Declare the part file the generator writes (`part 'models.cocoon.dart';`,
exactly as above), point build_runner at the lock, and run it:

```yaml title="build.yaml"
targets:
  $default:
    sources:
      - lib/**
      - cocoon.lock
      - $package$
```

```bash
dart run build_runner build -d
```

## What the generator emits

Per `@Collection` model:

- an adapter instance named after the last collection id, plus its
  `CollectionAdapter` class: `accounts` (`AccountCollection`), `txns`
  (`TxnCollection`);
- typed query handles on a `$` holder class, one `static final
  FieldColumn` per indexed field and path param: `Txn$.bookedOn`,
  `Txn$.accountId`;
- the canonical `encode`/`decode` codec (protobuf wire format).

Additionally, `lib/cocoon_schema.g.dart` carries the package's
`const cocoonSchemaVersion` — hand it to `Cocoon.open` as shown in
[Schema Migrations](/libraries/cocoon/migrations).

```dart
final db = await Cocoon.open(file, collections: [accounts, txns]);
final recent = await db.collection(accounts).doc('a1').collection(txns)
    .orderBy(Txn$.bookedOn, descending: true)
    .limit(50)
    .get();
```

<Info>
  The generated `*.cocoon.dart` and `lib/cocoon_schema.g.dart` files are
  build outputs, not committed source. `cocoon.lock` **is** committed —
  it is the source of truth for field numbers.
</Info>

## Rules the generator enforces

Build errors say exactly what to fix:

- One generative constructor whose parameters are named like the stored
  fields (named or positional). Stored fields are final instance fields not
  marked `@Ignore()`; getters are not stored. No generic models, no abstract
  models, no super parameters.
- Supported field types: `int`, `double`, `bool`, `String`, `DateTime` (UTC
  microseconds), `Uint8List`, enums (stored by name), `List<T>` of those
  (elements may not be nullable), `@Embedded()` classes — any of them
  nullable except list elements — and `Map<K, V>` where `K` is `String` or
  `int` and `V` is any supported non-Map type. Map values may not be
  nullable or Maps; encode the absence of a value by omitting its entry.
  Maps are stored like protobuf's map type: one nested message per entry,
  key at field 1, value at field 2, entries written sorted by key, so equal
  maps always encode to equal bytes.
- A field missing from an older document decodes to the constructor default,
  else `null` when nullable, else the zero value (`0`, `''`, `false`, empty
  list, empty map, epoch UTC, first enum value).
- Maps cannot be indexed: an `Index([...])` naming a map field is a build
  error.
- `@Indexed()` is allowed on exactly the types an index field allows (`int`,
  `double`, `bool`, `String`, `DateTime`, `Uint8List`, enums) and, like
  `@Mirrored()`, is a build error inside `@Embedded` classes: embedded
  fields live inside the document blob and have no column, so there is
  nothing to index. Anything else — a list, a map, an embedded class — is a
  build error naming the field and the supported types. Path params cannot
  carry it; they stay on the class (a stacked `@Index` line or `indexes:`).
- `@Mirrored()` is allowed on exactly the types an index field allows
  (`int`, `double`, `bool`, `String`, `DateTime`, `Uint8List`, enums) and
  inside `@Embedded` classes only as an error: embedded fields live inside
  the document blob and have no column, so there is nothing to mirror.
  Anything else — a list, a map, an embedded class — is a build error
  naming the field and the supported types.
- **Subcollection indexes start with the path params** (`accountId` above):
  a scoped query always filters them, so an index without them can't serve
  it. An index without params serves collection-group queries.
- The build fails when the models and `cocoon.lock` disagree:

  ```text
  Cocoon schema changed for Txn: run "dart run cocoon_generator:migrate" (added: currencyCode; removed: currency).
  ```

  The builder never writes the lock; the `migrate` command does.

## Without code generation

Every generated artifact is a plain class you can write by hand: one
`CollectionAdapter<T>` per collection, with typed `FieldColumn` handles,
`ParamColumn` handles for path params, `IndexDef` declarations and a
`WireWriter`/`WireReader` codec. The storage contract it must satisfy is
described in [Internals](/libraries/cocoon/internals).

One adapter per collection model. It declares the table shape, the indexed
fields copied into typed columns, and the canonical wire codec. This is the
class the code generator emits from `@Collection` models; you only need this
when you can't use codegen. The examples below use hand-written handles
(`txnBookedOn`); generated code exposes the same handles as `Txn$.bookedOn`.

```dart
enum TxnStatus { pending, posted, failed }

class Txn {
  const Txn({
    required this.bookedOn,
    required this.amountMinor,
    required this.currency,
    required this.status,
    required this.createdAt,
    this.memo,
  });

  final int bookedOn; // yyyymmdd
  final int amountMinor; // minor units; may be negative
  final String currency;
  final TxnStatus status;
  final DateTime createdAt;
  final String? memo;
}

// Typed handles, one per indexed field. Used for queries and for the
// columns the engine mirrors into SQLite.
final txnBookedOn = FieldColumn.integer<Txn, int>(
  'bookedOn',
  read: (t) => t.bookedOn,
);
final txnAmountMinor = FieldColumn.integer<Txn, int>(
  'amountMinor',
  read: (t) => t.amountMinor,
);
final txnCurrency = FieldColumn.text<Txn, String>(
  'currency',
  read: (t) => t.currency,
);
final txnStatus = FieldColumn.enumerated<Txn, TxnStatus>(
  'status',
  read: (t) => t.status,
  values: TxnStatus.values,
);
final txnCreatedAt = FieldColumn.dateTime<Txn, DateTime>(
  'createdAt',
  read: (t) => t.createdAt,
);
final txnMemo = FieldColumn.text<Txn, String?>(
  'memo',
  read: (t) => t.memo,
  nullable: true,
);
final txnAccountId = ParamColumn(txns.pattern, 'accountId');

final class TxnAdapter extends CollectionAdapter<Txn> {
  @override
  String get model => 'Txn';

  @override
  final pattern = CollectionPattern.parse('accounts/{accountId}/txns');

  @override
  List<FieldColumn<Txn, Object?>> get columns => [
    txnBookedOn,
    txnAmountMinor,
    txnCurrency,
    txnStatus,
    txnCreatedAt,
    txnMemo,
  ];

  @override
  List<IndexDef> get indexes => [
    // '-' prefixes a descending part, like @Index(['accountId', '-bookedOn']).
    IndexDef.fromFields(['accountId', '-bookedOn']),
    IndexDef.fromFields(['status', 'bookedOn']),
  ];

  @override
  Uint8List encode(Txn value) {
    final writer = WireWriter();
    writer.writeInt64(1, value.bookedOn);
    writer.writeSint64(2, value.amountMinor); // zigzag: safe for negatives
    writer.writeString(3, value.currency);
    writer.writeString(4, value.status.name);
    writer.writeInt64(5, value.createdAt.toUtc().microsecondsSinceEpoch);
    final memo = value.memo;
    if (memo != null) writer.writeString(6, memo); // skip nulls
    return writer.toBytes();
  }

  @override
  Txn decode(Uint8List bytes) {
    final reader = WireReader(bytes);
    var bookedOn = 0;
    var amountMinor = 0;
    var currency = '';
    var status = TxnStatus.pending;
    var createdAt = DateTime.utc(1970);
    String? memo;
    while (!reader.isAtEnd) {
      final tag = reader.readTag();
      switch (tag.field) {
        case 1: bookedOn = reader.readInt64();
        case 2: amountMinor = reader.readSint64();
        case 3: currency = reader.readString();
        case 4: status = TxnStatus.values.byName(reader.readString());
        case 5:
          createdAt = DateTime.fromMicrosecondsSinceEpoch(
            reader.readInt64(),
            isUtc: true,
          );
        case 6: memo = reader.readString();
        default: reader.skip(tag.type); // unknown fields from the future
      }
    }
    return Txn(
      bookedOn: bookedOn,
      amountMinor: amountMinor,
      currency: currency,
      status: status,
      createdAt: createdAt,
      memo: memo,
    );
  }
}

final txns = TxnAdapter();
```

Field numbers are the identity of a field on disk (they will be pinned in
`cocoon.lock`); write them in ascending order. Ready-made column
factories: `FieldColumn.integer`, `real`, `boolean` (stored 0/1), `text`,
`dateTime` (UTC microseconds), `enumerated` (name as text) and `blob`.
