Skip to content

Rewrite API

Use POST /v1/rewrite when your app owns the Postgres connection.

SQL Tamer returns a rewrite plan. Your app still opens the Postgres connection and executes that plan.

If you are targeting ClickHouse over HTTP, use the ClickHouse API instead.

Replace SQLTAMER_BASE_URL with your API base URL before running the examples on this page.

Minimal request

curl -X POST "$SQLTAMER_BASE_URL/v1/rewrite" \
  -H "Authorization: Bearer $SQLTAMER_API_KEY" \
  -H "Content-Type: application/json" \
  --data '{
    "sql": "SELECT id, email FROM users WHERE id IN (101, 202, 303, 404, 505)",
    "dialect": "postgres",
    "min_in_list_items": 3
  }'

Minimal response

{
  "main_sql": [
    "SELECT id, email FROM users WHERE id = ANY($1::BIGINT[])"
  ],
  "main_bindings": [
    [
      {
        "kind": "postgres_bigint_array",
        "values": [101, 202, 303, 404, 505]
      }
    ]
  ],
  "setup_sql": [],
  "load_ops": [],
  "cleanup_sql": [],
  "metadata": {
    "applied_rewrites": [
      {
        "rule": "in_list_to_any_array",
        "temp_table_name": null,
        "extracted_items": 5
      }
    ]
  }
}

What this means:

  • main_sql is the rewritten query or queries
  • main_bindings contains separate values to bind with your driver
  • setup_sql, load_ops, and cleanup_sql are only present when the rewrite needs temporary data or setup work

How to execute the plan

  1. Open one Postgres transaction.
  2. Run every statement in setup_sql.
  3. Execute each load_ops entry on the same connection.
  4. Run each main_sql[i] with main_bindings[i].
  5. Run every statement in cleanup_sql.
  6. Commit or roll back.

Fields that matter

Key Meaning
main_sql The rewritten query or queries
main_bindings Parameter values to bind separately
setup_sql Statements to run before the main query
load_ops Rows to bulk-load into temporary data
cleanup_sql Statements to run at the end
metadata.applied_rewrites Which rewrite rule fired

Common request fields

Field Meaning
sql The original SQL text
dialect Use postgres for this endpoint
min_in_list_items Override the threshold for large IN (...) rewrites
enable_case_to_temp_table Turn on CASE rewrites explicitly
rules Force a specific set of rewrite rules

When this page is enough

If the response only contains main_sql and main_bindings, you can usually execute that directly with your normal driver.

If the response also contains load_ops, move on to the Postgres integration guide.