# `PgRest.SQL.ScopedSource`
[🔗](https://github.com/agoodway/pgrest/blob/v0.2.0/lib/pg_rest/sql/scoped_source.ex#L1)

Splices a resource's Ecto-scoped base query into PgRest's hand-built SQL.

`base_query/3` computes the scoped Ecto query once per resource per request and
enforces the predicate contract: `scope/2` may only add `where`, `join` and `distinct`.
`compile/3` turns that query into a parenthesised subquery whose `$n` placeholders are
shifted past the parameters the builder already holds. `effective_prefix/2` is the one
schema rule every statement on a resource follows.

A scope with joins or a `distinct` is spliced as a primary-key (or `unique_key`)
semijoin, so joined rows cannot duplicate base rows and no per-parent Sort + Unique is
planned. The semijoin reads the table in the scope's effective prefix
(`from.prefix`, then the query prefix, then the resource schema) and selects the
resource's default-select fields only, so columns outside the Ecto schema never appear.
With no prefix anywhere (no `from.prefix`, query prefix or schema prefix) the table is left
unqualified and resolves through `search_path`, exactly like Ecto's own SQL.
`unique_key` columns must be `NOT NULL`: `IN` drops rows whose key is NULL.

Compiled SQL text is cached in an ETS table owned by `PgRest.Cache` (created through
`create_cache/0`). Above 5,000 shapes the cache is cleared before storing a new entry;
concurrent callers may briefly exceed the bound. Hook shapes can vary per user.
Without the table, queries compile uncached. Every compile emits a
`[:pgrest, :scope_cache]` telemetry event with `cached: boolean()` metadata.

# `base_query`

```elixir
@spec base_query(module(), map(), [{String.t(), String.t()}]) ::
  Ecto.Query.t() | {:error, PgRest.Error.t()}
```

The scoped Ecto query: `scope/2` applied to the resource, then `handle_param/4` for each
declared custom param. Raises `ArgumentError` when the result uses anything beyond
`where`/`join`/`distinct`.

# `cache_table`

```elixir
@spec cache_table() :: atom()
```

Name of the ETS table holding compiled scoped SQL.

# `compile`

```elixir
@spec compile(Ecto.Query.t(), module(), PgRest.SQL.Builder.t()) ::
  {iodata(), PgRest.SQL.Builder.t()}
```

Compiles `source_query` to `(<sql>)`, for use as `FROM (...) AS alias`. The repo comes
from the builder (`Builder.new(repo: repo)`). Columns are named by Ecto field name.

# `effective_prefix`

```elixir
@spec effective_prefix(module(), Ecto.Query.t() | nil) :: String.t() | nil
```

The schema prefix the scoped source reads: the scope's `from.prefix`, then its query prefix
(`put_query_prefix/2`), then the resource's `@schema_prefix`; `nil` when none is set. Every
statement on the resource (reads, the write target, the semijoin, the catalog lookups and
the request `search_path`) uses this one rule, so a scope that picks a tenant schema reads
and writes the same table. `source_query` may be `nil` (no scope known): the resource's own
prefix.

# `effective_schema`

```elixir
@spec effective_schema(module(), Ecto.Query.t() | nil) :: String.t()
```

The schema of `effective_prefix/2`, or the resource's configured schema (`"public"`) when no
prefix is set: the schema the catalog is read from and the `search_path` lists.

# `exists_probe`

```elixir
@spec exists_probe(iodata(), [String.t()], [iodata()], iodata()) :: iodata()
```

A correlated `EXISTS` probe of the scoped source: `EXISTS (SELECT 1 FROM <scoped> s WHERE
(s.<field>, ...) = (<right>, ...)<tail>)`. `fields` are the scope's column (field) names,
`right` the matching outer expressions, `tail` text after the comparison (such as an
optimization fence). Never `IN (subquery)`: in a conflict filter an `IN` becomes a hashed
SubPlan over every in-scope row.

# `hook_query!`

```elixir
@spec hook_query!(Ecto.Query.t(), module(), module()) :: Ecto.Query.t()
```

Normalizes a policy query and enforces the scope predicate contract.

# `identity_scope?`

```elixir
@spec identity_scope?(module(), Ecto.Query.t()) :: boolean()
```

Whether `source_query` is the plain `from(r in resource)`, i.e. the scope is the identity.

# `intersect`

```elixir
@spec intersect(Ecto.Query.t(), Ecto.Query.t(), module()) ::
  Ecto.Query.t() | {:error, :denied}
```

Intersects a policy query with the base scope; neither source can widen the other.

# `key_fields`

```elixir
@spec key_fields(map()) :: [atom()]
```

The key fields (atoms) a scoped write or semijoin identifies rows by: the resource's
`unique_key`, else its primary key. `[]` when it has neither.

# `projection`

```elixir
@spec projection(map(), [atom()], String.t() | nil) :: iodata()
```

`<qualifier>.<source column> AS <field name>` for each of `fields` (atoms), comma separated;
unqualified when `qualifier` is `nil`. How a source or `RETURNING` exposes the columns
under their Ecto field names.

# `table`

```elixir
@spec table(module(), Ecto.Query.t() | nil) :: iodata()
```

The resource's table in its `effective_prefix/2`, quoted; unqualified when there is no
prefix, so it resolves through `search_path` exactly like Ecto's own SQL.

# `with_params`

```elixir
@spec with_params(Ecto.Query.t() | {:error, PgRest.Error.t()}, module(), map(), [
  {String.t(), String.t()}
]) :: Ecto.Query.t() | {:error, PgRest.Error.t()}
```

Applies validated request parameters directly to an identity source, including keyless
resources. Restricted sources are intersected with the result and require a key when
changed; without a key the request is refused. Effective prefix changes are always rejected.
A callback that replaces predicates or adds `or_where` cannot widen scope or policy.

## Differences from PostgREST

Custom parameters are an application extension; their queries can only narrow an
authorized source, including when no authorization hook is configured.
Changed restricted sources need a key (42501 otherwise); identity sources do not.

---

*Consult [api-reference.md](api-reference.md) for complete listing*
