# Defining tables

Inside `$Schema->create(...)` and `$Schema->alter(...)` you get a `$Table` — a `Blueprint` — to
describe your columns, keys and foreign keys. This page is a cookbook: find what you need, copy it.

Every column is `$Table->add('name', Types::Something)` plus optional modifiers.

- **Methods chain** (`->limit()`, `->constrain()`, …) — they return the column.
- **`nullable` and `default` are properties** — you *assign* them. An assignment ends the
  statement, so it comes **last** (or capture the column in a variable):

```php
$Table->add('active', Types::Boolean)->default = true;     // ok: assignment last
$Table->add('bio', Types::Text)->nullable = true;          // ok

$Email = $Table->add('email', Types::String)->limit(190);  // capture, then assign
$Email->nullable = true;
```

**Columns are `NOT NULL` by default.** Set `->nullable = true` to allow `NULL`.

## The columns you need most

```php
use Bootgly\ADI\Databases\SQL\Builder\Expression;
use Bootgly\ADI\Databases\SQL\Schema\Auxiliaries\Defaults;
use Bootgly\ADI\Databases\SQL\Schema\Auxiliaries\Keys;
use Bootgly\ADI\Databases\SQL\Schema\Auxiliaries\Types;
use Bootgly\ADI\Databases\SQL\Schema\Blueprint;

$Schema->create('users', function (Blueprint $Table): void {
   // Auto-incrementing primary key
   $Table->add('id', Types::BigInteger)->generate()->constrain(Keys::Primary);

   // Text with a length limit, must be unique
   $Table->add('email', Types::String)->limit(190)->constrain(Keys::Unique);

   // Free text, optional (allows NULL)
   $Table->add('bio', Types::Text)->nullable = true;

   // Boolean with a default
   $Table->add('active', Types::Boolean)->default = true;

   // Money / fixed decimal: 10 digits, 2 after the point, default 0
   $Table->add('balance', Types::Decimal)->size(10, 2)->default = 0;

   // Timestamp defaulting to "now"
   $Table->add('created_at', Types::Timestamp)->default = new Expression('CURRENT_TIMESTAMP');
});
```

### Default values

`default` takes a literal (`bool`, `int`, `float`, `string` or `null`), a `Stringable`, or an
`Expression`:

```php
$Table->add('status', Types::String)->limit(20)->default = 'draft';        // DEFAULT 'draft'
$Table->add('settings', Types::Json)->default = new Expression("('{}')");  // DEFAULT ('{}')
```

- A string, or the text of a `Stringable`, is written as a quoted literal, its `'` doubled.
- An `Expression` is written as is: it is trusted raw SQL, so never build one from user input
  (see **[Trusted expressions](/manual/ADI/Databases/SQL/Builder/Composing/overview/#trusted-expressions)**).
  On MySQL, a `Text`, `Json` or `JsonB` column takes a default only this way, in parentheses as
  above — a literal fails with `1101: BLOB, TEXT, GEOMETRY or JSON column '…' can't have a default value`.
- `->default = null` writes `DEFAULT NULL`, so make the column `nullable` too: MySQL refuses
  `NOT NULL DEFAULT NULL` (`1067: Invalid default value`), and on PostgreSQL and SQLite every
  insert that leaves the column out fails.
- `Defaults::None` takes back a default you assigned: no `DEFAULT` clause is written.
- Any other value throws at the assignment:
  `InvalidArgumentException: Schema column default must be scalar, Stringable or Expression.` A
  float must be finite: `NAN`, `INF` and `-INF` pass the assignment, and `create()`/`alter()`
  throws `InvalidArgumentException: Schema default float must be finite.`

> [!WARNING]
> For now, MySQL reads a backslash in a string default as an escape: a default of `'C:\temp'` is
> stored with a tab in place of `\t`, and a default that ends in `\` breaks the statement
> (`1064`). PostgreSQL and SQLite store the backslash as written.

### Primary keys and generated ids

`constrain(Keys::Primary)` makes the column the primary key and `constrain(Keys::Unique)` adds a
`UNIQUE` constraint. `generate()` lets the engine number the rows:

| Engine | `->generate()->constrain(Keys::Primary)` on a `BigInteger` |
|--------|-------------------------------------------------------------|
| PostgreSQL | `BIGINT GENERATED BY DEFAULT AS IDENTITY NOT NULL PRIMARY KEY` |
| MySQL | `BIGINT NOT NULL AUTO_INCREMENT PRIMARY KEY` |
| SQLite | `INTEGER PRIMARY KEY AUTOINCREMENT` |

- Generate integer columns only: PostgreSQL refuses other types
  (`identity column type must be smallint, integer, or bigint`), MySQL too (`1063`), and SQLite
  turns a generated primary key into `INTEGER` whatever type you gave.
- A generated column takes no default: PostgreSQL answers `both default and identity specified`,
  MySQL `1067`, and SQLite leaves the default out.
- An insert may still give the id itself. On PostgreSQL that leaves the identity behind — see
  **[Explicit keys and identity sequences](/manual/ADI/Databases/SQL/Schema/Dialects/overview/#explicit-keys-and-identity-sequences)**.
- `constrain()` marks this one column: `Keys::Primary` on two columns gives two `PRIMARY KEY`
  clauses, and every engine refuses the table. A composite primary key needs a raw statement.

> [!WARNING]
> For now, SQLite ignores `generate()` on a column that is not the primary key: the column is
> created as a plain `NOT NULL` integer with nothing to fill it, so every insert that leaves it out
> fails with `NOT NULL constraint failed`. On SQLite, generate the primary key only.

### Checks

```php
$Table->add('age', Types::Integer)->check('age >= 0');  // "age" INTEGER NOT NULL CHECK (age >= 0)
```

`check()` adds `CHECK (…)` to the column; call it again for another one. The expression is raw SQL
written into the statement as is — a string or an `Expression` alike — so never build it from user
input. PostgreSQL, MySQL and SQLite all enforce it.

### Linking to another table (foreign key)

Declare a foreign key at table level, with `$Table->reference()` — the referenced column defaults
to `id`:

```php
use Bootgly\ADI\Databases\SQL\Schema\Auxiliaries\References;

$Schema->create('members', function (Blueprint $Table): void {
   $Table->add('id', Types::BigInteger)->generate()->constrain(Keys::Primary);
   $Table->add('team_id', Types::BigInteger)->nullable = true;

   $Table->reference('team_id', 'teams')
      ->delete(References::SetNull)    // delete the team → its members keep no team
      ->update(References::Cascade);   // change the team's id → follow it
});
// … CONSTRAINT "members_team_id_teams_fk" FOREIGN KEY ("team_id") REFERENCES "teams" ("id") ON DELETE SET NULL ON UPDATE CASCADE
```

The constraint is named `<table>_<column>_<referenced table>_fk` — shortened past 63 bytes, see
**[Generated names](/manual/ADI/Databases/SQL/Schema/overview/#generated-names)** — unless you pass
`name:`. In `create()` it works on every engine; in `alter()` it compiles `ADD CONSTRAINT` on
PostgreSQL and MySQL, and SQLite refuses it
(`InvalidArgumentException: SQLite schema dialect lacks capability: AddConstraint.`).

What happens to the rows that point at a deleted row, or at a row whose key changes:

| Case | SQL | The engine… |
|------|-----|-------------|
| `Cascade` | `CASCADE` | deletes those rows too, or updates them to the new key |
| `SetNull` | `SET NULL` | sets their column to `NULL` — declare it `nullable` |
| `SetDefault` | `SET DEFAULT` | sets their column to its default, which must match an existing row, on PostgreSQL and SQLite. MySQL accepts the clause but refuses the change, as with `NoAction` |
| `Restrict` | `RESTRICT` | refuses the change |
| `NoAction` | `NO ACTION` | refuses the change. It is also what you get without a rule |

A column can also carry its foreign key inline:

```php
$Table->add('team_id', Types::BigInteger)->reference('teams');  // "team_id" BIGINT NOT NULL REFERENCES "teams" ("id")
```

The inline form takes no `delete()`/`update()` rule. PostgreSQL and SQLite keep it on the column,
and the engine names the constraint itself — `members_team_id_fkey` on PostgreSQL. MySQL ignores a
`REFERENCES` inside a column definition, so there Bootgly compiles the key as a table-level
constraint, after the columns in `create()` and right after the `ADD COLUMN` in `alter()`:

```sql
CONSTRAINT `members_team_id_teams_fk` FOREIGN KEY (`team_id`) REFERENCES `teams` (`id`)
```

The inline `name:` is written on MySQL only. When a later migration may have to drop the key, use
`$Table->reference()`: on every engine it takes the rules and writes the name.

Declare each foreign key once, inline or with `$Table->reference()`. For now, a key declared both
ways becomes two constraints on PostgreSQL and SQLite. MySQL keeps one when both point at the same
column under the same name and the inline one adds no rule; any other pair sharing the generated
name fails with `1826: Duplicate foreign key constraint name '…'`.

On MySQL the key holds its column and its index, which a `Down` may have to work around:

- `remove()` of the column fails with
  `1828: Cannot drop column 'team_id': needed in a foreign key constraint 'members_team_id_teams_fk'`.
  Call `$Schema->unconstrain('members', 'members_team_id_teams_fk')` first. PostgreSQL drops the
  key with the column, and its inline key has another name, so there that `unconstrain()` finds
  nothing to drop.
- `unindex()` of an index that starts with the key's column fails with
  `1553: Cannot drop index '…': needed in a foreign key constraint`: MySQL enforces the key with that
  index. Drop the key first, or drop the whole table.
- The column needs the referenced column's exact type: an `Integer` pointing at a `BigInteger` id
  fails with `3780: Referencing column 'team_id' and referenced column 'id' in foreign key
  constraint '…' are incompatible.` PostgreSQL accepts that pair.

> [!NOTE]
> Up to Bootgly 1.0.13, the inline form created no foreign key on MySQL. A database migrated with
> those versions still lacks the keys; running the same migrations again on a fresh database
> creates them. To add them to the old database, write a new migration with `$Table->reference()`
> and a `name:` different from the generated one — with the generated name, a fresh install, where
> the inline key already exists, fails with `1826: Duplicate foreign key constraint name`.

### Adding an index

Create an index with `$Schema->index()`, beside the table rather than inside its blueprint — see
**[Create a table with its indexes](/manual/ADI/Databases/SQL/Schema/overview/#create-a-table-with-its-indexes)**.

For now, `$Table->index()` inside a `create()`/`alter()` closure has no effect: the index never
reaches the DDL, and an `alter()` with only an index throws
`InvalidArgumentException: ALTER TABLE requires at least one schema action.`

### Picking a column type

| You want… | Use |
|-----------|-----|
| Whole number id / counter | `Types::BigInteger`, `Types::Integer` |
| Short text (names, emails) | `Types::String` + `->limit(n)` |
| Long text | `Types::Text` |
| True / false | `Types::Boolean` |
| Money / exact decimal | `Types::Decimal` + `->size(p, s)` |
| Fractional number | `Types::Float` |
| Date / time | `Types::Date`, `Types::Time`, `Types::Timestamp` |
| Instant with time zone | `Types::Timestamptz` |
| JSON document | `Types::Json`, `Types::JsonB` |
| UUID | `Types::Uuid` |

If you don't pass a type, you get `Types::Text`. A `String` without `limit()` is `VARCHAR(255)`.
The SQL each type compiles to, per engine, is in
**[Column types per engine](/manual/ADI/Databases/SQL/Schema/Dialects/overview/#column-types-per-engine)**.
Two of them behave differently from one engine to the next:

- **Always give a `Decimal` its `size()`.** Without it, MySQL's `DECIMAL` keeps no digits after the
  point — 12.75 is stored as 13. SQLite ignores the size and stores a fraction as a float, so keep
  money in integer cents there.
- **Only PostgreSQL tells `Timestamp` from `Timestamptz`**: `TIMESTAMP` is a date and time with no
  zone, `TIMESTAMPTZ` an instant. MySQL compiles both to `TIMESTAMP`, which it converts from the
  session time zone to UTC and back, and which holds 1970 to 2038 only. SQLite stores both as
  `TEXT`.

## Changing a table later

In an `alter()`, `add()` adds a new column, `change()` edits one that exists, `remove()` drops one
and `rename()` renames one. On PostgreSQL:

```php
$Schema->alter('users', function (Blueprint $Table): void {
   $Table->add('phone', Types::String)->limit(20)->nullable = true; // new column

   $Email = $Table->change('email', Types::String)->limit(320);
   $Email->nullable = false;                                          // TYPE VARCHAR(320), SET NOT NULL

   $Active = $Table->change('active', Types::Boolean);
   $Active->nullable = true;                                          // DROP NOT NULL
   $Active->default  = false;                                         // SET DEFAULT

   $Table->change('created_at', Types::Timestamp)->default = Defaults::None; // DROP DEFAULT

   $Table->remove('legacy');                                          // drop a column
});

// A rename goes in an alter() of its own.
$Schema->alter('users', function (Blueprint $Table): void {
   $Table->rename('bio', 'profile');
});
```

```sql
ALTER TABLE "users" ADD COLUMN "phone" VARCHAR(20), ALTER COLUMN "email" TYPE VARCHAR(320), ALTER COLUMN "email" SET NOT NULL, ALTER COLUMN "active" DROP NOT NULL, ALTER COLUMN "active" SET DEFAULT FALSE, ALTER COLUMN "created_at" DROP DEFAULT, DROP COLUMN "legacy"
ALTER TABLE "users" RENAME COLUMN "bio" TO "profile"
```

**A rename does not share an `alter()` on PostgreSQL.** Its `ALTER TABLE` has two disjoint forms —
a comma-separated list of actions, and one rename — so a rename beside anything else, another
rename included, is a syntax error rather than a statement, and Bootgly refuses that blueprint
instead of compiling it. MySQL accepts the combination and compiles it as written. Keeping a rename
in its own `alter()` works on every engine.

The engines differ here: MySQL refuses the `active` change above, since it has no action that
changes only nullability, and SQLite has no `change()` at all, nor more than one action per
`alter()`. An action the engine lacks throws when the statement compiles, before anything is sent
— see
**[What each engine can do](/manual/ADI/Databases/SQL/Schema/Dialects/overview/#what-each-engine-can-do)**.
The builder does not check everything the server checks, though: a definition the server rejects,
such as a default the column type cannot hold, compiles and fails when it runs.

### What a change changes

`change()` always names the column's type, but whether the type is changed depends on what else you
do with the `Change` it returns:

- Nothing else — `$Table->change('age', Types::BigInteger)` — changes the type:
  `ALTER COLUMN "age" TYPE BIGINT` on PostgreSQL.
- Assign `nullable`, `default` or `Defaults::None` and the change is about that attribute only:
  the type you named is not applied.
- Call `limit()`, `size()`, `cast()` or `generate()` too — before or after the assignments — and
  the type changes as well.

`limit()` sets the length of a `String` and `size()` the precision and scale of a `Decimal`; on
other types their arguments are not used. For now, retyping one of those other types while you
also change its nullability or default still takes one of the four calls — `size()` on an
`Integer` going to `BigInteger`, say, or `cast()` on PostgreSQL:

```php
$Age = $Table->change('age', Types::BigInteger)->size(20);  // size() keeps the type change
$Age->nullable = false;
$Age->default  = 0;
// PostgreSQL: ALTER COLUMN "age" TYPE BIGINT, ALTER COLUMN "age" SET NOT NULL, ALTER COLUMN "age" SET DEFAULT 0
// MySQL:      MODIFY COLUMN `age` BIGINT NOT NULL DEFAULT 0
```

`cast()` is PostgreSQL's `USING` — how to turn the old values into the new type:

```php
$Table->change('legacy_id', Types::BigInteger)->cast(new Expression('legacy_id::bigint'));
// ALTER COLUMN "legacy_id" TYPE BIGINT USING legacy_id::bigint
```

MySQL and SQLite refuse a cast (`schema dialect lacks capability: AlterColumnUsing.`).

### On MySQL, a type change carries the whole column

`MODIFY COLUMN` restates a column's entire definition, and anything the statement leaves out
reverts silently — the `NOT NULL`, the `DEFAULT`, the `AUTO_INCREMENT`, the `COMMENT`. So a change
that names only a type is refused rather than compiled. State on the change everything the column
must keep:

- `nullable` — always: a type change without it is refused;
- `default` — again, if the column has one: a `MODIFY COLUMN` without `DEFAULT` drops it;
- `generate()` — for an `AUTO_INCREMENT` key.

In one `alter()`, these two changes compile to one `ALTER TABLE` statement, with one
`MODIFY COLUMN` each:

```php
$Change = $Table->change('email', Types::String)->limit(320);
$Change->nullable = false;
$Change->default  = '';
// MODIFY COLUMN `email` VARCHAR(320) NOT NULL DEFAULT ''

$Key = $Table->change('id', Types::BigInteger)->generate();  // keep the identity
$Key->nullable = false;
// MODIFY COLUMN `id` BIGINT NOT NULL AUTO_INCREMENT
```

Without `generate()`, retyping an identity column drops it, and the next insert dies with
`1364: Field 'id' doesn't have a default value`. On PostgreSQL the identity survives a type
change on its own, so stating it there costs nothing and keeps the migration portable.

A `COMMENT` or `COLLATE` the column carries is not part of the blueprint, so it cannot be
restated this way — reapply it with a raw statement after the change.

A change that sets only a default keeps a lighter statement — `ALTER COLUMN … SET DEFAULT` or
`DROP DEFAULT` — while one that sets only nullability is refused, since MySQL has no such action.
These shapes are refused before anything is sent:

| The change… | Refused with |
|-------------|--------------|
| names only a type | `MySQL cannot retype the column "<name>" on its own: MODIFY COLUMN restates the whole definition, …` |
| sets `nullable` without changing the type | `MySQL schema dialect lacks capability: AlterColumnNullability.` |
| calls `cast()` | `MySQL schema dialect lacks capability: AlterColumnUsing.` |
| changes the type of a `Text`, `Json` or `JsonB` column and gives it a literal default | `MySQL cannot give the column "<name>" a literal default: BLOB, TEXT and JSON columns take one only as an expression, as in DEFAULT (JSON_OBJECT()).` |
| calls `generate()` and sets a default | `MySQL cannot give the generated column "<name>" a default: an AUTO_INCREMENT column supplies its own values.` |
| calls `generate()` with `nullable = true` | `MySQL cannot make the column "<name>" both AUTO_INCREMENT and nullable: a generated column is always NOT NULL.` |
| calls `generate()` on a type other than `Integer`, `BigInteger` or `Boolean` | `MySQL cannot make the column "<name>" AUTO_INCREMENT as a <Type>: only the integer types carry one.` |
| sets `nullable = false` and `default = null` | `MySQL cannot make the column "<name>" NOT NULL while it defaults to NULL.` |

Each is an `InvalidArgumentException`. For now, the `Text`, `Json` and `JsonB` check runs on a
type change only: a change that sets only a default —
`$Table->change('bio', Types::Text)->default = 'hi'` — compiles to `ALTER COLUMN … SET DEFAULT`,
and the server refuses it with `1101`. Nor do these checks cover `add()`: the same definitions
written with it — in `create()` or `alter()` — compile, and the server rejects them when they run
(`1067`, `1063`, `1101`). A default the type cannot hold, such as a string on an `Integer` column,
compiles on every path, `change()` included, and fails on the server too.

## Tip: typed names with enums

Table and column names accept a string, but also a backed enum — handy to avoid typos across
migrations:

```php
enum Tables: string  { case Users = 'users'; }
enum Columns: string { case Id = 'id'; case Email = 'email'; }

$Schema->create(Tables::Users, function (Blueprint $Table): void {
   $Table->add(Columns::Id, Types::BigInteger)->generate()->constrain(Keys::Primary);
   $Table->add(Columns::Email, Types::String)->limit(190)->constrain(Keys::Unique);
});
```

## Reference

The classes below are in `Bootgly\ADI\Databases\SQL\Schema` (`Blueprint`) and
`Bootgly\ADI\Databases\SQL\Schema\Blueprint` (the rest). Their public properties are what a
schema dialect reads to compile; they are read-only outside the class, except `nullable` and
`default`.

### Blueprint

```php
__construct (BackedEnum|Stringable|string $Table)
```

Starts the blueprint of `$Table`. `create()` and `alter()` build one for their closure.

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

The table name, as given (a backed enum's `value`, a `Stringable`'s text).

```php
public private(set) array $columns = []
```

The `Column` of each `add()`, in call order.

```php
public private(set) array $changes = []
```

The `Change` of each `change()`, in call order.

```php
public private(set) array $drops = []
```

The names given to `remove()`.

```php
public private(set) array $references = []
```

The `Reference` of each table-level `reference()`.

```php
public private(set) array $renames = []
```

The `Rename` of each `rename()`.

```php
add (BackedEnum|Stringable|string $Column, Types $Type = Types::Text): Column
```

Adds a column — `ADD COLUMN` in `alter()` — and returns it to modify.

```php
remove (BackedEnum|Stringable|string $Column): self
```

`alter()` only — drops a column (`DROP COLUMN`). Returns the blueprint.

```php
change (BackedEnum|Stringable|string $Column, Types $Type): Change
```

`alter()` only — changes a column that exists, and returns the `Change`. See
[What a change changes](#what-a-change-changes).

```php
rename (BackedEnum|Stringable|string $From, BackedEnum|Stringable|string $To): self
```

`alter()` only — renames a column (`RENAME COLUMN`). On PostgreSQL it must be the only action of
its `alter()`. Returns the blueprint.

```php
index (BackedEnum|Stringable|string|array $Columns, null|string $name = null, bool $unique = false): Index
```

Builds the `Index` value that `$Schema->index()` compiles. **Inside a `create()`/`alter()`
closure it currently has no effect** — see [Adding an index](#adding-an-index).

```php
reference (BackedEnum|Stringable|string $Column, BackedEnum|Stringable|string $Table, BackedEnum|Stringable|string $Reference = 'id', null|string $name = null): Reference
```

Adds a table-level foreign key from `$Column` to `$Table`.`$Reference` and returns it, for
`delete()`/`update()`. Without `$name`, the name is generated.

### Column

```php
__construct (string $table, string $name, Types $Type)
```

A column definition. `add()` creates it.

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

The table it belongs to.

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

The column name.

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

The portable type it compiles to.

```php
public bool $nullable
```

`false` until you assign `true`: the column is `NOT NULL` unless you do.

```php
public null|bool|float|int|string|Stringable|Defaults $default
```

The default — see [Default values](#default-values). Reading it gives `null` when none is set.
Assigning `Defaults::None` removes the one you set. Any other type throws
`InvalidArgumentException: Schema column default must be scalar, Stringable or Expression.`

```php
public private(set) bool $defaulted = false
```

Whether a default is set — `true` after an assignment, `null` included, `false` after
`Defaults::None`.

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

Whether `generate()` was called.

```php
public private(set) bool $primary = false
```

Whether `constrain(Keys::Primary)` was called.

```php
public private(set) bool $unique = false
```

Whether `constrain(Keys::Unique)` was called.

```php
public private(set) int $length = 255
```

The `String` length `limit()` sets.

```php
public private(set) int $precision = 0
```

The `Decimal` precision `size()` sets; `0` means none.

```php
public private(set) int $scale = 0
```

The `Decimal` scale `size()` sets.

```php
public private(set) null|Reference $Reference = null
```

The inline foreign key `reference()` sets.

```php
public private(set) array $checks = []
```

The `check()` expressions, strings or `Expression`s, in call order.

```php
limit (int $length): self
```

Sets the length of a `String` column: `VARCHAR($length)`. Other types, and SQLite, do not use it.

```php
size (int $precision, int $scale = 0): self
```

Sets the precision and scale of a `Decimal` column: `NUMERIC(p, s)` on PostgreSQL, `DECIMAL(p, s)`
on MySQL. Other types, and SQLite, do not use them.

```php
generate (): self
```

Makes the engine generate the values — see [Primary keys and generated ids](#primary-keys-and-generated-ids).

```php
constrain (Keys $Key): self
```

`Keys::Primary` writes `PRIMARY KEY` and `Keys::Unique` writes `UNIQUE`; call it once for each
key the column needs.

```php
check (string|Expression $expression): self
```

Adds `CHECK ($expression)`, written as is.

```php
reference (BackedEnum|Stringable|string $Table, BackedEnum|Stringable|string $Column = 'id', null|string $name = null): self
```

Adds an inline `REFERENCES $Table ($Column)` to the column. MySQL compiles it as a table-level
constraint and is the only engine that writes `$name` — see
[Linking to another table](#linking-to-another-table-foreign-key).

### Change

A `Change` is what `Blueprint::change()` returns: it reads `nullable` and `default` like a
`Column`, but `nullable` has a third state, `null`.

```php
__construct (string $name, Types $Type)
```

A change of the column `$name` to `$Type`. `change()` creates it.

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

The column it changes.

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

The type it names.

```php
public null|bool $nullable
```

`null` leaves nullability as it is, `true` allows `NULL` (`DROP NOT NULL`), `false` requires a
value (`SET NOT NULL`). Assigning `true` or `false` makes the change keep the column's type, unless
`limit()`, `size()`, `cast()` or `generate()` is called too, before or after.

```php
public null|bool|float|int|string|Stringable|Defaults $default
```

The new default (`SET DEFAULT`); `Defaults::None` drops the existing one (`DROP DEFAULT`). Like
`nullable`, an assignment makes the change keep the column's type unless one of the four calls is
made too. Any other type throws
`InvalidArgumentException: Schema change default must be scalar, Stringable or Expression.`

```php
public private(set) bool $defaulted = false
```

Whether a new default was assigned.

```php
public private(set) bool $dropped = false
```

Whether `Defaults::None` was assigned.

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

Whether `generate()` was called.

```php
public private(set) bool $typed = true
```

Whether the change applies the type — see [What a change changes](#what-a-change-changes).

```php
public private(set) null|string|Expression $expression = null
```

The `USING` expression `cast()` sets.

```php
public private(set) int $length = 255
```

The `String` length `limit()` sets.

```php
public private(set) int $precision = 0
```

The `Decimal` precision `size()` sets; `0` means none.

```php
public private(set) int $scale = 0
```

The `Decimal` scale `size()` sets.

```php
limit (int $length): self
```

Sets the `String` length and keeps the type change.

```php
size (int $precision, int $scale = 0): self
```

Sets the `Decimal` precision and scale and keeps the type change.

```php
generate (): self
```

States that the column generates its values, and keeps the type change. MySQL restates
`AUTO_INCREMENT`; PostgreSQL keeps the identity anyway.

```php
cast (string|Expression $expression): self
```

Sets PostgreSQL's `USING` expression, raw SQL written as is, and keeps the type change. MySQL and
SQLite refuse it.

### Reference (foreign key)

```php
__construct (string $origin, string $source, string $table, string $column = 'id', null|string $name = null)
```

A foreign key from `$origin`.`$source` to `$table`.`$column`. `Blueprint::reference()` and
`Column::reference()` create it.

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

The table that holds the key.

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

The column that holds the key.

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

The referenced table.

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

The referenced column.

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

The constraint name: the one passed, or `<origin>_<source>_<table>_fk`, dots turned into `_` and
shortened past 63 bytes.

```php
public private(set) null|References $Delete = null
```

The `ON DELETE` rule, if set.

```php
public private(set) null|References $Update = null
```

The `ON UPDATE` rule, if set.

```php
delete (References $Reference): self
```

Sets the `ON DELETE` rule.

```php
update (References $Reference): self
```

Sets the `ON UPDATE` rule.

### Index

```php
__construct (string $table, array $columns, null|string $name = null, bool $unique = false)
```

An index over `$columns`. `Blueprint::index()` creates it, for `$Schema->index()`.

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

The indexed table.

```php
public private(set) array $columns
```

The indexed columns, in order.

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

The index name: the one passed, or `<table>_<columns>_<index|unique>`, shortened past 63 bytes.

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

Whether it is a unique index.

### Rename

```php
__construct (string $from, string $to)
```

A column rename. `Blueprint::rename()` creates it.

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

The current column name.

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

The new column name.

### Identifier

```php
public const int LIMIT = 63
```

The longest generated name, in bytes.

```php
static limit (string $name): string
```

Returns `$name` when it fits in `LIMIT` bytes; otherwise its first 54 bytes, `_` and the first 8
hex digits of its SHA-256 hash. `Index` and `Reference` pass their generated names through it.

### Auxiliary enums

Namespace `Bootgly\ADI\Databases\SQL\Schema\Auxiliaries`.

| Enum | Case | Means |
|------|------|-------|
| `Types` | `BigInteger`, `Integer` | whole numbers, 64 and 32 bits |
| | `Boolean` | true / false |
| | `Decimal` | exact decimal, shaped by `size()` |
| | `Float` | double-precision floating point |
| | `String` | text up to `limit()` characters |
| | `Text` | text of any length |
| | `Date`, `Time` | a date; a time of day |
| | `Timestamp` | a date and time with no zone |
| | `Timestamptz` | a date and time with zone — an instant |
| | `Json`, `JsonB` | a JSON document; `JsonB` is PostgreSQL's binary form |
| | `Uuid` | a UUID |
| `Keys` | `Primary`, `Unique` | `PRIMARY KEY`, `UNIQUE` |
| `References` | `Cascade`, `NoAction`, `Restrict`, `SetDefault`, `SetNull` | the rules in [Linking to another table](#linking-to-another-table-foreign-key) |
| `Defaults` | `None` | no default: clears a default, or drops one in a `change()` |
| `Directions` | `Up`, `Down` | the direction the migration Runner applies a migration in; no public method takes it |
| `Capabilities` | `AddConstraint`, `AlterColumnDefault`, `AlterColumnNullability`, `AlterColumnType`, `AlterColumnUsing`, `DropColumn`, `DropConstraint`, `MultiActionAlter`, `RenameColumn` | what a dialect can compile — see **[What each engine can do](/manual/ADI/Databases/SQL/Schema/Dialects/overview/#what-each-engine-can-do)** |

The SQL each `Types` case compiles to, per engine, is in
**[Column types per engine](/manual/ADI/Databases/SQL/Schema/Dialects/overview/#column-types-per-engine)**.
`Bootgly\ADI\Databases\SQL\Schema\Auxiliaries::ENUMS` lists the six enum classes.
