2017-06-17 16:45:31 +00:00
# orm
[![Pub ](https://img.shields.io/pub/v/angel_orm.svg )](https://pub.dartlang.org/packages/angel_orm)
[![build status ](https://travis-ci.org/angel-dart/orm.svg )](https://travis-ci.org/angel-dart/orm)
2017-07-09 16:53:35 +00:00
Source-generated PostgreSQL ORM for use with the
[Angel framework ](https://angel-dart.github.io ).
Now you can combine the power and flexibility of Angel with a strongly-typed ORM.
2017-06-17 16:45:31 +00:00
2017-07-10 21:49:00 +00:00
* [Usage ](#usage )
* [Model Definitions ](#models )
* [MVC Example ](#example )
* [Relationships ](#relations )
2018-12-08 23:30:28 +00:00
* [Many-to-Many Relationships ](#many-to-many-relations )
2017-09-15 19:41:30 +00:00
* [Columns (`@Column(...)`) ](#columns )
* [Column Types ](#column-types )
* [Indices ](#indices )
* [Default Values ](#default-values )
2017-07-10 21:49:00 +00:00
# Usage
You'll need these dependencies in your `pubspec.yaml` :
```yaml
dependencies:
2018-12-08 23:30:28 +00:00
angel_orm: ^2.0.0-dev
2017-07-10 21:49:00 +00:00
dev_dependencies:
2018-12-08 23:30:28 +00:00
angel_orm_generator: ^2.0.0-dev
build_runner: ^1.0.0
2017-07-10 21:49:00 +00:00
```
2018-12-08 23:30:28 +00:00
`package:angel_orm_generator` exports a class that you can include
2017-07-10 21:49:00 +00:00
in a `package:build` flow:
2018-12-08 23:30:28 +00:00
* `PostgresOrmGenerator` - Fueled by `package:source_gen` ; include this within a `SharedPartBuilder` .
2017-07-10 21:49:00 +00:00
2018-12-08 23:30:28 +00:00
However, it also includes a `build.yaml` that builds ORM files automatically, so you shouldn't
have to do any configuration at all.
2017-06-17 16:53:32 +00:00
2017-07-09 16:53:35 +00:00
# Models
2017-06-17 16:51:01 +00:00
Your model, courtesy of `package:angel_serialize` :
2017-06-17 16:45:31 +00:00
```dart
library angel_orm.test.models.car;
2018-12-31 11:36:08 +00:00
import 'package:angel_migration/angel_migration.dart';
import 'package:angel_model/angel_model.dart';
2017-06-18 04:19:05 +00:00
import 'package:angel_orm/angel_orm.dart';
2017-06-17 16:45:31 +00:00
import 'package:angel_serialize/angel_serialize.dart';
part 'car.g.dart';
@serializable
2017-06-18 04:19:05 +00:00
@orm
2018-12-09 17:44:16 +00:00
abstract class _Car extends Model {
String get make;
String get description;
bool get familyFriendly;
DateTime get recalledAt;
2017-06-17 16:45:31 +00:00
}
2018-12-09 17:44:16 +00:00
// You can disable migration generation.
@Orm (generateMigrations: false)
abstract class _NoMigrations extends Model {}
2017-06-17 16:45:31 +00:00
```
2017-07-09 16:53:35 +00:00
Models can use the `@Alias()` annotation; `package:angel_orm` obeys it.
2017-06-18 04:19:05 +00:00
After building, you'll have access to a `Query` class with strongly-typed methods that
2017-06-17 16:45:31 +00:00
allow to run asynchronous queries without a headache.
2017-07-09 16:53:35 +00:00
2017-07-10 21:49:00 +00:00
**IMPORTANT:** The ORM *assumes* that you are using `package:angel_serialize` , and will only generate code
designed for such a workflow. Save yourself a headache and build models with `angel_serialize` :
https://github.com/angel-dart/serialize
2018-12-08 23:30:28 +00:00
Remember that if you don't need automatic id-and-date fields, you can do the following:
```dart
@Serializable (autoIdAndDateFields: false)
abstract class _ThisIsNotAnAngelModel {
}
```
2017-07-10 21:49:00 +00:00
# Example
2017-07-09 16:53:35 +00:00
MVC just got a whole lot easier:
2017-06-17 16:45:31 +00:00
```dart
import 'package:angel_framework/angel_framework.dart';
2018-12-08 23:30:28 +00:00
import 'package:angel_orm/angel_orm.dart';
2017-06-17 16:45:31 +00:00
import 'car.dart';
import 'car.orm.g.dart';
2018-12-08 23:30:28 +00:00
/// Returns an Angel plug-in that connects to a database, and sets up a controller connected to it...
AngelConfigurer connectToCarsTable(QueryExecutor executor) {
2017-06-17 16:45:31 +00:00
return (Angel app) async {
2017-06-18 04:19:05 +00:00
// Register the connection with Angel's dependency injection system.
2017-06-17 16:45:31 +00:00
//
// This means that we can use it as a parameter in routes and controllers.
2018-12-08 23:30:28 +00:00
app.container.registerSingleton(executor);
2017-06-17 16:45:31 +00:00
// Attach the controller we create below
2018-12-08 23:30:28 +00:00
await app.mountController< CarController > ();
2017-06-17 16:45:31 +00:00
};
}
@Expose ('/cars')
2017-07-15 15:20:47 +00:00
class CarController extends Controller {
2018-12-08 23:30:28 +00:00
// The `executor` will be injected.
2017-06-18 04:19:05 +00:00
@Expose ('/recalled_since_2008')
2018-12-08 23:30:28 +00:00
carsRecalledSince2008(QueryExecutor executor) {
2017-06-18 04:19:05 +00:00
// Instantiate a Car query, which is auto-generated. This class helps us build fluent queries easily.
2017-07-15 15:21:18 +00:00
var cars = new CarQuery();
2017-06-18 04:19:05 +00:00
cars.where
..familyFriendly.equals(false)
..recalledAt.year.greaterThanOrEqualTo(2008);
// Shorter syntax we could use instead...
cars.where.recalledAt.year < = 2008;
2018-12-08 23:30:28 +00:00
// `get()` returns a Future< List < Car > >.
return await cars.get(executor);
2017-06-17 16:45:31 +00:00
}
2017-06-18 04:19:05 +00:00
@Expose ('/create', method: 'POST')
2018-12-08 23:30:28 +00:00
createCar(QueryExecutor executor) async {
2017-06-18 04:19:05 +00:00
// `package:angel_orm` generates a strongly-typed `insert` function on the query class.
// Say goodbye to typos!!!
2018-12-08 23:30:28 +00:00
var query = new CarQuery();
query.values
..familyFriendly = true
..make 'Honda';
var car = query.insert(executor);
2017-06-18 04:19:05 +00:00
// Auto-serialized using code generated by `package:angel_serialize`
return car;
}
}
```
# Relations
2017-09-15 19:41:30 +00:00
`angel_orm` supports the following relationships:
2017-06-18 04:19:05 +00:00
2018-12-08 23:30:28 +00:00
* `@HasOne()` (one-to-one)
* `@HasMany()` (one-to-many)
2017-09-15 19:41:30 +00:00
* `@BelongsTo()` (one-to-one)
The annotations can be abbreviated with the default options (ex. `@hasOne` ), or supplied
with custom parameters (ex. `@HasOne(foreignKey: 'foreign_id')` ).
2017-06-18 04:19:05 +00:00
```dart
@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;
@Alias ('writing_utensil')
@hasOne
Pen pen;
2017-06-17 16:45:31 +00:00
}
2017-09-15 19:41:30 +00:00
```
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
2018-12-08 23:30:28 +00:00
## Many to Many Relations
A many-to-many relationship can now be modeled like so.
`UserRole` 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:
```dart
library angel_orm_generator.test.models.user;
import 'package:angel_model/angel_model.dart';
import 'package:angel_orm/angel_orm.dart';
import 'package:angel_serialize/angel_serialize.dart';
import 'package:collection/collection.dart';
part 'user.g.dart';
@serializable
@orm
abstract class _User extends Model {
String get username;
String get password;
String get email;
@hasMany
List< _UserRole > get userRoles;
List< _Role > get roles => userRoles.map((m) => m.role).toList();
}
@serializable
@orm
abstract class _Role extends Model {
String name;
@hasMany
List< _UserRole > get userRoles;
List< _User > get users => userRoles.map((m) => m.user).toList();
}
@Serializable (autoIdAndDateFields: false)
@orm
abstract class _UserRole {
int get id;
@belongsTo
_User get user;
@belongsTo
_Role get role;
}
```
TLDR:
1. Make a pivot table, C, between two tables, table A and B
2. C should `@belongsTo` both A and B.
3. Both A and B should `@hasMany` C.
4. For convenience, write a simple getter, like the above `User.roles` .
Test: https://raw.githubusercontent.com/angel-dart/orm/master/angel_orm_generator/test/many_to_many_test.dart
There are 2 tests there, but they are more or less a proof-of-concept. All the logic for the other relations have their own unit tests.
2017-09-15 19:41:30 +00:00
# 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:
```dart
@serializable
@orm
abstract class _Foo extends Model {
2018-12-08 23:30:28 +00:00
@Column (type: ColumnType.bigInt)
2017-09-15 19:41:30 +00:00
int bar;
}
```
## Indices
Columns can also have an `index` :
```dart
@serializable
@orm
abstract class _Foo extends Model {
2018-12-08 23:30:28 +00:00
@Column (index: IndexType.primaryKey)
2017-09-15 19:41:30 +00:00
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.
```dart
@serializable
@orm
abstract class _Foo extends Model {
@Column (defaultValue: 'baz')
String bar;
}
2017-06-17 16:45:31 +00:00
```