# `Lotus.Storage.Query`
[🔗](https://github.com/elixir-lotus/lotus/blob/v1.0.0/lib/lotus/storage/query.ex#L1)

Represents a saved Lotus query.

Queries can be stored, updated, listed, and executed by the host app.
Supports `{{var}}` placeholders in the SQL `statement` for value substitution
only. Variables are bound at runtime using configured variables and are only
safe for SQL values (WHERE clauses, ORDER BY values, etc.), never for
identifiers like table names, column names, or schema names.

# `t`

```elixir
@type t() :: %Lotus.Storage.Query{
  __meta__: term(),
  data_source: String.t() | nil,
  description: String.t() | nil,
  id: term(),
  inserted_at: DateTime.t(),
  name: String.t(),
  query_language: String.t() | nil,
  search_path: String.t() | nil,
  statement: String.t(),
  updated_at: DateTime.t(),
  variables: [Lotus.Storage.QueryVariable.t()]
}
```

# `changeset`

# `compile`

```elixir
@spec compile(t(), map()) :: {:ok, Lotus.Query.Statement.t()} | {:error, String.t()}
```

Compiles a stored query into an executable `Lotus.Query.Statement`.

Resolves `{{variable}}` placeholders, casts the supplied values, and folds
them through the source adapter's substitution callbacks. The returned
statement carries the adapter-native `:body` (SQL for Ecto adapters, a
DSL / AST / JSON payload for others) and the bound `:params`.

Returns `{:ok, %Lotus.Query.Statement{}}` on success, or `{:error, reason}`
when a required variable is missing, a list variable is empty, or a supplied
value fails type casting.

Use `compile!/2` if you prefer a raising variant.

# `compile!`

```elixir
@spec compile!(t(), map()) :: Lotus.Query.Statement.t()
```

Same as `compile/2` but raises `ArgumentError` on error.

# `extract_optional_variable_names`

```elixir
@spec extract_optional_variable_names(String.t()) :: MapSet.t()
```

Returns a `MapSet` of variable names that appear inside `[[...]]` optional
clause blocks in the given SQL statement.

# `extract_variables_from_statement`

```elixir
@spec extract_variables_from_statement(String.t()) :: [String.t()]
```

Extracts unique variable names from an SQL statement in order of first occurrence.

Variables are identified by the `{{variable_name}}` syntax.

## Examples

    iex> Lotus.Storage.Query.extract_variables_from_statement("SELECT * FROM users WHERE id = {{user_id}} AND status = {{status}}")
    ["user_id", "status"]

    iex> Lotus.Storage.Query.extract_variables_from_statement("SELECT * FROM users WHERE id = {{user_id}} OR id = {{user_id}}")
    ["user_id"]

    iex> Lotus.Storage.Query.extract_variables_from_statement("SELECT * FROM users")
    []

# `new`

# `update`

---

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