# Query extensions

> Restrict the perimeter of every resource, add columns for the policies, narrow page sizes per user and add search instructions from an extension.

Four kinds act on the SQL queries of the package, and `ProvidesPerimeter` marks a restriction that is the perimeter. They throw `Lomkit\Rest\Exceptions\InvalidQueryExtensionException`, which names the extension by its name and its class. See [Extensions](/extensions/overview) for registering an extension.

## Restricting queries

`RestrictsQueries::restrict(RestrictionContext $context)` adds where clauses to the perimeter of a resource:

```php [Vendor/Tenancy/TenantExtension.php]
use Lomkit\Rest\Extensions\Contexts\RestrictionContext;
use Lomkit\Rest\Extensions\Extension;
use Lomkit\Rest\Extensions\Kinds\RestrictsQueries;

final class TenantExtension extends Extension implements RestrictsQueries
{
    public function __construct(private readonly CurrentTenant $tenant) {}

    #[\Override]
    public static function name(): string
    {
        return 'tenant';
    }

    #[\Override]
    public function restrict(RestrictionContext $context): void
    {
        if ($context->user === null) {
            $context->query->whereRaw('0 = 1');

            return;
        }

        $context->query->where($context->query->qualifyColumn('tenant_id'), $this->tenant->id());
    }
}
```

- `$context->query` is the Eloquent builder of the extension's own where group. The group comes after `perimeterQuery()`, inside its own parentheses, and is AND-ed with the perimeter and the other extensions: an `orWhere()` in it cannot widen the rows.
- `$context->resource` is the restricted resource: the related one on an include, a relation filter, sort or aggregate. `$context->user` is the user of the request, `null` for a guest: decide the rows of a guest yourself.
- Qualify columns with `$context->query->qualifyColumn()`: pivot reads join another table.
- A restriction may run several times in one request, and again on each attempt of a write transaction: keep it free of side effects.

### Where it applies

A restriction applies wherever the perimeter does: searches and includes, through a pivot too, relation filters, sorts and aggregates, metrics and the key of their cache in both scopes, the key lookups of `mutate`, `destroy`, `restore`, `forceDestroy` and actions, the rows of queued actions, child syncs, attached pivot rows, the records read again after a write and the write gates of rendered rows. It also applies to `#[WithoutPerimeter]` resources. See [Perimeter](/resources/perimeter).

- The key of a cached metric holds the SQL and the bindings of each restricted perimeter, with the user, so a restriction that reads a tenant or a flag never shares a result. Without a restriction, the key does not change.
- Every relation path reads the perimeter through the final `Relation::constrainToPerimeter()`. It opens one where group, runs `applyPerimeter()` inside it, then adds the restrictions after it: an override of `applyPerimeter()` cannot skip a restriction. A custom relation picks the restricted resource with the protected `perimeterResource(Model $model)`.
- On a search engine, the rows of a page load by key without the restriction: the engine is the proof. Restrict the engine query with [`RestrictsEngineQueries`](/extensions/engines#restricting-engine-searches), or a text search of the resource throws `InvalidTextSearchException` on an engine that does not run SQL. On the Scout `database` and `collection` drivers, the restriction applies in the SQL of the engine query.
- A tenant that does not come from `$context->user`, such as a subdomain or a header, is not in the keys of kept decisions: add it with [`ContributesCacheContext`](/extensions/authorization#adding-to-the-cache-context).

### What it refuses

Only where clauses. A join, order, limit, offset, select, distinct, lock, group, having, union, eager load, other table, before-query or after-query callback, added global scope or removed global scope (`withTrashed()`, `withoutGlobalScope()`) throws:

```text
The [tenant] extension Vendor\Tenancy\TenantExtension adds a join to the restriction of App\Rest\Resources\PostResource, which holds only where clauses. Restrict through another table with whereHas() or whereExists().
```

- The check reads the nested where groups too, at every depth.
- Laravel drops a global scope or an `afterQuery()` callback added to the Eloquent builder of a nested group before the check runs: neither is applied. Write where clauses only.

## Providing the perimeter

`rest:check` reports a resource without `perimeterQuery()` or `#[WithoutPerimeter]` even when a `RestrictsQueries` extension restricts it: a tenant extension narrows a perimeter declared elsewhere, it does not stand for it.

An extension whose restriction is the perimeter, such as an access-control extension that decides the rows of each user, implements `ProvidesPerimeter`, which extends `RestrictsQueries` and adds no method:

```php
use Lomkit\Rest\Extensions\Kinds\ProvidesPerimeter;

final class AccessControlExtension extends Extension implements ProvidesPerimeter
{
    // name() and restrict(), as above
}
```

- `rest:check` then accepts the resources that the extension applies to, with a `perimeter from acl` line and an entry of `rows.extension_perimeter` in `--json`. Plain restrictions show as `restricted by tenant` lines and in `rows.restricted`. See [Checking the application](/digging-deeper/artisan#checking-the-application).
- It changes nothing at runtime.
- `rest:check` reads the config of the environment it runs in: where the extension is disabled, or its `appliesTo()` leaves a resource out, the problem comes back. Run it with the extensions of production.
- A `RestrictsQueries` extension whose `appliesTo()` throws for a resource is a `rows` problem of `rest:check` that names it. The extensions that answer are still named for that resource, and the other resources are still checked.

## Adding to rendered rows

`AugmentsQueries::augment(AugmentationContext $context)` loads what the policies and gates of the rendered rows read, in the same query:

```php [Vendor/Locks/LockColumnsExtension.php]
use Lomkit\Rest\Extensions\Contexts\AugmentationContext;
use Lomkit\Rest\Extensions\Extension;
use Lomkit\Rest\Extensions\Kinds\AugmentsQueries;

final class LockColumnsExtension extends Extension implements AugmentsQueries
{
    #[\Override]
    public static function name(): string
    {
        return 'locks';
    }

    #[\Override]
    public function appliesTo(string $resource): bool
    {
        return is_a($resource, PostResource::class, true);
    }

    #[\Override]
    public function augment(AugmentationContext $context): void
    {
        if (! in_array('update', $context->gates, true)) {
            return;
        }

        $context->column('owner_id');
        $context->select('locked', Lock::query()->selectRaw('count(*) > 0')->whereColumn('locks.post_id', 'posts.id'));
        $context->with('approvals');
    }
}
```

- `column()` adds a column of the model table, as is.
- `select()` adds a subquery and returns its alias, `{name}__{alias}`: here `locks__locked`, the attribute that the policy reads. It takes a query builder, an Eloquent builder or a closure that builds the subquery on a fresh query builder, as `addSelect()` does.
- `with()` eager loads a relation path of public relation methods declared with a `Relation` return type, never past a `MorphTo`. It takes an optional constraint closure, as Laravel's `with()`, which runs when the relation loads and cannot call the context.
- `$context->gates` lists the row gates rendered for these rows, `[]` on an include level that the client did not search. `$context->resource` and `$context->user` are the resource of the level and the user of the request.

### Guarantees

- It runs on the rows that a response renders only, at every include level: a search page, the rows of `Rest::search()`, the records read after a write and the rows of a search engine page. Never on a count, an action, a metric, an aggregate or a key lookup.
- `fields()` alone decides what renders: added columns, subqueries and eager loads never render.
- An eager load on a relation that the client includes at that level under its own name is skipped: the policies read the relation as the client filtered and limited it. An include under an alias does not skip it.
- The default `paginate()` and `PageQuery` count without the augmentation. A `paginate()` override that counts with `$query->paginate()` counts the added columns.
- On a query that groups rows, such as a scope with `groupBy()`, add only a column that the `GROUP BY` holds or that depends on its key, or PostgreSQL and MySQL with `ONLY_FULL_GROUP_BY` refuse the query.

### What it refuses

- An alias that is not 1 to 32 lowercase letters or digits starting with a letter, with words joined by single underscores (`a__b` and `a_` are refused), longer than 63 characters with its prefix, selected twice or equal to a field name.
- A column that is not a column name of the model, a relation path that is not public relation methods, that goes past a `MorphTo`, or that two extensions load.
- A call to `column()`, `select()` or `with()` after `augment()` returned.

## Narrowing limits

`NarrowsLimits::narrowLimits(LimitsContext $context)` narrows the page sizes, the total cap and the include limit of a resource for the user:

```php [Vendor/Plans/PlanLimitsExtension.php]
use Lomkit\Rest\Extensions\Contexts\LimitsContext;
use Lomkit\Rest\Extensions\Extension;
use Lomkit\Rest\Extensions\Kinds\NarrowsLimits;

final class PlanLimitsExtension extends Extension implements NarrowsLimits
{
    #[\Override]
    public static function name(): string
    {
        return 'plan_limits';
    }

    #[\Override]
    public function narrowLimits(LimitsContext $context): void
    {
        $context->allowSizes([10, 25]);
        $context->maxTotal(1000);
        $context->includeLimit(10);
    }
}
```

- Never upward, in any extension order. `allowSizes()` intersects the sizes of `limits()`. `maxSize()` and `maxTotal()` drop the larger sizes. `maxTotal()` and `includeLimit()` take the minimum with the resource.
- The default page size becomes the largest size left at or below `$defaultLimit`, and the include limit the largest size left at or below the smaller include limit.
- Validation, paging, includes and `/details` use the limits of the current user, `$context->user`.
- `$context->declared` holds the limits that the resource declares, before any extension: `allowed`, `defaultLimit`, `includeLimit` and `maxTotal`. `ResourceDefinition::declaredLimits()` returns them too.
- The OpenAPI document shows the declared limits and never calls `narrowLimits()`. `total_capped` is optional on the pages of a resource that an extension may cap.
- A capped count prohibits [`search.totals`](/search/totals) for that user.

It refuses a value below 1, a narrowing that leaves no size, no size at or below `$defaultLimit` or none at or below the include limit, and a read of `definition()->limits()` of the same resource inside `narrowLimits()`: read `$context->declared`. See [Limits](/resources/limits).

## Declaring instructions

`DeclaresInstructions::instructions(InstructionsContext $context)` adds search instructions to a resource:

```php [Vendor/Archive/ArchiveInstructionsExtension.php]
use Lomkit\Rest\Extensions\Contexts\InstructionsContext;
use Lomkit\Rest\Extensions\Extension;
use Lomkit\Rest\Extensions\Kinds\DeclaresInstructions;

final class ArchiveInstructionsExtension extends Extension implements DeclaresInstructions
{
    #[\Override]
    public static function name(): string
    {
        return 'arc';
    }

    #[\Override]
    public function instructions(InstructionsContext $context): array
    {
        return is_subclass_of($context->resource, ArchivableResource::class) ? [WithArchivedInstruction::class] : [];
    }
}
```

```json [POST /api/authors/search]
{
  "search": {
    "instructions": [{"name": "arc.with-archived"}]
  }
}
```

- It receives the resource class only, no user. Its instructions are read with those of the resource.
- The key of each instruction is the extension name, a dot and its `uriKey()`: `arc.with-archived`, in requests, `/details`, search meta and the OpenAPI document. `$instruction->publicUriKey()` returns it.
- Like any instruction, it runs in its own where group, AND-ed with the rest of the search. See [Scopes and instructions](/search/scopes-and-instructions).
- It refuses a key that another instruction of the resource or of an extension takes, and the entries that `instructions()` of a resource refuses. `rest:check` reports both.

<note>

`Instruction` gains the final method `publicUriKey()`: an instruction that declares a method of that name renames it.

</note>
