orm

Pubbuild status

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

Documentation for migrations can be found here:https://angel-dart.gitbook.io/angel/v/2.x/orm/migrations

Usage

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

  1. dependencies:
  2. angel_orm: ^2.0.0-dev
  3. dev_dependencies:
  4. angel_orm_generator: ^2.0.0-dev
  5. build_runner: ^1.0.0

package:angel_orm_generator exports a class that you can includein 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'thave to do any configuration at all.

Models

The ORM works best when used with package:angel_serialize:

  1. library angel_orm.test.models.car;
  2.  
  3. import 'package:angel_migration/angel_migration.dart';
  4. import 'package:angel_model/angel_model.dart';
  5. import 'package:angel_orm/angel_orm.dart';
  6. import 'package:angel_serialize/angel_serialize.dart';
  7. part 'car.g.dart';
  8.  
  9. @serializable
  10. @orm
  11. abstract class _Car extends Model {
  12. String get make;
  13.  
  14. String get description;
  15.  
  16. bool get familyFriendly;
  17.  
  18. DateTime get recalledAt;
  19. }
  20.  
  21. // You can disable migration generation.
  22. @Orm(generateMigrations: false)
  23. abstract class _NoMigrations extends Model {}

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

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

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

  1. @Serializable(autoIdAndDateFields: false)abstract class _ThisIsNotAnAngelModel { @primaryKey String get username;}

Example

MVC just got a whole lot easier:

  1. import 'package:angel_framework/angel_framework.dart';
  2. import 'package:angel_orm/angel_orm.dart';
  3. import 'car.dart';
  4. import 'car.orm.g.dart';
  5.  
  6. /// Returns an Angel plug-in that connects to a database, and sets up a controller connected to it...
  7. AngelConfigurer connectToCarsTable(QueryExecutor executor) {
  8. return (Angel app) async {
  9. // Register the connection with Angel's dependency injection system.
  10. //
  11. // This means that we can use it as a parameter in routes and controllers.
  12. app.container.registerSingleton(executor);
  13.  
  14. // Attach the controller we create below
  15. await app.mountController<CarController>();
  16. };
  17. }
  18.  
  19. @Expose('/cars')
  20. class CarController extends Controller {
  21. // The `executor` will be injected.
  22. @Expose('/recalled_since_2008')
  23. carsRecalledSince2008(QueryExecutor executor) {
  24. // Instantiate a Car query, which is auto-generated. This class helps us build fluent queries easily.
  25. var query = new CarQuery();
  26. query.where
  27. ..familyFriendly.equals(false)
  28. ..recalledAt.year.greaterThanOrEqualTo(2008);
  29.  
  30. // Shorter syntax we could use instead...
  31. query.where.recalledAt.year <= 2008;
  32.  
  33. // `get()` returns a Future<List<Car>>.
  34. var cars = await query.get(executor);
  35.  
  36. return cars;
  37. }
  38.  
  39. @Expose('/create', method: 'POST')
  40. createCar(QueryExecutor executor) async {
  41. // `package:angel_orm` generates a strongly-typed `insert` function on the query class.
  42. // Say goodbye to typos!!!
  43. var query = new CarQuery();
  44. query.values
  45. ..familyFriendly = true
  46. ..make 'Honda';
  47. var car = query.insert(executor);
  48.  
  49. // Auto-serialized using code generated by `package:angel_serialize`
  50. return car;
  51. }
  52. }

Relations

angel_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 suppliedwith custom parameters (ex. @HasOne(foreignKey: 'foreign_id')).

  1. @serializable@ormabstract class _Author extends Model { @HasMany // Use the defaults, and auto-compute foreignKey List<_Book> books;

  2. // Also supports parameters… @HasMany(localKey: 'id', foreignKey: 'author_id', cascadeOnDelete: true) List<_Book> books;

  3. @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 wouldbe 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:

  1. @serializable@ormabstract class _User extends Model { String get username; String get password; String get email;

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

  3. @serializable@ormabstract class _RoleUser { @belongsTo _Role get role;

  4. @belongsTo _User get user;}

  5. @serializable@ormabstract class _Role extends Model { String name;

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

TLDR:

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:

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

Indices

Columns can also have an index:

  1. @serializable@ormabstract 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 includeit in the generated schema. The PostgresOrmGenerator ignores default values;it does not need them to function properly.

  1. @serializable@ormabstract class _Foo extends Model { @Column(defaultValue: 'baz') String bar;}