dorm_annotations 2.0.0-dev.1 copy "dorm_annotations: ^2.0.0-dev.1" to clipboard
dorm_annotations: ^2.0.0-dev.1 copied to clipboard

Exposes annotations used to generate code for dORM framework.

dorm_annotations #

pub package pub popularity pub likes pub points

Provides annotations related with dORM code generation.

Getting started #

Run the following commands inside your project:

dart pub add dorm_annotations
dart pub get

Take a look at the dorm_generator package to learn how to generate code for these annotations.

Usage #

Models #

The Model annotation is used to link a database table to a Dart class.

It accepts two parameters:

  • name: Specifies the name of the table in the underlying database.
  • as: Provides a name for the repository accessor of the model.
import 'package:dorm_annotations/dorm_annotations.dart';

@Model(name: 'user', as: #users)
abstract class _User {}

Fields #

The Field annotation is used to link a database column to a Dart field within a model class.

It accepts the following parameters:

  • name: Optional name of the column in the underlying database. When omitted, the generator uses the annotated getter name.
  • defaultValue: Provides an optional default value for the field. If not explicitly set and the return type of the getter is nullable, the field will default to null.
import 'package:dorm_annotations/dorm_annotations.dart';

@Model(name: 'user', as: #users)
abstract class _User {
  @Field(name: 'name')
  String? get name;

  @Field(name: 'birth-date')
  DateTime get birthDate;

  @Field(name: 'emails', defaultValue: [])
  List<String> get emails;

  @Field(name: 'picture-url')
  Uri get pictureUrl;
}

The return type of the getters can be any of the specified on the json_serializable package:

BigInt, bool, DateTime, double, Duration, Enum, int, Iterable, List, Map, num, Object, Record, Set, String and Uri.

The collection types - Iterable, List, Map, Record, Set - can contain values of all the above types.

For Map, the key value must be one of BigInt, DateTime, Enum, int, Object, String and Uri.

If you own/control the desired type, add a fromJson constructor and a toJson function to the type.

Foreign fields #

The ForeignField annotation is used to link a database foreign key to a Dart field within a model class.

In a relational database, a foreign key is a column in a table that establishes a relationship or association with the primary key column of another table. The foreign column helps enforce referential integrity, which ensures that the referenced data exists and remains consistent.

It accepts the following parameters:

  • name: Optional name of the foreign key column in the underlying database. When omitted, the generator uses the annotated getter name.
  • referTo: Specifies the model class that the foreign key references.
  • unique: Indicates that the foreign key is unique in the source model. A non-unique foreign key is many-to-one; a unique foreign key can be one-to-one.
  • as: Optional name of the generated forward relationship accessor.
  • inverseAs: Optional explicit name of the generated inverse relationship accessor.
import 'package:dorm_annotations/dorm_annotations.dart';

@Model(name: 'post', as: #posts)
abstract class _Post {
  @Field(name: 'contents')
  String get contents;

  @Field(name: 'creation-date')
  DateTime get creationDate;

  @ForeignField(name: 'user-id', referTo: _User, inverseAs: #posts)
  String get userId;
}

Derived fields #

The DerivedField annotation marks a static callback whose result is materialized with the model. It does not create a database index. A SQL engine stores a simple name as a scalar column and a root/child name inside a backend-specific JSON value.

The callback name must start with $dorm$derived$. The suffix becomes the generated getter and schema field name. The annotation's name is the persisted storage name; when omitted, the suffix is used.

import 'package:dorm_annotations/dorm_annotations.dart';

@Model(name: 'school', as: #schools)
abstract class _School {
  @Field(name: 'name')
  String get name;

  @DerivedField(name: '_query/name')
  static String $dorm$derived$qName(
    _School model,
    DerivedTransformations transformations,
  ) => transformations.text(model.name) ?? '';
}

The generator creates qName on the generated model and includes its value in the serialized representation. Query the field through its generated DerivedFieldSchema.

The callback can combine values directly, without a token list or automatic separator:

@DerivedField(name: '_query/address')
static String $dorm$derived$qAddress(
  _SchoolAddress model,
  DerivedTransformations transformations,
) => '${model.zipCode}_${model.number}';

DerivedTransformations provides text, enumeration, date, and datetime. Each method delegates to the corresponding normalization helper and returns a nullable String. The callback may also return another synchronous value that the existing serialization and database engine can represent, such as a number, boolean, list, map, date, or null.

Derived callbacks are synchronous, are declared directly on the annotated class, and receive the model plus a DerivedTransformations instance. The generator does not inspect the callback body to prove that its result is serializable.

Composite fields #

The ModelField annotation is used to link a database composite column to a Dart field within a model class.

In a non-relational database, a composite column refers to a field that can hold a collection of values or sub-attributes within a single column. Unlike a simple column that holds a single value, a composite column allows for the grouping or nesting of multiple values or sub-attributes together. This can be useful for representing complex or structured data within a single field in a non-relational database model.

It accepts the following parameters:

  • name: Optional name of the column in the underlying database. When omitted, the generator uses the annotated getter name.
  • referTo: Specifies the model class that should be represented within this field.
import 'package:dorm_annotations/dorm_annotations.dart';

@Model(name: 'school-address', as: #schoolAddresses)
abstract class _SchoolAddress {
  @Field(name: 'zip-code')
  String get zipCode;
}

@Model(name: 'school', as: #schools)
abstract class _School {
  @Field(name: 'name')
  String get name;

  @ModelField(name: 'address', referTo: _SchoolAddress)
  get address;
}

Plain models #

The Data annotation is used to simply serialize a class.

It accepts no arguments.

import 'package:dorm_annotations/dorm_annotations.dart';

@Data()
abstract class _SchoolAddress {
  @Field(name: 'zip-code')
  String get zipCode;

  @Field(name: 'district')
  String get district;

  @Field(name: 'house-number')
  int get number;
}

You can also use a class annotated with Data as an argument to referTo of a ModelField annotation.

Polymorphism #

The PolymorphicField annotation is used to link a database composite column and a pivot column to a Dart field within a model class.

In a non-relational database, polymorphism refers to the ability to store different types of objects in a single table. It allows for flexible data modeling, where objects of various types can be stored together, and the specific type of each object is determined by a pivot column. A composite column stores the specific contents of each sub-table, while the remaining columns store the common attributes of the base table.

  • The pivot column, represented as a string, is used to identify the specific type or sub-table to which each object belongs. It acts as a discriminator, indicating the type of the object stored in the composite column.
  • The composite column holds the contents or attributes specific to each sub-table or object type. Depending on the value of the pivot column, the composite column stores the corresponding data structure or format for that specific object type.
  • The remaining columns in the table represent the common attributes shared by all object types. These columns store the general or shared properties that are applicable to all objects, regardless of their specific type.

It accepts the following parameters:

  • name: Optional name of the composite column in the underlying database. When omitted, the generator uses the annotated getter name.
  • pivotName: Specifies the name of the pivot column in the underlying database.
  • pivotAs: Specifies the name of the pivot field in the Dart class.
import 'package:dorm_annotations/dorm_annotations.dart';

abstract class _Action {}

@Model(name: 'operation', as: #operations)
abstract class _Operation {
  @Field(name: 'name')
  String get name;

  @PolymorphicField(name: 'action', pivotName: 'type', pivotAs: #type)
  _Action get action;
}

The PolymorphicData is used to create a composite object of a polymorphic field:

import 'package:dorm_annotations/dorm_annotations.dart';

@PolymorphicData(name: 'attack')
abstract class _Attack implements _Action {
  @Field(name: 'strength')
  int get strength;
}

@PolymorphicData(name: 'defence')
abstract class _Defense implements _Action {
  @Field(name: 'resistance')
  int get resistance;
}

@PolymorphicData(name: 'healing')
abstract class _Healing implements _Action {
  @Field(name: 'health')
  int get health;
}

Unique identification #

The default identifier type is String. A custom generated identity method is declared directly on the annotated class. It receives the generated model and the initially generated identity, and returns the identity that should be persisted:

import 'package:dorm_annotations/dorm_annotations.dart';

@Model(name: 'country', as: #countries)
abstract class _Country {}

@Model(name: 'capital', as: #capitals)
abstract class _Capital {
  static String $dorm$generateId(_Capital model, String id) => model.countryId;

  @ForeignField(name: 'country-id', referTo: _Country)
  String get countryId;
}

The generator validates the method signature while generating the source. A custom generated key type can be declared through GeneratedIdSpec(type: ...). A database-assigned key can be declared through DatabaseGeneratedIdSpec(type: ...); each database engine decides which ID types it supports.

0
likes
0
points
234
downloads

Publisher

verified publisherenzosantos.dev

Weekly Downloads

Exposes annotations used to generate code for dORM framework.

Homepage
Repository (GitHub)
View/report issues

License

unknown (license)

Dependencies

copy_with_extension, json_annotation, lints, meta

More

Packages that depend on dorm_annotations