# Bulk Operations

- [Introduction](#introduction)
- [Allowing bulk requests](#allowing-bulk-requests)
- [Creating many models](#creating-many-models)
- [Updating many models](#updating-many-models)
- [Deleting many models](#deleting-many-models)
- [All or nothing](#all-or-nothing)
- [Errors](#errors)
- [Agents](#agents)

## Introduction

A bulk request creates, updates or deletes many models of one repository at once. Restify runs each item through the same code as the single request: the input's validation and the repository's hooks. The request must be allowed the bulk actions, which are separate from the single ones. All the items run in one database transaction, so if one item fails, none of them is saved.

The bulk endpoints answer exactly as Restify for PHP's do, so a client written for PHP keeps working. Their answers are therefore simpler than the single endpoints': raw models, an empty object, an empty array.

## Allowing bulk requests

Every repository has the bulk endpoints and tools, and refuses them until its `authorize` allows the bulk actions. They are separate from the single ones, so a repository may let a user change one post and not fifty:

| Action | Asked | `model` is |
| --- | --- | --- |
| `Action::StoreBulk` | Once for the request | `None` |
| `Action::UpdateBulk` | For each item, after every model is found and before any is changed | The model, before the change |
| `Action::DeleteBulk` | For each item, after every model is found and before any is deleted | The model |

The example app lets only an admin write posts in bulk:

```rust
async fn authorize(action: Action, request: &Request, post: Option<&Post>) -> laravel::Result<()> {
    match (action, post) {
        (Action::AllowRestify | Action::Index | Action::Store, _) => Ok(()),
        (Action::Show, Some(post)) => request.authorize(PostPolicy::show, post).await,
        (Action::Update, Some(post)) => request.authorize(PostPolicy::update, post).await,
        (Action::Delete, Some(post)) => request.authorize(PostPolicy::delete, post).await,
        (Action::StoreBulk | Action::UpdateBulk | Action::DeleteBulk, _) => {
            request.authorize(PostPolicy::bulk, ()).await
        }
        _ => Err(laravel::abort(403)),
    }
}
```

A request may hold at most `MAX_BULK` items, `100` by default. Restify for PHP has no limit; this one is a safety limit, so that one request can't hold a database transaction open for long. To change it, set it on the repository:

```rust
const MAX_BULK: usize = 20;
```

## Creating many models

Send a JSON array of `Store` inputs to `POST /api/restify/posts/bulk`:

```json
[
    { "title": "First", "votes": 1 },
    { "title": "Second", "body": "Text" }
]
```

It answers `200` with every new model, in the order sent. As in Restify for PHP, each model is its own JSON, not a resource: no `type` and no `attributes`, the key as a number, and no field rules applied, so a hidden column such as `body` shows:

```json
{
    "data": [
        { "id": 1, "title": "First", "votes": 1, "user_id": 1, "created_at": "..", "updated_at": ".." },
        { "id": 2, "title": "Second", "body": "Text", "user_id": 1, "created_at": "..", "updated_at": ".." }
    ]
}
```

A column the item could have set but left out, such as `body` in the first item, isn't shown. Read the posts again with `GET` to see them as resources.

Restify calls `authorize` once with `Action::StoreBulk` and validates every item. Then, for each item, it runs `creating`, saves it, and runs `stored`.

## Updating many models

Send a JSON array to `POST /api/restify/posts/bulk/update`. Each item is the model's `id` and the `Update` fields to change:

```json
[
    { "id": 1, "title": "Laravel for Rust", "votes": 11 },
    { "id": "2", "title": "Renamed" }
]
```

It answers `200` with an empty object, `{}`, as Restify for PHP does. An `id` may be a number or a string.

A bulk update is a full update, like `PUT`: a field with a `required` rule, such as the post's `title`, must be in every item. Other fields an item leaves out keep their values.

Restify validates every item, finds every model through `Repository::query`, and calls `authorize` with `Action::UpdateBulk` for each. Then, for each item, it runs `updating`, saves it, and runs `updated`.

## Deleting many models

Send a JSON array of ids to `DELETE /api/restify/posts/bulk/delete`:

```json
[1, 2, 3]
```

It answers `200` with an empty array, `[]`, as Restify for PHP does. An id sent twice deletes its model once. Restify finds every model through `Repository::query` and calls `authorize` with `Action::DeleteBulk` for each. Then it deletes each one and runs `deleted`.

## All or nothing

Restify checks the whole request before it writes anything: every item's input, every model, and every permission. Then it writes the items one after another, in the order sent, inside one database transaction (the framework's `db::transaction`). If a hook fails part way, the transaction rolls back every item before it. So a client never has to work out which items were saved.

- A `422` lists the errors of every item at once, so a client can fix them all and send the request again.
- Events and queued jobs the framework dispatches wait for the transaction to commit, so a rolled-back request sends nothing. See the framework's `database.md` guide, "Transactions".

## Errors

A field error's key starts with the item's position in the array, starting at `0`. Here the second item has no title:

```json
{
    "message": "A post needs a title.",
    "errors": { "1.title": ["A post needs a title."] }
}
```

The message is the field's own, as on the single endpoints. A message the rule writes itself names the item, such as "The 1.title field is required.".

Restify for PHP leaves out a field's own messages in bulk, and answers "The 1.title field is required." here. That is a bug in PHP. The status and the error keys are the same.

A refusal answers `403` and a missing model `404`, with the same message as the single endpoints.

| Status | When |
| --- | --- |
| `401` | The middleware found no user |
| `403` | `authorize`, a policy, or the input's own check refused an item |
| `404` | No model has an item's id, or `query` leaves it out |
| `422` | An item is invalid, or an update item has no `id`; or the body isn't an array, is empty, or holds more than `MAX_BULK` items |

A key the input doesn't declare, such as `user_id`, is ignored, as on the single endpoints and in Restify for PHP. A field's write gates apply to each item as they do to a single write: `can_store` in a bulk create, `can_update` in a bulk update, and `readonly_when` in both. A key a gate refuses is dropped from that item. See [Fields only some users may write](writing.md#fields-only-some-users-may-write).

The errors about the array itself use the key `items`: `"items": ["Send at most 100 items at once. This request sent 150; split it into smaller requests."]`.

## Agents

There are no bulk MCP tools, as in Restify for PHP. An agent creates, updates or deletes one record per call. See [MCP](mcp.md).
