platform/packages/orm
2021-12-23 20:05:57 +08:00
..
angel_migration Updated linter 2021-12-20 12:25:43 +08:00
angel_migration_runner Updated README 2021-12-21 07:52:59 +08:00
angel_orm Updated ORM 2021-12-23 20:05:57 +08:00
angel_orm_generator Removed deprecated packages 2021-12-22 07:51:13 +08:00
angel_orm_mysql Updated orm_mysql pubspec 2021-12-21 08:02:53 +08:00
angel_orm_postgres Updated ORM 2021-12-23 20:05:57 +08:00
angel_orm_service Updated orm_service pubspec 2021-12-21 08:08:32 +08:00
angel_orm_sqlite Updated license 2021-06-14 11:52:58 +08:00
angel_orm_test Updated ORM 2021-12-23 20:05:57 +08:00
tool Add 'packages/orm/' from commit 'ceb58a25b58eeabeeab5a0bb6257f144e150dc24' 2020-02-15 18:22:15 -05:00
.gitignore Add 'packages/orm/' from commit 'ceb58a25b58eeabeeab5a0bb6257f144e150dc24' 2020-02-15 18:22:15 -05:00
.travis.yml Add 'packages/orm/' from commit 'ceb58a25b58eeabeeab5a0bb6257f144e150dc24' 2020-02-15 18:22:15 -05:00
LICENSE Updated linter 2021-12-20 12:25:43 +08:00
README.md Updated linter 2021-12-20 12:25:43 +08:00

ORM

Pub Version (including pre-releases) Null Safety Gitter License

Source-generated ORM for use with the Angel3 framework. Now you can combine the power and flexibility of Angel3 with a strongly-typed ORM.

Documentation for migrations can be found here: ORM Migration

Usage

You'll need these dependencies in your pubspec.yaml:

dependencies:
  angel3_orm: ^4.0.0
dev_dependencies:
  angel3_orm_generator: ^4.0.0
  build_runner: ^2.0.0

package:angel3_orm_generator exports a class that you can include in a package:build flow:

  • PostgresOrmGenerator - Fueled by package:source_gen; include this within a SharedPartBuilder.

However, it also includes a build.yaml that builds ORM files automatically, so you shouldn't have to do any configuration at all.

Models

The ORM works best when used with package:angel3_serialize:

library angel_orm.test.models.car;

import 'package:angel3_migration/angel3_migration.dart';
import 'package:angel3_model/angel3_model.dart';
import 'package:angel3_orm/angel3_orm.dart';
import 'package:angel3_serialize/angel3_serialize.dart';
part 'car.g.dart';

@serializable
@orm
abstract class _Car extends Model {
  String get make;

  String get description;

  bool get familyFriendly;

  DateTime get recalledAt;
}

// You can disable migration generation.
@Orm(generateMigrations: false)
abstract class _NoMigrations extends Model {}

Models can use the @SerializableField() annotation; package:angel3_orm obeys it.

After building, you'll have access to a Query class with strongly-typed methods that allow to run asynchronous queries without a headache.

Remember that if you don't need automatic id-and-date fields, you can simply just not extend Model:

@Serializable
abstract class _ThisIsNotAnAngelModel {
  @primaryKey
  String get username;
}

Example

MVC just got a whole lot easier:

import 'package:angel3_framework/angel3_framework.dart';
import 'package:angel3_orm/angel3_orm.dart';
import 'car.dart';
import 'car.orm.g.dart';

/// Returns an Angel plug-in that connects to a database, and sets up a controller connected to it...
AngelConfigurer connectToCarsTable(QueryExecutor executor) {
  return (Angel app) async {
    // Register the connection with Angel's dependency injection system.
    // 
    // This means that we can use it as a parameter in routes and controllers.
    app.container.registerSingleton(executor);
    
    // Attach the controller we create below
    await app.mountController<CarController>();
  };
}

@Expose('/cars')
class CarController extends Controller {
  // The `executor` will be injected.
  @Expose('/recalled_since_2008')
  carsRecalledSince2008(QueryExecutor executor) {
    // Instantiate a Car query, which is auto-generated. This class helps us build fluent queries easily.
    var query = CarQuery();
    query.where
      ..familyFriendly.equals(false)
      ..recalledAt.year.greaterThanOrEqualTo(2008);
    
    // Shorter syntax we could use instead...
    query.where.recalledAt.year <= 2008;
    
    // `get()` returns a Future<List<Car>>.
    var cars = await query.get(executor);
    
    return cars;
  }
  
  @Expose('/create', method: 'POST')
  createCar(QueryExecutor executor) async {
    // `package:angel3_orm` generates a strongly-typed `insert` function on the query class.
    // Say goodbye to typos!!!
    var query = CarQuery();
    query.values
      ..familyFriendly = true
      ..make 'Honda';
    var car = query.insert(executor);
    
    // Auto-serialized using code generated by `package:angel_serialize`
    return car;
  }
}

Relations

angel3_orm supports the following relationships:

  • @HasOne() (one-to-one)
  • @HasMany() (one-to-many)
  • @BelongsTo() (one-to-one)
  • @ManyToMany() (many-to-many, using a "pivot" table)

The annotations can be abbreviated with the default options (ex. @hasOne), or supplied with custom parameters (ex. @HasOne(foreignKey: 'foreign_id')).

@serializable
@orm
abstract class _Author extends Model {
  @HasMany // Use the defaults, and auto-compute `foreignKey`
  List<_Book> books;
  
  // Also supports parameters...
  @HasMany(localKey: 'id', foreignKey: 'author_id', cascadeOnDelete: true)
  List<_Book> books;
  
  @SerializableField(alias: 'writing_utensil')
  @hasOne
  _Pen pen;
}

The relationships will "just work" out-of-the-box, following any operation. For example, after fetching an Author from the database in the above example, the books field would be populated with a set of deserialized Book objects, also fetched from the database.

Relationships use joins when possible, but in the case of @HasMany(), two queries are used:

  • One to fetch the object itself
  • One to fetch a list of related objects

Many to Many Relations

A many-to-many relationship can now be modeled like so. RoleUser in this case is a pivot table joining User and Role.

Note that in this case, the models must reference the private classes (_User, etc.), because the canonical versions (User, etc.) are not-yet-generated:

@serializable
@orm
abstract class _User extends Model {
  String get username;
  String get password;
  String get email;

  @ManyToMany(_RoleUser)
  List<_Role> get roles;
}

@serializable
@orm
abstract class _RoleUser {
  @belongsTo
  _Role get role;

  @belongsTo
  _User get user;
}

@serializable
@orm
abstract class _Role extends Model {
  String name;

  @ManyToMany(_RoleUser)
  List<_User> get users;
}

TLDR:

  1. Make a pivot table, C, between two tables, table A and B
  2. C should @belongsTo both A and B. C should not extend Model.
  3. A should have a field: @ManyToMany(_C) List<_B> get b;
  4. B should have a field: @ManyToMany(_C) List<_A> get a;

Test: https://raw.githubusercontent.com/angel-dart/orm/master/angel_orm_generator/test/many_to_many_test.dart

Columns

Use a @Column() annotation to change how a given field is handled within the ORM.

Column Types

Using the @Column() annotation, it is possible to explicitly declare the data type of any given field:

@serializable
@orm
abstract class _Foo extends Model {
  @Column(type: ColumnType.bigInt)
  int bar;
}

Indices

Columns can also have an index:

@serializable
@orm
abstract class _Foo extends Model {
  @Column(index: IndexType.primaryKey)
  String bar;
}

Default Values

It is also possible to specify the default value of a field. Note that this only works with primitive objects.

If a default value is supplied, the SqlMigrationBuilder will include it in the generated schema. The PostgresOrmGenerator ignores default values; it does not need them to function properly.

@serializable
@orm
abstract class _Foo extends Model {
  @Column(defaultValue: 'baz')
  String bar;
}