# Add Soft Delete to a Vapor App

Yes. An agent adds a Fluent deleted_at timestamp to a Vapor model, a migration, a restore route and tests that deleted rows stay out of queries, and opens a PR.

[Run this on Rush](https://cloud.getrush.ai/run/add-soft-delete/vapor/). Opens the console with this prompt ready to send, in a Project that has your repository.

## What the agent does

The agent starts by reading the app as it is. In a project generated from vapor/template with Fluent, `Package.swift` pins `vapor` from 4.121.4, `fluent` from 4.13.0, the Fluent driver the generator chose, and `swift-nio` from 2.101.0 under `swift-tools-version:6.3`, with upcoming features such as `ExistentialAny` and `MemberImportVisibility` turned on for both targets. `Sources/App/Models/Todo.swift` is a `final class Todo: Model, @unchecked Sendable` with the schema name `todos`, an `@ID` and a single `@Field(key: "title")`; `Migrations/CreateTodo.swift` creates that table with `.id()` and a required string `title`; `DTOs/TodoDTO.swift` carries `id` and an optional `title` and converts both ways; and `Controllers/TodoController.swift` registers `GET /todos`, `POST /todos` and `DELETE /todos/:todoID`, where `delete` calls `todo.delete(on: req.db)` and answers `204`. `configure.swift` adds `CreateTodo()` to `app.migrations`, and `Tests/AppTests/AppTests.swift` runs four Swift Testing cases under a `withApp` helper that calls `autoMigrate()` before each test and `autoRevert()` after.

Fluent already has the mechanism: a `@Timestamp(key: "deleted_at", on: .delete)` property turns `delete(on:)` into an update that sets the timestamp, and every query on the model filters out rows where it is set unless the query calls `withDeleted()`. The agent adds that property to `Todo`, named `deletedAt` with type `Date?`, and writes a second migration, `AddTodoDeletedAt`, that calls `database.schema("todos").field("deleted_at", .datetime).update()` in `prepare` and `deleteField("deleted_at")` in `revert`, then registers it after `CreateTodo()` in `configure.swift`. It leaves `CreateTodo` untouched so a database that already ran it migrates forward with the `migrate --yes` command that `docker-compose.yml` runs in its `migrate` service.

The controller gains two routes beside the existing three. `DELETE /todos/:todoID?force=true` calls `todo.delete(force: true, on: req.db)` for a real row removal, so the old route keeps its meaning and an operator still has a way to purge. `POST /todos/:todoID/restore` loads the row with `Todo.query(on: req.db).withDeleted().filter(\.$id == id).first()`, throws `Abort(.notFound)` when there is no such row, calls `todo.restore(on: req.db)` and answers the DTO. `TodoDTO` gets an optional `deletedAt` so a client can tell a restored row from a fresh one, and `toDTO()` copies it from `self.$deletedAt.value`. Nothing else in `routes.swift` or `entrypoint.swift` changes.

Then it writes the tests the template's style asks for: in `AppTests.swift`, a case that creates two todos, deletes one through the route, and asserts `GET /todos` returns only the other while `Todo.query(on: app.db).withDeleted().count()` still reports two; a case that restores it and asserts it is back in the list with `deletedAt` nil; a case for `force=true` that asserts the row is gone even with `withDeleted()`; and a case that `restore` on an unknown id is `404`. It runs `swift build` and `swift test` the way `test-template.yml` does, against the database the project was generated for, and pastes the test output into the pull request.

## Start it with one API call

`POST https://api.phoenix.so/o/{org}/sessions`

```json
{
  "agent": "claude",
  "input": "Add soft delete to the Todo model in this Vapor app and open a pull request. Read Package.swift, Sources/App/configure.swift, routes.swift, Models/Todo.swift, Migrations/CreateTodo.swift, DTOs/TodoDTO.swift, Controllers/TodoController.swift and Tests/AppTests/AppTests.swift first. Add a @Timestamp(key: \"deleted_at\", on: .delete) property to Todo, a new AsyncMigration that adds a nullable deleted_at datetime field to the todos table and removes it on revert, registered after CreateTodo in configure.swift. Keep DELETE /todos/:todoID as a soft delete, add ?force=true for a hard delete, and add POST /todos/:todoID/restore that loads the row with withDeleted(), restores it and returns the DTO, or 404. Expose deletedAt on TodoDTO. Add Swift Testing cases in AppTests.swift for soft delete hiding the row from GET /todos but not from withDeleted(), restore, force delete and restore of an unknown id. Run swift build and swift test and paste the output in the pull request. Do not change CreateTodo or the existing routes' status codes.",
  "resources": [
    {
      "url": "https://github.com/your-org/your-app"
    }
  ]
}
```

1. **Get an API key.** In the console, open Settings, then API keys, and create a key for your org. Send it in the Authorization header as a Bearer token.
2. **Send the request.** POST the body in request.json to https://api.phoenix.so/o/{org}/sessions, with your repository as the resources URL. The run starts in its own cloud sandbox.
3. **Read what came back.** Follow the run on its live stream or wait for the run.completed webhook, then read the result and its trajectory.

## What comes back

What comes back is a pull request that edits `Models/Todo.swift`, `DTOs/TodoDTO.swift`, `Controllers/TodoController.swift`, `configure.swift` and `Tests/AppTests/AppTests.swift`, and adds `Migrations/AddTodoDeletedAt.swift`. The description lists the new routes, says which migration to run and pastes the `swift test` output with the new cases named, and points out that the restore route accepts only ids that exist in the table, deleted or not.

A repository with a CI workflow that runs `swift test` on pull requests builds the change on the same image the template's own workflow uses, `swift:6.3-noble`, with the database service the project targets, so the migration and the four new cases run before anyone reviews. A repository with no workflow still has the output the agent pasted, with the commands it ran kept in the run's record.

A reviewer checks three things before merging: that the migration is appended, not inserted before `CreateTodo`, so an existing database migrates forward; that no query in the app relies on seeing deleted rows, because after this change `Todo.query` hides them by default; and whether `force=true` should be reachable at all in their deployment, since it is the only route that still removes data.

## Run it on every model that needs soft delete

A team with several Vapor services sends one `POST /o/{org}/sessions` per repository with this prompt, naming the model in `input` and that repository in `resources`. Each run reads its own `Package.swift` and migrations, so a project on the MySQL driver gets the same field under `.datetime` and a project with several models gets one migration per model it was asked about, and each run opens its own pull request. Send a `request_id` with each request so a retried call returns the run it already started instead of a second sandbox.

Give the key a `webhook_url` and every run it starts posts `run.completed` when its turn ends, with `data.session_url` to read the pull request link from, so a script collects the links without polling.

## Why run it on Rush?

A soft-delete change is small in code and easy to get subtly wrong: a `withDeleted()` missing from the restore query makes restore a permanent `404`, a migration registered in the wrong order fails on a database that already exists, and a `delete(force:)` left as the default throws the data away. Running it on Rush means the agent compiles the package with the pinned Swift 6.3 toolchain in its own sandbox, runs `swift test` against a real database it starts itself, and keeps every command and its output in the run's record, so the reviewer reads what happened rather than what was claimed.

The sandbox is disposable and the result is a branch with a pull request, so nothing touches a laptop's toolchain or a shared development database. The same request works on any Fluent model: the prompt names the model, and the run adapts the field, migration and routes to it.

## Frequently asked questions

### Will existing calls to delete(on:) start soft-deleting?

Yes. Once the model has a `@Timestamp` with `on: .delete`, Fluent turns every `delete(on:)` on that model into an update of `deleted_at`. The route behaves the same for a client, answering `204`, but the row stays in the table. Code that needs a real removal passes `force: true`, which is what the new `?force=true` query parameter does.

### Does this work with the SQLite driver the template can generate?

It does. The migration uses `.datetime`, which every Fluent driver maps to its own column type, and `schema(...).update()` with a new nullable field works on SQLite, MySQL and Postgres. The tests run under `withApp`, which migrates and reverts around each case, so the new migration is exercised on whichever driver the project was generated with.

### Why keep the old DELETE route instead of adding a new one?

Clients already call `DELETE /todos/:todoID`, and the safer behaviour for an existing client is that the row becomes recoverable rather than gone. Hard deletion is the exceptional case, so it is the one that needs an explicit flag. A reviewer who prefers the reverse can ask for the default to flip in a follow-up message to the run.

### What about the four existing tests?

They still pass. `getAllTodos`, `createTodo` and `deleteTodo` do not read `deleted_at`; `deleteTodo` asserts `Todo.find` returns nil after the route, and `find` hides soft-deleted rows, so the assertion holds. The run's test output shows all cases, old and new.

## More Vapor jobs

- [Add Structured JSON Logging to a Vapor App](https://getrush.ai/run/add-structured-logging/vapor/)
- [Add Pagination to a Vapor API from a Linear Issue](https://getrush.ai/run/add-todo-pagination/vapor/)
- [Add User Registration to a Vapor App](https://getrush.ai/run/add-user-registration/vapor/)

## The same job on other stacks

- [Add Soft Delete to an Actix Web API](https://getrush.ai/run/add-soft-delete/actix/)
- [Add Soft Delete to an ASP.NET Core App](https://getrush.ai/run/add-soft-delete/aspnet-core/)
- [Add Soft Delete to an Axum API](https://getrush.ai/run/add-soft-delete/axum/)

## Keep reading

- [How a Rush run works on your repository, from request to pull request](https://getrush.ai/cloud/)
- [Compare cloud agents, agent sandboxes and AI code review](https://getrush.ai/compare/)
- [Rush pricing: Free, Pro and Max](https://getrush.ai/pricing/)
