# Schema Builder

The Schema Builder is **how you shape your database**. You call it from inside a migration to
create, change or drop tables and indexes — never raw SQL — and it writes the SQL your engine
(PostgreSQL, MySQL or SQLite) expects.

Every method only **compiles**: it returns a `Query` — the statement text and its parameters —
and touches no database. The migration Runner runs what a migration returns; outside a migration,
you hand the query to `$Database->query()` yourself.

> New here? Follow the **[Database migrations](/guide/database-migrations/overview/)** guide
> first — it shows the whole flow. This page is what you do inside `Up`/`Down`.

## The five things you'll do

Inside a migration you get a `$Schema`. With it you almost always do one of these:

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

// 1. Create a table
$Schema->create('users', function (Blueprint $Table): void {
   $Table->add('id', Types::BigInteger)->generate()->constrain(Keys::Primary);
   $Table->add('email', Types::String)->limit(190)->constrain(Keys::Unique);
   $Table->add('active', Types::Boolean)->default = true;
   $Table->add('created_at', Types::Timestamp)->default = new Expression('CURRENT_TIMESTAMP');
});

// 2. Change it
$Schema->alter('users', function (Blueprint $Table): void {
   $Table->add('bio', Types::Text)->nullable = true;  // a new nullable column
});

// 3. Index a column
$Schema->index('users', 'created_at');               // users_created_at_index

// 4. Rename it
$Schema->rename('users', 'members');

// 5. Drop it
$Schema->drop('members');
```

Each call compiles one statement. A migration's `Up` or `Down` returns one of them, or an array of
them, which the Runner runs in order.

> `nullable` and `default` are **properties**, not methods: you assign them
> (`->default = true`, `->nullable = true`), you don't chain them. To drop an existing
> default in `alter`, assign `Defaults::None`. Details in
> **[Defining tables](/manual/ADI/Databases/SQL/Schema/Blueprint/overview/)**.

**What does it produce?** For the `create()` above, PostgreSQL gets:

```sql
CREATE TABLE "users" ("id" BIGINT GENERATED BY DEFAULT AS IDENTITY NOT NULL PRIMARY KEY, "email" VARCHAR(190) NOT NULL UNIQUE, "active" BOOLEAN NOT NULL DEFAULT TRUE, "created_at" TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP)
```

MySQL and SQLite get their own spelling of the same table — see
**[Dialects](/manual/ADI/Databases/SQL/Schema/Dialects/overview/)**. How you describe columns (the
`$Table->add(...)` part) lives in **[Defining tables](/manual/ADI/Databases/SQL/Schema/Blueprint/overview/)**.

## Create a table with its indexes

An index is not part of the table definition: create it beside the table, with
`$Schema->index()`, in the same migration. `Up` returns both statements as an array — they run in
order, and on PostgreSQL and SQLite inside the migration's transaction:

```php
use Bootgly\ADI\Databases\SQL\Schema\Auxiliaries\Keys;
use Bootgly\ADI\Databases\SQL\Schema\Auxiliaries\Types;
use Bootgly\ADI\Databases\SQL\Schema\Blueprint;
use Bootgly\ADI\Databases\SQL\Schema\Migrating;
use Bootgly\ADI\Databases\SQL\Schema\Migration;

return new Migration(
   Up: fn (Migrating $Schema) => [
      $Schema->create('posts', function (Blueprint $Table): void {
         $Table->add('id', Types::BigInteger)->generate()->constrain(Keys::Primary);
         $Table->add('author_id', Types::BigInteger);
         $Table->add('slug', Types::String)->limit(190);
         $Table->add('published_at', Types::Timestamp)->nullable = true;
      }),
      $Schema->index('posts', 'slug', unique: true),           // posts_slug_unique
      $Schema->index('posts', ['author_id', 'published_at']),  // posts_author_id_published_at_index
   ],
   Down: fn (Migrating $Schema) => $Schema->drop('posts')
);
```

A list of columns makes one composite index, in the order given. Without `name:`, the index is
named after the table, its columns and `index` or `unique` — see [Generated names](#generated-names).
Dropping a table drops its indexes, so `Down` only drops the table.

> [!WARNING]
> For now, `$Table->index()` inside the `create()` closure has no effect: it builds the index
> description and discards it, so the table is created without the index — and without an error.
> Return `$Schema->index()` beside the `create()`, as above.

A column's `constrain(Keys::Unique)` also makes the engine keep a unique index, but under a name
the engine picks — `users_email_key` on PostgreSQL, `email` on MySQL, `sqlite_autoindex_users_1`
on SQLite. When a later migration may have to drop it, prefer `index(..., unique: true)`, whose
name you know.

### Index a table that exists

In a later migration, `index()` alone is the change, and `unindex()` — which takes the index
name — undoes it:

```php
return new Migration(
   Up: fn (Migrating $Schema) => $Schema->index('posts', ['author_id', 'slug']),
   Down: fn (Migrating $Schema) => $Schema->unindex('posts', 'posts_author_id_slug_index')
);
```

`CREATE INDEX` is compiled without `IF NOT EXISTS`, so creating an index whose name is taken
fails.

## Change a table

`alter()` compiles one `ALTER TABLE` from everything its closure asks for: new columns (`add()`),
changed ones (`change()`), renamed ones (`rename()`), dropped ones (`remove()`) and foreign keys
(`reference()`). How much fits in one `alter()` depends on the engine:

- **PostgreSQL** joins the actions with commas — except a column rename, which goes in an
  `alter()` of its own. A rename beside any other action, a second rename included, throws
  `InvalidArgumentException: PostgreSQL renames a column in an ALTER TABLE of its own: give each rename its own alter(), with no other action beside it.`
- **MySQL** joins every action, renames included.
- **SQLite** takes one action per `alter()`. A second one throws
  `InvalidArgumentException: SQLite schema dialect lacks capability: MultiActionAlter.`

On PostgreSQL and MySQL:

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

$Schema->alter('users', function (Blueprint $Table): void {
   $Table->add('team_id', Types::BigInteger)->nullable = true;
   $Table->remove('legacy');
   $Table->reference('team_id', 'teams')
      ->delete(References::SetNull)
      ->update(References::Cascade);
});
// ALTER TABLE "users" ADD COLUMN "team_id" BIGINT, DROP COLUMN "legacy", ADD CONSTRAINT "users_team_id_teams_fk" FOREIGN KEY ("team_id") REFERENCES "teams" ("id") ON DELETE SET NULL ON UPDATE CASCADE
```

A migration that must also run on SQLite returns one `alter()` per action, as an array — a shape
every engine accepts:

```php
return new Migration(
   Up: fn (Migrating $Schema) => [
      $Schema->alter('users', fn (Blueprint $Table) => $Table->rename('bio', 'profile')),
      $Schema->alter('users', fn (Blueprint $Table) => $Table->remove('legacy')),
   ],
   Down: fn (Migrating $Schema) => [
      $Schema->alter('users', function (Blueprint $Table): void {
         $Table->add('legacy', Types::Text)->nullable = true;
      }),
      $Schema->alter('users', fn (Blueprint $Table) => $Table->rename('profile', 'bio')),
   ]
);
```

`Down` brings the `legacy` column back, not its data. Which column changes each engine accepts
— type, default, nullability — is in the
**[Dialects](/manual/ADI/Databases/SQL/Schema/Dialects/overview/#what-each-engine-can-do)** table,
and how to write them is in
**[Changing a table later](/manual/ADI/Databases/SQL/Schema/Blueprint/overview/#changing-a-table-later)**.

## Drop and re-run

`drop()` writes `IF EXISTS` unless you pass `exists: false`, on every engine, so dropping a table
that is already gone succeeds. `unindex()` and `unconstrain()` take the same `exists` flag, also
`true` by default, but not every engine honours it: PostgreSQL does for both and SQLite for
`unindex()`, MySQL ignores it for now, and SQLite cannot drop a constraint at all. On PostgreSQL:

```php
$Schema->drop('users');                                   // DROP TABLE IF EXISTS "users"
$Schema->drop('users', exists: false);                    // DROP TABLE "users"
$Schema->unindex('users', 'users_email_index');           // DROP INDEX IF EXISTS "users_email_index"
$Schema->unconstrain('users', 'users_team_id_teams_fk');  // ALTER TABLE "users" DROP CONSTRAINT IF EXISTS "users_team_id_teams_fk"
```

Each engine's statements are in
**[Dropping indexes and constraints](/manual/ADI/Databases/SQL/Schema/Dialects/overview/#dropping-indexes-and-constraints)**.

> [!WARNING]
> For now, MySQL ignores `exists` in `unindex()` and `unconstrain()`, so dropping an index or a
> foreign key that is already gone fails there with
> `1091: Can't DROP '…'; check that column/key exists`. MySQL runs a migration without a
> transaction: when a `Down` fails this way, the statements before it stay applied, the migration
> stays recorded as applied, and a retry fails the same way. Where a `Down` can drop the whole
> table instead, do that — its indexes and foreign keys go with it.

## Generated names

When you pass no `name:`, `index()` and the table-level `reference()` name what they create:

- an index: `<table>_<columns>_index`, or `<table>_<columns>_unique` with `unique: true` —
  `posts_author_id_published_at_index`;
- a foreign key: `<table>_<column>_<referenced table>_fk` — `users_team_id_teams_fk`, with every
  `.` of a schema-qualified name turned into `_`.

A generated name longer than 63 bytes — PostgreSQL's identifier limit; MySQL's is 64 characters —
is shortened to its first 54 bytes, an `_` and the first 8 hex digits of the SHA-256 hash of the
whole name. The same table and columns always give the same name, so a later `unindex()` can
repeat it:

```php
$Schema->index('subscription_invoices', ['billing_account_id', 'invoice_issued_at'], unique: true);
// CREATE UNIQUE INDEX "subscription_invoices_billing_account_id_invoice_issue_3301c710" ON "subscription_invoices" ("billing_account_id", "invoice_issued_at")

$Schema->unindex('subscription_invoices', 'subscription_invoices_billing_account_id_invoice_issue_3301c710');
```

A `name:` you pass is used verbatim: Bootgly does not shorten it. PostgreSQL then cuts a name
longer than 63 bytes down to 63, MySQL refuses one longer than 64 characters
(`1059: Identifier name '…' is too long`), and SQLite keeps any length.

> [!WARNING]
> For now, the generated name of an index on a schema-qualified table keeps the dot:
> `$Schema->index('audit.users', 'email')` names the index `audit.users_email_index`, which
> compiles as `"audit"."users_email_index"`, and PostgreSQL (`syntax error at or near "."`) and
> MySQL (`1064`) refuse the statement. On a schema-qualified table, pass `name:`.

## Use it outside a migration

Schema changes belong in migrations, which the Runner records and can undo. When a boot function,
a command or a script needs DDL anyway, open the database as
**[Open a database](/manual/ADI/Databases/SQL/overview/#open-a-database)** shows, take its Schema
Builder and run what it compiles:

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

$Schema = $Database->structure();

$Query = $Schema->create('settings', function (Blueprint $Table): void {
   $Table->add('key', Types::String)->limit(100)->constrain(Keys::Primary);
   $Table->add('value')->nullable = true;  // no type: Types::Text
}, exists: true);

$Database->await($Database->query($Query));
```

`structure()` creates the facade's Schema Builder on its first call and returns the same one after.
With `exists: true` the statement is `CREATE TABLE IF NOT EXISTS`, so the script can run again.

## Good to know

- **A column without a type is `Types::Text`**: `$Table->add('value')` compiles `"value" TEXT NOT NULL`.
- **Empty blueprints are rejected.** A `create()` with no column and no foreign key throws
  `InvalidArgumentException: CREATE TABLE requires at least one column or constraint.`, and an
  `alter()` with no action throws `InvalidArgumentException: ALTER TABLE requires at least one schema action.`
- **Names are typed.** Every table and column name — and the index or constraint name that
  `unindex()` and `unconstrain()` take — accepts a `string`, any `Stringable` or a backed enum,
  whose `value` is used; see
  **[Tip: typed names with enums](/manual/ADI/Databases/SQL/Schema/Blueprint/overview/#tip-typed-names-with-enums)**.
  The `name:` you give `index()` or `reference()` is a plain `string`: an enum there throws a
  `TypeError`.
- **A dot qualifies.** `'audit.users'` compiles as `"audit"."users"` — a schema and a table — so
  a name cannot contain a dot of its own.

## Reference

Get a Schema Builder from a database facade with `$Database->structure()` — see the
**[SQL database](/manual/ADI/Databases/SQL/overview/#reference)** Reference — or build one for a
dialect. Migration closures receive it typed as `Migrating`.

### Schema

`Bootgly\ADI\Databases\SQL\Schema`. In the signatures, `QueryDialect` is
`Bootgly\ADI\Databases\SQL\Builder\Dialect` and `SchemaDialect` is
`Bootgly\ADI\Databases\SQL\Schema\Dialect`.

```php
__construct (null|QueryDialect|SchemaDialect $Dialect = null)
```

Creates a Schema Builder. A schema dialect is used as given — the way to plug in a dialect of your
own (see **[Writing a dialect](/manual/ADI/Databases/SQL/Schema/Dialects/overview/#writing-a-dialect)**).
A Query Builder dialect is mapped to the schema dialect of the same engine, and `null` means
PostgreSQL. A Query Builder dialect with no schema counterpart throws
`InvalidArgumentException: Schema Builder dialect is not registered.`

```php
public private(set) SchemaDialect $Dialect
```

The schema dialect the builder compiles with. Read it to ask what the engine supports —
`$Schema->Dialect->check(Capabilities::AlterColumnUsing)` — or whether it runs DDL in a
transaction, `$Schema->Dialect->transactions` (see
**[Dialects](/manual/ADI/Databases/SQL/Schema/Dialects/overview/#reference)**).

```php
create (BackedEnum|Stringable|string $Table, Closure $Build, bool $exists = false): Query
```

Compiles one `CREATE TABLE`. `$Build` receives a new `Blueprint` for `$Table`: add the columns and
the table-level foreign keys to it (see
**[Defining tables](/manual/ADI/Databases/SQL/Schema/Blueprint/overview/)**). `exists: true` adds
`IF NOT EXISTS`. A blueprint with no column and no foreign key throws
`InvalidArgumentException: CREATE TABLE requires at least one column or constraint.` Indexes
declared on the blueprint are not compiled — see [Create a table with its indexes](#create-a-table-with-its-indexes).

```php
alter (BackedEnum|Stringable|string $Table, Closure $Build): Query
```

Compiles one `ALTER TABLE` from what `$Build` adds to a new `Blueprint`: `ADD COLUMN` for each
`add()`, the column changes of each `change()`, `RENAME COLUMN` for each `rename()`, `DROP COLUMN`
for each `remove()` and `ADD CONSTRAINT … FOREIGN KEY` for each `reference()`, in that order. A
blueprint with no action throws `InvalidArgumentException: ALTER TABLE requires at least one schema action.`
PostgreSQL refuses a rename beside another action and SQLite a second action (see
[Change a table](#change-a-table)), and an action the engine lacks throws
`InvalidArgumentException: <Dialect> schema dialect lacks capability: <Capability>.`

```php
drop (BackedEnum|Stringable|string $Table, bool $exists = true): Query
```

Compiles one `DROP TABLE`, with `IF EXISTS` unless `exists: false`, on every engine.

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

Compiles one table rename: `ALTER TABLE "users" RENAME TO "members"` on PostgreSQL and SQLite,
``RENAME TABLE `users` TO `members` `` on MySQL.

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

Compiles one `CREATE INDEX` — `CREATE UNIQUE INDEX` with `unique: true` — over one column or a
list of columns, in order. Without `$name`, the name is generated (see
[Generated names](#generated-names)). There is no `IF NOT EXISTS`: an index whose name is taken
fails on the server.

```php
unindex (BackedEnum|Stringable|string $Table, BackedEnum|Stringable|string $Name, bool $exists = true): Query
```

Compiles one `DROP INDEX` for the index `$Name`. `$exists` adds `IF EXISTS` on PostgreSQL and
SQLite; MySQL ignores it for now and compiles `` DROP INDEX `name` ON `table` ``. PostgreSQL takes
the schema of a schema-qualified `$Table`: `unindex('audit.users', 'users_email_index')` compiles
`DROP INDEX IF EXISTS "audit"."users_email_index"`. SQLite does not use `$Table`.

```php
unconstrain (BackedEnum|Stringable|string $Table, BackedEnum|Stringable|string $Name, bool $exists = true): Query
```

Compiles the drop of the constraint `$Name`. PostgreSQL compiles
`ALTER TABLE … DROP CONSTRAINT`, with `IF EXISTS` unless `exists: false`, for any constraint.
MySQL compiles `ALTER TABLE … DROP FOREIGN KEY`, which drops foreign keys only, and ignores
`$exists` for now. SQLite throws
`InvalidArgumentException: SQLite schema dialect lacks capability: DropConstraint.`

### Migrating

`Bootgly\ADI\Databases\SQL\Schema\Migrating` is the interface migration closures type `$Schema`
with. It declares the seven compile methods above — `create`, `alter`, `drop`, `rename`, `index`,
`unindex` and `unconstrain` — with the same signatures. `Schema` implements it, and the Runner
always passes the closures its database's `structure()`.
