# ORM attributes

Four attributes in `Bootgly\ADI\Databases\SQL\Model` map an entity: `Table` on the class, `Key` and
`Column` on the properties the database stores, and `Relation` on the properties that hold related
entities. `Model::reflect()` reads them when a class is first mapped. What makes a class mappable,
the errors a bad mapping throws and how to type the properties are on
**[ORM Model](/manual/ADI/Databases/SQL/Model/overview/)**.

The sections below use these entities:

```php
use DateTimeImmutable;

use Bootgly\ADI\Databases\SQL\Model\Auxiliaries\Relations;
use Bootgly\ADI\Databases\SQL\Model\Column;
use Bootgly\ADI\Databases\SQL\Model\Key;
use Bootgly\ADI\Databases\SQL\Model\Relation;
use Bootgly\ADI\Databases\SQL\Model\Table;

#[Table('users')]
class User
{
   #[Key]
   public null|int $id = null;

   #[Column]
   public string $name = '';

   #[Column('created_at', insert: false, update: false)]
   public null|DateTimeImmutable|string $CreatedAt = null;

   /** @var array<int,Post> */
   #[Relation(Relations::HasMany, Post::class, 'id', 'user')]
   public array $Posts = [];

   #[Relation(Relations::HasOne, Profile::class, 'id', 'user')]
   public null|Profile $Profile = null;

   /** @var array<int,Team> */
   #[Relation(Relations::BelongsToMany, Team::class, 'id', 'id', table: 'memberships', pivotLocal: 'user_id', pivotForeign: 'team_id')]
   public array $Teams = [];
}

#[Table('posts')]
class Post
{
   #[Key]
   public null|int $id = null;

   #[Column('user_id')]
   public int $user = 0;

   #[Column]
   public string $title = '';

   #[Relation(Relations::BelongsTo, User::class, 'user', 'id', name: 'author')]
   public null|User $Author = null;
}

#[Table('profiles')]
class Profile
{
   #[Key]
   public null|int $id = null;

   #[Column('user_id')]
   public int $user = 0;

   #[Column]
   public string $bio = '';
}

#[Table('teams')]
class Team
{
   #[Key]
   public null|int $id = null;

   #[Column]
   public string $name = '';
}
```

They map the tables `users (id, name, created_at)`, with `created_at` defaulting to the current
time, `posts (id, user_id, title)`, `profiles (id, user_id, bio)`, `teams (id, name)` and the pivot
table `memberships (user_id, team_id)`. Every `id` is generated by the database. The examples run
on `$Database`, the SQL facade, opened as
**[Open a database](/manual/ADI/Databases/SQL/overview/#open-a-database)** shows.

## Table

```php
#[Table('users')]
class User
```

`Table` names the table of the entity. A class carries exactly one, and a subclass declares its own
(see **[Inheritance](/manual/ADI/Databases/SQL/Model/overview/#inheritance)**).

The name is quoted as an identifier in every statement, so write it exactly as the table is named:
PostgreSQL matches a quoted name case-sensitively, and so does MySQL on Linux by default, so
`#[Table('Users')]` does not find a table created as `users`. A dotted name is quoted part by part:
`#[Table('billing.invoices')]` maps the `invoices` table of the `billing` schema on PostgreSQL, or
of the `billing` database on MySQL. An empty name throws `ORM table name cannot be empty.`

## Key

```php
#[Key]
public null|int $id = null;
```

`Key` marks the primary key: one property per entity, one column. The column is the property name,
or the name you pass, as in `#[Key('user_id')]`. An UPDATE never writes the key, which is the
`WHERE` of the statement. Who assigns the key decides how `save()` picks between `INSERT` and
`UPDATE`, as the two cases below sum up; the routing in full, with the cases the identity map does
not cover yet, is on **[Save entities](/manual/ADI/Databases/SQL/Repository/overview/#save-entities)**.

### Generated keys

`#[Key]` alone means `generated: true`: the database assigns the key, with `serial` or an identity
column on PostgreSQL, `AUTO_INCREMENT` on MySQL and `INTEGER PRIMARY KEY` on SQLite. The INSERT
leaves the key column out, and hydrating the `save()` writes the generated key into the object you
saved. `save()` inserts while the key reads `null` and updates the row with that key otherwise, so
declare the key `null|int $id = null`, or leave it uninitialized (see
**[Construction and defaults](/manual/ADI/Databases/SQL/Model/overview/#construction-and-defaults)**).

### Application-assigned keys

```php
use Bootgly\ADI\Databases\SQL\Model\Column;
use Bootgly\ADI\Databases\SQL\Model\Key;
use Bootgly\ADI\Databases\SQL\Model\Table;

#[Table('settings')]
class Setting
{
   #[Key(generated: false)]
   public null|string $name = null;

   #[Column]
   public string $value = '';
}

$Settings = $Database->map(Setting::class);

$Setting = new Setting;
$Setting->name = 'theme';
$Setting->value = 'dark';

$Database->await($Settings->save($Setting));

$Setting = $Settings->hydrate($Database->await($Settings->find('theme')))->entity;
$Setting->value = 'light';

$Database->await($Settings->save($Setting));
```

`#[Key(generated: false)]` leaves the key to the application: the INSERT writes it, and an UPDATE
never does. A key that is already set cannot tell `save()` whether its row exists, so `save()` asks
the repository's identity map: a key the repository tracks, because it hydrated the row, means an
UPDATE, and any other key an INSERT — hence the `find()` before the change above. What that means
for an entity you built, a second save, a `null` key or a deleted one is on
**[Save entities](/manual/ADI/Databases/SQL/Repository/overview/#save-entities)**.

## Column

```php
#[Column]
public string $name = '';

#[Column('created_at', insert: false, update: false)]
public null|DateTimeImmutable|string $CreatedAt = null;
```

`Column` maps one stored property. Its options:

| Option | Default | Effect |
|---|---|---|
| `name` | `null` | The column. `null` uses the property name. An empty name throws `ORM column name cannot be empty.` |
| `insert` | `true` | `false` leaves the column out of every INSERT, so the database default fills it. |
| `update` | `true` | `false` leaves the column out of every UPDATE. |
| `generated` | `false` | `true` leaves the column out of an INSERT or an UPDATE while the property holds `null`, and lets a row omit the column. A value is written like any other. |
| `nullable` | `false` | `true` lets a row omit the column. It does not let the property take `null`: the property's type decides that. |

Each flag works on its own. On a table that gives `score` a default of `10` and `created_at` the
current time:

```php
use DateTimeImmutable;

use Bootgly\ADI\Databases\SQL\Model\Column;
use Bootgly\ADI\Databases\SQL\Model\Key;
use Bootgly\ADI\Databases\SQL\Model\Table;

#[Table('accounts')]
class Account
{
   #[Key]
   public null|int $id = null;

   #[Column]
   public string $email = '';

   #[Column(update: false)]
   public string $plan = 'free';

   #[Column(generated: true)]
   public null|int $score = null;

   #[Column(nullable: true)]
   public null|string $nick = null;

   #[Column('created_at', insert: false, update: false)]
   public null|DateTimeImmutable|string $CreatedAt = null;
}

$Accounts = $Database->map(Account::class);

$Account = new Account;
$Account->email = 'ada@example.test';
$Account->plan = 'pro';

$Account = $Accounts->hydrate($Database->await($Accounts->save($Account)))->entity ?? $Account;

$Account->email = 'ada@lovelace.test';
$Account->plan = 'team';
$Database->await($Accounts->save($Account));

$Account = $Accounts->hydrate($Database->await($Accounts->find($Account->id)))->entity;

$Account->email; // 'ada@lovelace.test'
$Account->plan;  // 'pro': update: false kept the inserted value
$Account->score; // 10: the INSERT left the null out, so the column default applied
```

### Columns the database fills

```php
use Bootgly\ADI\Databases\SQL\Model\Column;
use Bootgly\ADI\Databases\SQL\Model\Key;
use Bootgly\ADI\Databases\SQL\Model\Table;

#[Table('lines')]
class Line
{
   #[Key]
   public null|int $id = null;

   #[Column]
   public int $quantity = 0;

   #[Column]
   public int $price = 0;

   #[Column(insert: false, update: false)]
   public null|int $total = null;
}
```

- A column the database always computes or stamps, such as `total` above, declared
  `GENERATED ALWAYS AS (quantity * price) STORED`, or a creation time, takes
  `insert: false, update: false`. `generated: true` is not enough for it: once a hydration fills the
  property, the next UPDATE writes the value back, and the database refuses it. PostgreSQL answers
  `column "total" can only be updated to DEFAULT`, MySQL
  `3105: The value specified for generated column 'total' in table 'lines' is not allowed.` and
  SQLite `Unable to prepare statement: cannot UPDATE generated column "total"`.
- `generated: true` fits a column the database fills only when you give it no value, a default you
  may override, like `score` in `Account`.
- With `insert: false` alone, the column stays writable by an UPDATE, and for now, on MySQL and
  SQLite, the next `save()` after the INSERT writes the class default over the database's value, as
  **[Save entities](/manual/ADI/Databases/SQL/Repository/overview/#save-entities)** explains:
  `find()` the entity before you change it, or add `update: false`.

Temporal columns have one more constraint on PostgreSQL, which refuses a `DateTimeImmutable` on
`save()` for now: see **[Dates and times](/manual/ADI/Databases/SQL/Model/overview/#dates-and-times)**.

### Rows without a column

A repository selects every mapped column, so a row misses one only when you hydrate a query of your
own: a `nullable` or `generated` column may then be missing, and any other throws, as
**[Missing and extra columns](/manual/ADI/Databases/SQL/Repository/Hydration/overview/#missing-and-extra-columns)**
shows. Cursor pagination refuses to order by a `nullable` column (see
**[ORM Repository Pagination](/manual/ADI/Databases/SQL/Repository/Pagination/overview/#order-a-cursor-walk)**).

## Relation

```php
#[Relation(Relations::HasMany, Post::class, 'id', 'user')]
public array $Posts = [];
```

`Relation` maps a property that holds related entities. Its parameters, in order:

- `Type`: the kind of relation, a case of `Relations`: `HasOne`, `HasMany`, `BelongsTo` or
  `BelongsToMany`.
- `target`: the class of the related entity, which must be mapped too. It is compiled when the
  relation is first loaded, so a wrong class fails then, with that class's mapping error.
- `local`: the column of this entity the relation matches on, named by its property or by its
  column.
- `foreign`: the column of the target it matches, named by its property or by its column.
- `table`, `pivotLocal`, `pivotForeign`: for `BelongsToMany` only. The pivot table, its column that
  holds this entity's `local` value, and its column that holds the target's `foreign` value. The
  pivot has no entity, so these are column names. A `BelongsToMany` without all three throws
  `ORM belongsToMany relation requires pivot table and keys.` when it is loaded.
- `name`: the name of the relation in `load()`, `Selection::load()`, `attach()` and the keys of
  `$Mapped->loads`. It defaults to the property name and is case-sensitive: `$Posts` loads as
  `'Posts'`, never as `'posts'`. An empty name throws `ORM relation name cannot be empty.`
- `lazy`: `true` puts a lazy wrapper in the property at hydration, which loads the relation on first
  access (see **[ORM Repository Relations](/manual/ADI/Databases/SQL/Repository/Relations/overview/)**).

An empty `local` or `foreign` throws `ORM relation keys cannot be empty.` With the entities at the
top of the page, the relations load by name:

```php
$Users = $Database->map(User::class, Awaiting: $Database);

$Mapped = $Users->hydrate($Database->await(
   $Users->fetch($Users->select()->load('Posts', 'Profile', 'Teams'))
));

foreach ($Mapped->entities as $User) {
   $User->Posts;   // the user's posts, an array of Post
   $User->Profile; // a Profile, or null
   $User->Teams;   // the user's teams, through memberships
}

$Posts = $Database->map(Post::class, Awaiting: $Database);

$Mapped = $Posts->hydrate($Database->await(
   $Posts->fetch($Posts->select()->load('author'))
));

$Mapped->entities[0]->Author; // the User who wrote the post
```

`Awaiting: $Database` makes `hydrate()` load and attach the relations itself; without it they come
back as operations to await, as
**[ORM Repository Relations](/manual/ADI/Databases/SQL/Repository/Relations/overview/)** shows.

### Keys by kind

A related entity belongs to a parent when its `foreign` value equals the parent's `local` value.
For `BelongsToMany`, a pivot row links them instead: it holds the parent's `local` value in
`pivotLocal` and the target's `foreign` value in `pivotForeign`.

| Kind | `local`, on this entity | `foreign`, on the target | Property | Lazy property |
|---|---|---|---|---|
| `HasOne` | The key the target points to, usually the primary key | The target's column that points back | `null\|Target` | `LazyReference` |
| `HasMany` | The key the targets point to | The targets' column that points back | `array` | `LazyCollection` |
| `BelongsTo` | The column that points to the target | The key it points to, usually the primary key | `null\|Target` | `LazyReference` |
| `BelongsToMany` | The key the pivot points to | The target key the pivot points to | `array` | `LazyCollection` |

The two keys are checked when the relation is loaded. A `local` that is not a mapped column of this
entity throws `ORM property is not mapped: <local>`. A `foreign` that is not a column of the target
fails on PostgreSQL and MySQL with the database's unknown-column error, but on SQLite the relation
loads empty, with no error.

### Relation properties

- A singular relation writes `null` when nothing matches, so type its property `null|Target`. A
  property typed `Target` alone throws PHP's `TypeError`:
  `Cannot assign null to property User::$Profile of type Profile`.
- A plural relation writes an array, empty when nothing matches.
- A `lazy: true` property must be able to hold its wrapper, a `LazyCollection` or a
  `LazyReference`: the types it accepts, the default to give it and the entities that get no
  wrapper for now are on
  **[Lazy policy](/manual/ADI/Databases/SQL/Repository/Relations/overview/#lazy-policy)**.
- `save()` never writes a relation property: adding a `Post` to `$User->Posts` changes the object
  only. Save related entities through their own repository, and write pivot rows with the
  **[Query Builder](/manual/ADI/Databases/SQL/Builder/Writing/overview/)**.

## Reference

### Table

`#[Attribute(Attribute::TARGET_CLASS)]`

```php
__construct (string $name)
```

Maps the class to the table `$name`. Throws `InvalidArgumentException` with
`ORM table name cannot be empty.` for an empty name.

```php
public private(set) string $name
```

The table name.

### Key

`#[Attribute(Attribute::TARGET_PROPERTY)]`. `Key` extends `Column`, so a key is a column with fixed
flags, and its properties are those of [Column](#column-1).

```php
__construct (null|string $name = null, bool $generated = true)
```

Maps the primary key. `$name` is the column, `null` for the property name. `$generated` is copied
to `generated`, and `insert` is its opposite: a generated key is never inserted, an
application-assigned one is. `update` and `nullable` are always `false`. Throws the
`InvalidArgumentException` of `Column` for an empty name.

### Column

`#[Attribute(Attribute::TARGET_PROPERTY)]`

```php
__construct (
   null|string $name = null,
   bool $insert = true,
   bool $update = true,
   bool $generated = false,
   bool $nullable = false
)
```

Maps one stored property. Throws `InvalidArgumentException` with `ORM column name cannot be empty.`
for an empty name.

```php
public private(set) null|string $name
```

The column, or `null` when the property name is the column.

```php
public private(set) bool $insert
```

Whether an INSERT writes the column.

```php
public private(set) bool $update
```

Whether an UPDATE writes the column.

```php
public private(set) bool $generated
```

Whether the database fills the column when the property holds `null`: INSERT and UPDATE then leave
it out, and a row may omit it.

```php
public private(set) bool $nullable
```

Whether a row may omit the column. Cursor pagination refuses to order by a `nullable` column.

### Relation

`#[Attribute(Attribute::TARGET_PROPERTY)]`, once per property.

```php
__construct (
   Relations $Type,
   string $target,
   string $local,
   string $foreign,
   null|string $table = null,
   null|string $pivotLocal = null,
   null|string $pivotForeign = null,
   null|string $name = null,
   bool $lazy = false
)
```

Maps one relation property. Throws `InvalidArgumentException` with
`ORM relation keys cannot be empty.` for an empty `$local` or `$foreign`, and with
`ORM relation name cannot be empty.` for an empty `$name`.

```php
public private(set) Relations $Type
```

The kind of relation.

```php
public private(set) string $target
```

The class of the related entity.

```php
public private(set) string $local
```

The key on this entity, by property or column name.

```php
public private(set) string $foreign
```

The key on the target, by property or column name.

```php
public private(set) null|string $table
```

The pivot table of a `BelongsToMany`.

```php
public private(set) null|string $pivotLocal
```

The pivot column that holds this entity's `local` value.

```php
public private(set) null|string $pivotForeign
```

The pivot column that holds the target's `foreign` value.

```php
public private(set) null|string $name
```

The name passed to the attribute, or `null`: the model then names the relation after its property.

```php
public private(set) bool $lazy
```

Whether hydration installs a lazy wrapper instead of leaving the relation to `load()`.

### Relations

`Bootgly\ADI\Databases\SQL\Model\Auxiliaries\Relations`, an enum with no backing values.

```php
case BelongsTo;
```

This entity holds the key of one target.

```php
case BelongsToMany;
```

Many targets, linked to this entity through a pivot table.

```php
case HasMany;
```

Many targets hold this entity's key.

```php
case HasOne;
```

One target holds this entity's key.

### Auxiliaries

`Bootgly\ADI\Databases\SQL\Model\Auxiliaries`, the registry of the model's auxiliary enums.

```php
static check (string $class): bool
```

Whether `$class` is one of the model's auxiliary enums.

```php
const array ENUMS
```

The auxiliary enum classes: `Relations`.
