### Schema file for SqlProof quick start Source: https://github.com/alialavia/sqlproof/blob/main/website/src/content/docs/getting-started.md Example PostgreSQL schema defining customers and orders tables with constraints. Used as input to SqlProof.from_schema_file(). ```sql -- schema.sql CREATE TABLE customers ( id SERIAL PRIMARY KEY, name VARCHAR(100) NOT NULL, email VARCHAR(255) NOT NULL UNIQUE ); CREATE TABLE orders ( id SERIAL PRIMARY KEY, customer_id INTEGER NOT NULL REFERENCES customers(id), total NUMERIC(10,2) NOT NULL CHECK (total >= 0) ); ``` -------------------------------- ### Run the Inbox Sample: Install, Start, Load Schema, Test, Fix, Rerun Source: https://github.com/alialavia/sqlproof/blob/main/examples/inbox/README.md Commands to install sqlproof, start a Supabase-shaped Postgres, load the initial buggy schema, run tests (expect 9 failures, 2 skipped), apply a recipe fix, and rerun the specific test. Replace 'recipe 2' and the test file with your chosen recipe. ```bash # 1. Install pip install sqlproof # 2. Start a Supabase-shaped Postgres (with pgvector + auth schema) supabase start export SUPABASE_DB_URL='postgresql://postgres:postgres@127.0.0.1:54322/postgres' # 3. Load the initial (buggy) schema psql "$SUPABASE_DB_URL" -f examples/inbox/schema/001_initial.sql # 4. Run the tests — 9 failures, 2 skipped pytest examples/inbox/tests -v # 5. Pick a recipe (say recipe 2). Apply its fix. psql "$SUPABASE_DB_URL" -f examples/inbox/schema/003_fix_tickets_rls.sql # 6. Rerun just that recipe's test pytest examples/inbox/tests/test_tickets_rls.py -v ``` -------------------------------- ### Clone and Setup Development Environment Source: https://github.com/alialavia/sqlproof/blob/main/README.md Clones the repository, syncs dependencies with uv, and runs the full test and lint suite (pytest, ruff, pyright, mypy). ```bash git clone https://github.com/alialavia/sqlproof.git cd sqlproof uv sync --extra dev uv run pytest uv run ruff check src tests uv run pyright src/sqlproof uv run mypy src/sqlproof ``` -------------------------------- ### Start Supabase with supabase start Source: https://github.com/alialavia/sqlproof/blob/main/website/src/content/docs/supabase-quickstart.md Starts the local Supabase stack before generating or running tests. Run this command before asking your agent for a test. ```bash supabase start ``` -------------------------------- ### Install SqlProof with pip Source: https://github.com/alialavia/sqlproof/blob/main/website/src/content/docs/getting-started.md Install the SqlProof library using pip. Requires Python 3.11+, PostgreSQL 13+ (or Docker for testcontainers), and the PostgreSQL client library (libpq) on the host. ```bash pip install sqlproof ``` -------------------------------- ### Run tests with pytest Source: https://github.com/alialavia/sqlproof/blob/main/website/src/content/docs/getting-started.md Command to run the property tests using pytest. ```bash pytest ``` -------------------------------- ### Install PostgreSQL client development tools Source: https://github.com/alialavia/sqlproof/blob/main/README.md Install the PostgreSQL client development tools before installing SqlProof from source. Commands for Debian/Ubuntu and macOS are provided. ```bash # Debian / Ubuntu sudo apt-get install build-essential libpq-dev # macOS brew install libpq export PATH="$(brew --prefix libpq)/bin:$PATH" ``` -------------------------------- ### sqlproof report Source: https://github.com/alialavia/sqlproof/blob/main/website/public/llms.txt CLI command to inspect a failure file saved under `.sqlproof/failures/`. ```APIDOC ## sqlproof report ### Description CLI command to inspect a failure file saved under `.sqlproof/failures/`. ### Parameters - **file** (string) - Required - Path to the failure file. ### Example ```bash sqlproof report .sqlproof/failures/example.json ``` ``` -------------------------------- ### Run tests with pytest tests/ -v Source: https://github.com/alialavia/sqlproof/blob/main/website/src/content/docs/supabase-quickstart.md Runs the generated property tests. Each test runs 20 generated examples by default, each with a freshly-generated dataset that respects every FK, CHECK, UNIQUE, and NOT NULL in the schema. If any example fails, Hypothesis shrinks to the smallest reproducer and reports it. ```bash pytest tests/ -v ``` -------------------------------- ### Mutation Scoring Setup: Test Container, Template DB, and Test Run Source: https://github.com/alialavia/sqlproof/blob/main/examples/inbox/README.md Commands to set up a dedicated Supabase-shaped Postgres test container, initialize it, create a template database by terminating and cloning the postgres DB, load all schema files, and run the mutation tests. Requires a test container (not supabase start) with zero open connections. ```bash # Supabase-shaped Postgres test container (same image as CI) docker run -d --name sqlproof-pg -e POSTGRES_PASSWORD=postgres \ -p 54399:5432 supabase/postgres:15.8.1.040 until docker exec sqlproof-pg pg_isready -U postgres >/dev/null 2>&1; do sleep 2; done docker exec -i sqlproof-pg psql -v ON_ERROR_STOP=1 -U postgres -d postgres \ < .github/actions/setup-supabase-test-db/sql/supabase-test-init.sql # Template: clone the auth-bearing postgres DB. The image's pg_cron/pg_net # workers hold sessions on it and the postgres role can't terminate them, # so terminate-and-clone in one supabase_admin session: docker exec -e PGPASSWORD=postgres sqlproof-pg psql -U supabase_admin -d template1 \ -c "SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE datname='postgres' AND pid <> pg_backend_pid()" \ -c 'CREATE DATABASE inbox_proof_template TEMPLATE postgres' \ -c 'ALTER DATABASE inbox_proof_template OWNER TO postgres' for f in examples/inbox/schema/*.sql; do docker exec -i sqlproof-pg psql -v ON_ERROR_STOP=1 -U postgres \ -d inbox_proof_template < "$f" done export SQLPROOF_TEMPLATE_URL='postgresql://postgres:postgres@127.0.0.1:54399/inbox_proof_template' uv run pytest examples/inbox/tests/mutation -m mutation -v ``` -------------------------------- ### Property failure output example Source: https://github.com/alialavia/sqlproof/blob/main/README.md Example output shown when a property fails, including the failure message, row context, and dataset shape. ```text Property failed: order totals match sum of line items Failure: AssertionError: expected totals to match Row context: {'order_id': 1} Dataset shape: {'orders': {'rows': 1}, 'line_items': {'rows': 2}} ``` -------------------------------- ### Install SqlProof with testcontainers extra Source: https://github.com/alialavia/sqlproof/blob/main/website/src/content/docs/guides/local-dev.md Install the optional testcontainers extra to enable SqlProof to manage disposable Postgres instances. Docker must be running when using testcontainers. ```bash pip install "sqlproof[testcontainers]" ``` -------------------------------- ### Run the Inbox sample with sqlproof and Supabase Source: https://github.com/alialavia/sqlproof/blob/main/website/src/content/docs/examples/inbox/index.md Sets up the environment: installs sqlproof, starts Supabase, exports the database URL, applies the initial schema, and runs the test suite. Expect 9 failures and 2 skipped initially. ```bash pip install sqlproof supabase start export SUPABASE_DB_URL='postgresql://postgres:postgres@127.0.0.1:54322/postgres' psql "$SUPABASE_DB_URL" -f examples/inbox/schema/001_initial.sql pytest examples/inbox/tests -v # 9 failures + 2 skipped ``` -------------------------------- ### SqlProof API usage example Source: https://github.com/alialavia/sqlproof/blob/main/README.md Shows the main SqlProof API: creating a proof from a schema file or connection string, running property checks, invariants, ad-hoc fixture rows, and disconnecting. The invariant shorthand runs a query against each generated dataset and raises SqlProofUsageError if the query is not a plain SELECT cols FROM table when no connection is provided. ```python proof = SqlProof.from_schema_file("./schema.sql") proof = SqlProof.from_connection_string("postgresql://localhost/postgres") # Property runner (decorator shown above, or method form): proof.check("name", sizes={"orders": 10}, property=lambda db: ...) # Shorthand for "this query must return no rows". The query runs against each # generated dataset on the connected database; a query that errors raises. # (Without a connection only a plain `SELECT cols FROM table` can be evaluated; # anything else, e.g. a WHERE clause, raises SqlProofUsageError.) proof.invariant( "no bad rows", sizes={"orders": 10}, query="SELECT id FROM orders WHERE total < 0", expect_empty=True, ) # Ad-hoc fixture row (see above): order = proof.row_strategy("orders", customer_id=42).example() proof.disconnect() ``` -------------------------------- ### Download AGENTS.md for SqlProof Source: https://github.com/alialavia/sqlproof/blob/main/website/public/llms.txt Download the AGENTS.md file for agents without a plugin system. Copy it into the project root and load the SKILL.md files from the provided URLs. ```bash curl -O https://raw.githubusercontent.com/alialavia/sqlproof/main/AGENTS.md ``` -------------------------------- ### SqlProof.client_for_dataset Source: https://github.com/alialavia/sqlproof/blob/main/website/public/llms.txt Creates a SqlProofClient for a given dataset. This is used in Hypothesis-based tests to get a `db` client for the generated dataset. ```APIDOC ## SqlProof.client_for_dataset(dataset) ### Description Creates a SqlProofClient for a given dataset. This is used in Hypothesis-based tests to get a `db` client for the generated dataset. ### Parameters - **dataset** (dict) - Required - Dataset dictionary generated by `dataset_strategy`. ### Returns - **SqlProofClient** - A client for the given dataset. ### Example ```python with proof.client_for_dataset(dataset) as db: ... ``` ``` -------------------------------- ### Extra Step for Recipe 7 (Equivalence): Apply Workload Summary v2 Source: https://github.com/alialavia/sqlproof/blob/main/examples/inbox/README.md For recipe 7 (equivalence), run this additional psql command between steps 3 and 4 of the main setup to load the workload summary v2 schema. ```bash psql "$SUPABASE_DB_URL" -f examples/inbox/schema/008_add_workload_summary_v2.sql ``` -------------------------------- ### on_setup with self.enter for context managers Source: https://github.com/alialavia/sqlproof/blob/main/website/src/content/docs/api/state-machine.md Override on_setup to seed example-specific fixtures. Use self.enter to adopt context managers that live across rules but not across examples; they close in reverse-entry order during teardown. The savepoint rolls back inside example boundaries. ```python def on_setup(self) -> None: self.enter(as_supabase_user(self.db, self.user_id)) self.enter(self.db.savepoint()) # roll back inside example boundaries ``` -------------------------------- ### Initialize SqlProof from a schema file Source: https://github.com/alialavia/sqlproof/blob/main/website/src/content/docs/guides/local-dev.md Use SqlProof.from_schema_file() to set up SqlProof locally with a schema file. This is the easiest local setup. ```python from sqlproof import SqlProof proof = SqlProof.from_schema_file("./schema.sql") ``` -------------------------------- ### Install index_advisor extension Source: https://github.com/alialavia/sqlproof/blob/main/website/src/content/docs/guides/scale-analysis.md SqlProof never installs the extension. If missing, result.advisor_notes reports 'index_advisor not installed (CREATE EXTENSION index_advisor CASCADE)' and the measurement still stands. Install it once in the test database; with in_clone=True the throwaway copy inherits the extension. ```sql CREATE EXTENSION index_advisor CASCADE; -- also installs hypopg ``` -------------------------------- ### Clone and set up development environment with uv Source: https://github.com/alialavia/sqlproof/blob/main/CONTRIBUTING.md Clones the repository and installs dependencies using uv. Requires Python 3.11+ and uv. Installs runtime dependencies (hypothesis, PyGreSQL, postgast, rich) and dev toolchain (pytest, ruff, mypy, pyright, syrupy, mutmut). ```bash git clone https://github.com/alialavia/sqlproof.git cd sqlproof uv sync --extra dev ``` -------------------------------- ### Install sqlproof with pip or uv Source: https://github.com/alialavia/sqlproof/blob/main/README.md Install the sqlproof package using pip or uv. Requires Python 3.11+ and PostgreSQL 13+. ```bash pip install sqlproof # or: uv add sqlproof ``` -------------------------------- ### Inspect and replay counterexamples with sqlproof CLI Source: https://github.com/alialavia/sqlproof/blob/main/README.md Commands to inspect counterexamples written under `.sqlproof/failures/` and replay them, including loading failing rows into a database as a scenario. The `--as-scenario` option requires `--schema-file` and `--output` arguments. ```bash sqlproof report .sqlproof/failures/test_name.json sqlproof report .sqlproof/failures/test_name.json --format json sqlproof replay .sqlproof/failures/test_name.json # Reload the failing rows into a database as a scenario: sqlproof replay .sqlproof/failures/test_name.json --as-scenario \ --schema-file schema.sql --output scenarios/failure.scenario.yaml ``` -------------------------------- ### sqlproof replay Source: https://github.com/alialavia/sqlproof/blob/main/website/public/llms.txt CLI command to replay a failure file. Optionally converts the failing rows into a scenario for use with `scenarios up`. ```APIDOC ## sqlproof replay [--as-scenario] [--schema-file ] ### Description CLI command to replay a failure file. Optionally converts the failing rows into a scenario for use with `scenarios up`. ### Parameters - **file** (string) - Required - Path to the failure file. - **--as-scenario** (flag) - Optional - Convert the failing rows into a scenario. - **--schema-file** (string) - Optional - Path to the schema file (required when using `--as-scenario`). ### Example ```bash sqlproof replay .sqlproof/failures/example.json --as-scenario --schema-file schema.sql ``` ``` -------------------------------- ### Run the example with uv and pytest Source: https://github.com/alialavia/sqlproof/blob/main/examples/supabase_rls/README.md Sets the SQLPROOF_TEST_DATABASE_URL environment variable and runs the test suite for the example. The example creates its own schema and seed pool of auth.users rows on first import; re-runs are idempotent because DROP TABLE / DROP SCHEMA calls reset the example's tables without affecting other database objects. ```bash export SQLPROOF_TEST_DATABASE_URL=postgresql://postgres:postgres@127.0.0.1:54322/postgres uv run pytest examples/supabase_rls ``` -------------------------------- ### Run integration tests with Docker Postgres Source: https://github.com/alialavia/sqlproof/blob/main/CONTRIBUTING.md Starts a Postgres container using the supabase/postgres image, waits for readiness, installs plpgsql_check extension, runs the test suite against it, and tears down the container. Requires SQLPROOF_TEST_DATABASE_URL to point to the container. ```bash docker run -d --name sqlproof-pg \ -e POSTGRES_PASSWORD=postgres \ -p 54399:5432 \ supabase/postgres:15.8.1.040 ``` ```bash # Wait for Postgres, then install plpgsql_check (needed by some tests) until docker exec sqlproof-pg pg_isready -U postgres -d postgres >/dev/null 2>&1; do sleep 2; done docker exec sqlproof-pg psql -U postgres -d postgres \ -c "CREATE EXTENSION IF NOT EXISTS plpgsql_check;" ``` ```bash # Run the suite against it SQLPROOF_TEST_DATABASE_URL=postgresql://postgres:postgres@127.0.0.1:54399/postgres \ uv run pytest ``` ```bash # Tear down when done docker rm -f sqlproof-pg ``` -------------------------------- ### Initialize SqlProof from a connection string Source: https://github.com/alialavia/sqlproof/blob/main/website/src/content/docs/guides/local-dev.md Use SqlProof.from_connection_string() with the DATABASE_URL environment variable to connect to a local Postgres test database. ```python import os from sqlproof import SqlProof proof = SqlProof.from_connection_string(os.environ["DATABASE_URL"]) ``` -------------------------------- ### Minimal auth.uid() stub for plain Postgres Source: https://github.com/alialavia/sqlproof/blob/main/website/public/llms.txt Creates a minimal auth schema, users table, and auth.uid() function that reads the 'sub' claim from request.jwt.claims. Needed on plain Postgres when the Supabase GoTrue migration is not applied; without it auth.uid() silently returns NULL and RLS tests pass for the wrong reason. Also creates the 'authenticated' role (plus GRANTs on your tables, views, and auth.uid()). ```sql create schema if not exists auth; create table auth.users (id uuid primary key, email text not null unique); create function auth.uid() returns uuid language sql stable as $$ select (nullif(current_setting('request.jwt.claims', true), '')::jsonb ->> 'sub')::uuid $$; create role authenticated nologin; -- plus GRANTs on your tables, views and auth.uid() ``` -------------------------------- ### CREATE EXTENSION index_advisor CASCADE Source: https://github.com/alialavia/sqlproof/blob/main/website/src/content/docs/guides/scale-analysis.md Install the index_advisor extension in the test database. SqlProof never installs the extension. If it is missing, result.advisor_notes says so and the measurement still stands. Install it once in your test database. ```APIDOC ## CREATE EXTENSION index_advisor CASCADE ### Description Install the index_advisor extension in the test database. SqlProof never installs the extension. If it is missing, result.advisor_notes says so and the measurement still stands. Install it once in your test database. ### SQL ```sql CREATE EXTENSION index_advisor CASCADE; -- also installs hypopg ``` ``` -------------------------------- ### Property tests for get_dashboard_summary RPC Source: https://github.com/alialavia/sqlproof/blob/main/website/src/content/docs/supabase-quickstart.md Two Hypothesis property tests verifying the get_dashboard_summary RPC: the project owner sees the correct event count, and a non-member sees zero events. Uses dataset_strategy to generate datasets and as_rls_user to simulate RLS users. Each test runs 20 generated examples by default; failures shrink to the smallest reproducer. ```python """Property tests for get_dashboard_summary.""" from hypothesis import given from hypothesis import strategies as st from sqlproof import SqlProof from sqlproof.contrib.supabase import as_rls_user @given(data=st.data(), event_count=st.integers(min_value=1, max_value=20)) def test_owner_sees_event_count_for_their_project( supabase_proof: SqlProof, data, event_count: int ) -> None: dataset = data.draw(supabase_proof.dataset_strategy( sizes={"projects": 1, "events": event_count}, )) with supabase_proof.client_for_dataset(dataset) as db: project = dataset["projects"][0] with as_rls_user(db, project["user_id"]): payload = db.scalar( "SELECT get_dashboard_summary(%s::uuid)", project["id"] ) assert payload["event_count"] == event_count @given(data=st.data(), event_count=st.integers(min_value=1, max_value=20)) def test_non_member_sees_zero_event_count( supabase_proof: SqlProof, data, event_count: int ) -> None: dataset = data.draw(supabase_proof.dataset_strategy( sizes={"projects": 1, "events": event_count, "auth.users": 2}, )) with supabase_proof.client_for_dataset(dataset) as db: project = dataset["projects"][0] # The seeded test-user pool gives us a second user_id that's # not the project owner — exactly what we need for the # non-member case. non_member = next( u for u in dataset["auth.users"] if u["id"] != project["user_id"] ) with as_rls_user(db, non_member["id"]): payload = db.scalar( "SELECT get_dashboard_summary(%s::uuid)", project["id"] ) assert payload["event_count"] == 0 ``` -------------------------------- ### Run pytest with SUPABASE_DB_URL environment variable Source: https://github.com/alialavia/sqlproof/blob/main/website/public/llms.txt Set SUPABASE_DB_URL (or SQLPROOF_DATABASE_URL, or --sqlproof-database-url) to point to a Supabase local database, then run pytest. The plugin ships fixtures proof/db and supabase_proof/supabase_db for RLS tests. Each test runs in a savepoint that rolls back. ```bash export SUPABASE_DB_URL='postgresql://postgres:postgres@127.0.0.1:54322/postgres' # supabase start pytest tests/ -v ``` -------------------------------- ### Console report from plpgsql_coverage Source: https://github.com/alialavia/sqlproof/blob/main/SPEC.md Example output of the console report showing per-function statement and branch coverage percentages. ```text PL/pgSQL coverage: 1/2 functions fully covered get_user_usage_total stmt 75% branch 50% (6/8 executable lines) ------------------------------------------------------------ > 1 1 BEGIN > 2 1 SELECT ... 5 IF total < 0 THEN 6 RAISE EXCEPTION '...' get_geo_performance stmt 100% branch 100% (42/42 executable lines) ``` -------------------------------- ### SqlProofStateMachine.enter(cm) Source: https://github.com/alialavia/sqlproof/blob/main/website/src/content/docs/api/state-machine.md Adopts a context manager for the duration of the current example. Closes in reverse-entry order during teardown. Use it for resources that must live across rules but not across examples. ```APIDOC ## [METHOD] enter(cm) ### Description Adopts a context manager for the duration of the current example. Closes in reverse-entry order during teardown. Use it for resources that must live across rules but not across examples. ### Method enter ### Parameters - **cm** (context manager) - Required - The context manager to adopt for the current example. ### Request Example ```python def on_setup(self) -> None: self.enter(as_supabase_user(self.db, self.user_id)) self.enter(self.db.savepoint()) # roll back inside example boundaries ``` ### Response No return value documented. ``` -------------------------------- ### Install pbt-skills and sqlproof-skills plugins in Claude Code Source: https://github.com/alialavia/sqlproof/blob/main/AGENTS.md Run these commands in Claude Code to install the two plugins this file builds on. The project ships a .claude/settings.json that will prompt you to install both declared plugins on your first session. ```shell /plugin install alialavia/pbt-skills /plugin install alialavia/sqlproof-skills ``` -------------------------------- ### Console Failure Output Example Source: https://github.com/alialavia/sqlproof/blob/main/SPEC.md Shows the rich-formatted failure output for a property test, including the counterexample, failing assertion, and reproduction command. The output degrades gracefully in non-TTY environments. ```text ✗ Property failed: order totals match line items After 23 runs · seed: 1708891234 · shrunk 4 times Row context: {order_id: 1} Counterexample: customers: [{id: 1, name: ''}] orders: [{id: 1, customer_id: 1, total: 100.00}] line_items: - {id: 1, order_id: 1, price: 30.00, quantity: 2} - {id: 2, order_id: 1, price: 50.00, quantity: 1} Failing assertion: abs(stored - computed) < Decimal('0.01') where stored=Decimal('100.00'), computed=Decimal('110.00') Reproduce: pytest tests/test_orders.py::test_order_total_matches_line_items \ --sqlproof-seed=1708891234 Full counterexample written to: .sqlproof/failures/test_order_total_matches_line_items.json ``` -------------------------------- ### SqlProof.row_strategy Source: https://github.com/alialavia/sqlproof/blob/main/README.md Generates an ad-hoc fixture row for a table with optional column overrides. Returns an example row from the strategy. ```APIDOC ## SqlProof.row_strategy ### Description Generates an ad-hoc fixture row for a table with optional column overrides. Returns an example row from the strategy. ### Method Method ### Parameters - **table** (string) - Required - Name of the table. - **column_overrides** (dict) - Optional - Column values to override in the generated row. ### Returns - **dict** - An example row. ### Example ```python order = proof.row_strategy("orders", customer_id=42).example() ``` ``` -------------------------------- ### No database at all: install and run pytest Source: https://github.com/alialavia/sqlproof/blob/main/website/src/content/docs/guides/ci-cd.md Use these steps when tests only use the in-memory client or pure data generator, with no proof.check against a live DB. Drop both the service container and the SQLPROOF_DATABASE_URL env var. ```yaml - run: sudo apt-get update && sudo apt-get install -y libpq-dev - run: pip install sqlproof pytest - run: pytest ``` -------------------------------- ### Initialize sqlproof.scale package (src/sqlproof/scale/__init__.py) Source: https://github.com/alialavia/sqlproof/blob/main/docs/superpowers/plans/2026-09-03-bulk-generation-foundation.md Creates the scale package with a docstring indicating phase 2 will add sweep and fit. This is the minimal implementation to make the module importable. ```python # src/sqlproof/scale/__init__.py """Scale analysis: bulk loading now, sweep and fit in phase 2.""" ``` -------------------------------- ### SqlProof.__enter__ Source: https://github.com/alialavia/sqlproof/blob/main/SPEC.md Context manager entry point. Returns the instance itself. ```APIDOC ## SqlProof.__enter__ ### Description Context manager entry point. Returns the instance itself. ### Method Instance method ### Signature `__enter__(self) -> Self` ### Returns - **Self** - The SqlProof instance. ``` -------------------------------- ### Create minimal database role for SqlProof Source: https://github.com/alialavia/sqlproof/blob/main/website/src/content/docs/guides/security.md Creates a restricted PostgreSQL role with CONNECT and CREATE privileges on the test database. Avoid granting SUPERUSER or using production credentials. ```sql CREATE ROLE sqlproof_test LOGIN PASSWORD 'strong-password'; GRANT CONNECT ON DATABASE testdb TO sqlproof_test; GRANT CREATE ON DATABASE testdb TO sqlproof_test; ``` -------------------------------- ### Run SqlProof tests before every supabase db push Source: https://github.com/alialavia/sqlproof/blob/main/website/src/content/docs/supabase-quickstart.md Use this command to run your SqlProof tests before deploying migrations. If a test fails, the failing test name reads like a sentence (e.g., test_non_member_sees_zero_event_count failed), helping you fix the migration before it ships. ```bash pytest tests/ && supabase db push ``` -------------------------------- ### SqlProof.disconnect Source: https://github.com/alialavia/sqlproof/blob/main/README.md Closes the database connection. Should be called when done with the SqlProof instance. ```APIDOC ## SqlProof.disconnect ### Description Closes the database connection. Should be called when done with the SqlProof instance. ### Method Method ### Example ```python proof.disconnect() ``` ``` -------------------------------- ### SqlProofClient.get_generated_data Source: https://github.com/alialavia/sqlproof/blob/main/README.md Returns the generated dataset for the current test. Provides access to all generated rows. ```APIDOC ## SqlProofClient.get_generated_data ### Description Returns the generated dataset for the current test. Provides access to all generated rows. ### Method Method ### Returns - **dict** - Mapping of table names to generated rows. ### Example ```python data = db.get_generated_data() ``` ``` -------------------------------- ### Create template database from single schema file Source: https://github.com/alialavia/sqlproof/blob/main/website/src/content/docs/guides/mutation-testing.md Use when your schema is defined in one file. Creates an idle proof_template database and applies the schema. Avoids live dev database cloning failures. ```bash psql "$SUPABASE_DB_URL" -c 'CREATE DATABASE proof_template' TEMPLATE_URL="${SUPABASE_DB_URL%/*}/proof_template" psql "$TEMPLATE_URL" -f supabase/schemas/schema.sql ``` -------------------------------- ### SqlProofClient.scalar Source: https://github.com/alialavia/sqlproof/blob/main/README.md Executes a SQL query and returns a single scalar value. Useful for aggregate queries. ```APIDOC ## SqlProofClient.scalar ### Description Executes a SQL query and returns a single scalar value. Useful for aggregate queries. ### Method Method ### Parameters - **sql** (string) - Required - SQL query. - **params** (any) - Optional - Parameters to bind to the query. ### Returns - **any** - Scalar result. ### Example ```python total = db.scalar("SELECT count(*) FROM orders") ``` ``` -------------------------------- ### SqlProofClient.query_typed Source: https://github.com/alialavia/sqlproof/blob/main/README.md Executes a SQL query and returns rows typed as a specified model. Useful for type-safe access. ```APIDOC ## SqlProofClient.query_typed ### Description Executes a SQL query and returns rows typed as a specified model. Useful for type-safe access. ### Method Method ### Parameters - **sql** (string) - Required - SQL query. - **row_type** (type) - Required - Model class for row typing. ### Returns - **list** - List of typed rows. ### Example ```python typed = db.query_typed("SELECT id, total FROM orders", OrderRow) ``` ``` -------------------------------- ### SqlProofClient.query Source: https://github.com/alialavia/sqlproof/blob/main/README.md Executes a SQL query with parameters and returns the result rows. The client is passed to property functions. ```APIDOC ## SqlProofClient.query ### Description Executes a SQL query with parameters and returns the result rows. The client is passed to property functions. ### Method Method ### Parameters - **sql** (string) - Required - SQL query with placeholders. - **params** (any) - Optional - Parameters to bind to the query. ### Returns - **list** - List of rows. ### Example ```python rows = db.query("SELECT id, total FROM orders WHERE total >= %s", 0) ``` ``` -------------------------------- ### Create mutation package __init__.py Source: https://github.com/alialavia/sqlproof/blob/main/docs/superpowers/plans/2026-06-10-mutation-testing-v1.md Initializes the sqlproof.mutation package, re-exporting Drop, Mutant, MutationSet, and Replace from sqlproof.mutation.model. ```python from __future__ import annotations from sqlproof.mutation.model import Drop, Mutant, MutationSet, Replace __all__ = ["Drop", "Mutant", "MutationSet", "Replace"] ``` -------------------------------- ### SqlProof.check Source: https://github.com/alialavia/sqlproof/blob/main/README.md Runs a property-based test against generated datasets. The property function receives a SqlProofClient to query the database. ```APIDOC ## SqlProof.check ### Description Runs a property-based test against generated datasets. The property function receives a SqlProofClient to query the database. ### Method Method ### Parameters - **name** (string) - Required - Name of the property test. - **sizes** (dict) - Required - Mapping of table names to row counts for data generation. - **property** (callable) - Required - Function that takes a SqlProofClient and returns a boolean or raises an exception. ### Example ```python proof.check("name", sizes={"orders": 10}, property=lambda db: ...) ``` ``` -------------------------------- ### Replay counterexample as scenario and load it Source: https://github.com/alialavia/sqlproof/blob/main/website/src/content/docs/guides/scenarios.md Use `sqlproof replay` with `--as-scenario` to turn a failing property's counterexample into a scenario, then `sqlproof scenarios up` to load it into a database. `--schema-file schema.sql` can replace `--dsn`; the schema supplies keys and references. Each row becomes a pinned row named `_` for single-column keys, and foreign keys to counterexample rows become references. New keys are assigned in the same order, so relationships survive but key values do not; a key that is also a foreign key (e.g., `profiles.id` referencing `auth.users`) is pinned as a reference. Pass `--name` to choose the scenario's name. ```bash sqlproof replay .sqlproof/failures/test_totals.json --as-scenario \ --dsn "$DATABASE_URL" --output scenarios/totals_failure.scenario.yaml sqlproof scenarios up counterexample_test_totals --dsn "$DEV_DATABASE_URL" ``` -------------------------------- ### SqlProof.from_schema_file Source: https://github.com/alialavia/sqlproof/blob/main/README.md Creates a SqlProof instance from a schema file. This is a constructor method that initializes the proof runner with a SQL schema. ```APIDOC ## SqlProof.from_schema_file ### Description Creates a SqlProof instance from a schema file. This is a constructor method that initializes the proof runner with a SQL schema. ### Method Constructor ### Parameters - **schema_file** (string) - Required - Path to the SQL schema file. ### Returns - **SqlProof** - A new SqlProof instance. ### Example ```python proof = SqlProof.from_schema_file("./schema.sql") ``` ``` -------------------------------- ### SqlProof.check Source: https://github.com/alialavia/sqlproof/blob/main/website/public/llms.txt Method form of the decorator for defining a property-based test. It takes a name, sizes, and a property function that receives a `db` client. ```APIDOC ## SqlProof.check(name, sizes={...}, property=lambda db: ...) ### Description Method form of the decorator for defining a property-based test. It takes a name, sizes, and a property function that receives a `db` client. ### Parameters - **name** (string) - Required - Name of the check. - **sizes** (dict) - Required - Mapping of table names to row counts. - **property** (callable) - Required - Function that takes a `db` client and asserts a property. ### Example ```python proof.check("no_orphans", sizes={"orders": 20, "line_items": 50}, property=lambda db: ...) ``` ``` -------------------------------- ### SqlProof.invariant Source: https://github.com/alialavia/sqlproof/blob/main/README.md Shorthand for asserting that a query returns no rows. The query runs against each generated dataset; a query that errors raises an exception. ```APIDOC ## SqlProof.invariant ### Description Shorthand for asserting that a query returns no rows. The query runs against each generated dataset; a query that errors raises an exception. ### Method Method ### Parameters - **name** (string) - Required - Name of the invariant. - **sizes** (dict) - Required - Mapping of table names to row counts for data generation. - **query** (string) - Required - SQL query to execute. Must be a plain SELECT cols FROM table unless a connection is provided. - **expect_empty** (boolean) - Required - Set to True to assert the query returns no rows. ### Raises - **SqlProofUsageError** - If the query is not a plain SELECT and no connection is available. ### Example ```python proof.invariant( "no bad rows", sizes={"orders": 10}, query="SELECT id FROM orders WHERE total < 0", expect_empty=True, ) ``` ``` -------------------------------- ### Package marker for sqlproof.mutation.report (aggregate only) Source: https://github.com/alialavia/sqlproof/blob/main/docs/superpowers/plans/2026-06-18-mutation-dashboard.md Recommended version of `src/sqlproof/mutation/report/__init__.py` for this task, importing only `build_report` and `load_runs` from `aggregate`. Keeps tasks runnable in order; add `render_html` in Task 8. ```python from __future__ import annotations from sqlproof.mutation.report.aggregate import build_report, load_runs __all__ = ["build_report", "load_runs"] ``` -------------------------------- ### SqlProofClient query methods Source: https://github.com/alialavia/sqlproof/blob/main/README.md Shows the methods available on the SqlProofClient passed to property functions: query, scalar, query_typed, and get_generated_data. ```python rows = db.query("SELECT id, total FROM orders WHERE total >= %s", 0) total = db.scalar("SELECT count(*) FROM orders") typed = db.query_typed("SELECT id, total FROM orders", OrderRow) data = db.get_generated_data() ``` -------------------------------- ### Rebase onto origin/main after feat/inbox-sample merges Source: https://github.com/alialavia/sqlproof/blob/main/docs/superpowers/plans/2026-06-07-pgvector-foundation.md Run after confirming feat/inbox-sample is merged to main. If the merge hasn't happened yet, rebase onto feat/inbox-sample instead. The file examples/inbox/tests/_helpers.py must exist before proceeding. ```bash git fetch origin git rebase origin/main # after feat/inbox-sample merges # or, before that merge: git rebase feat/inbox-sample ``` -------------------------------- ### SqlProof.from_connection_string Source: https://github.com/alialavia/sqlproof/blob/main/README.md Creates a SqlProof instance from a database connection string. This is a constructor method that initializes the proof runner with a live database connection. ```APIDOC ## SqlProof.from_connection_string ### Description Creates a SqlProof instance from a database connection string. This is a constructor method that initializes the proof runner with a live database connection. ### Method Constructor ### Parameters - **connection_string** (string) - Required - PostgreSQL connection string. ### Returns - **SqlProof** - A new SqlProof instance. ### Example ```python proof = SqlProof.from_connection_string("postgresql://localhost/postgres") ``` ``` -------------------------------- ### Package marker for sqlproof.mutation.report (with render_html) Source: https://github.com/alialavia/sqlproof/blob/main/docs/superpowers/plans/2026-06-18-mutation-dashboard.md Initial package marker for `src/sqlproof/mutation/report/__init__.py` that imports `build_report`, `load_runs`, and `render_html`. The `render_html` import is added in Task 8; until then, comment out that line and the `__all__` entry, or implement Task 8 before importing the package. ```python from __future__ import annotations from sqlproof.mutation.report.aggregate import build_report, load_runs from sqlproof.mutation.report.render import render_html __all__ = ["build_report", "load_runs", "render_html"] ``` -------------------------------- ### SqlProofClient.execute Source: https://github.com/alialavia/sqlproof/blob/main/website/public/llms.txt Executes a SQL statement (e.g., INSERT, UPDATE, DELETE) and returns the number of affected rows. This method is available on the `db` fixture provided by the decorator. ```APIDOC ## SqlProofClient.execute(sql, *params) ### Description Executes a SQL statement (e.g., INSERT, UPDATE, DELETE) and returns the number of affected rows. This method is available on the `db` fixture provided by the decorator. ### Parameters - **sql** (string) - Required - SQL statement string. - **params** (variadic) - Optional - Statement parameters, splatted (not passed as a list). ### Returns - **int** - Number of affected rows. ### Example ```python affected = db.execute("DELETE FROM orders WHERE id = %s", 1) ``` ``` -------------------------------- ### Add 'tested with SqlProof' badge to README Source: https://github.com/alialavia/sqlproof/blob/main/README.md Markdown snippet for adding the 'tested with SqlProof' badge to a project README. The badge links to https://sqlproof.com. ```markdown [![tested with SqlProof](https://sqlproof.com/badges/tested-with.svg)](https://sqlproof.com) ``` -------------------------------- ### Turn UnhonoredCheckWarning into an error in pytest Source: https://github.com/alialavia/sqlproof/blob/main/README.md Add this to pytest configuration to treat sqlproof.exceptions.UnhonoredCheckWarning as an error, refusing schemas with uninterpretable CHECK constraints instead of warning. ```toml [tool.pytest.ini_options] filterwarnings = ["error::sqlproof.exceptions.UnhonoredCheckWarning"] ``` -------------------------------- ### Run full unit and meta test suite Source: https://github.com/alialavia/sqlproof/blob/main/docs/superpowers/plans/2026-06-07-pgvector-foundation.md Executes the unit and meta test suites. Expected result: all tests pass. ```bash uv run pytest tests/unit tests/meta -q ``` -------------------------------- ### SQL schema for orders and line_items Source: https://github.com/alialavia/sqlproof/blob/main/README.md Defines the orders and line_items tables with constraints including foreign keys, NOT NULL, and CHECK constraints. Used as input to SqlProof.from_schema_file. ```sql CREATE TABLE orders ( id SERIAL PRIMARY KEY, customer_id INTEGER NOT NULL, total NUMERIC(10,2) NOT NULL CHECK (total >= 0) ); CREATE TABLE line_items ( id SERIAL PRIMARY KEY, order_id INTEGER NOT NULL REFERENCES orders(id), quantity INTEGER NOT NULL CHECK (quantity > 0), price NUMERIC(10,2) NOT NULL CHECK (price > 0) ); ``` -------------------------------- ### Pytest fixtures: proof, db, supabase_proof, supabase_db Source: https://github.com/alialavia/sqlproof/blob/main/website/public/llms.txt Pytest plugin fixtures that provide SqlProof instances and database clients. The `supabase_proof` and `supabase_db` fixtures are for tests that touch `auth.uid()` or RLS. ```APIDOC ## Pytest fixtures: proof, db, supabase_proof, supabase_db ### Description Pytest plugin fixtures that provide SqlProof instances and database clients. The `supabase_proof` and `supabase_db` fixtures are for tests that touch `auth.uid()` or RLS. ### Fixtures - **proof** - A SqlProof instance. - **db** - A SqlProofClient for the current test. - **supabase_proof** - A SqlProof instance configured for Supabase (seeds a deterministic `auth.users` pool). - **supabase_db** - A SqlProofClient for Supabase tests. ### Usage ```python def test_example(db): rows = db.query("SELECT * FROM orders") assert rows ``` ### Configuration Set `SUPABASE_DB_URL` (or `SQLPROOF_DATABASE_URL`, or `--sqlproof-database-url`) to the database connection string. ### Example ```bash export SUPABASE_DB_URL='postgresql://postgres:postgres@127.0.0.1:54322/postgres' pytest tests/ -v ``` ``` -------------------------------- ### sqlproof scenarios CLI commands Source: https://github.com/alialavia/sqlproof/blob/main/website/src/content/docs/guides/scenarios.md Lists scenarios, shows a scenario's resolved references, and loads a scenario into a database. The --schema-file and --dsn flags are required for show and up respectively. ```bash sqlproof scenarios list sqlproof scenarios show tiered_customers --schema-file schema.sql sqlproof scenarios up tiered_customers --dsn "$DATABASE_URL" ``` -------------------------------- ### Run both test suites (Step 7) Source: https://github.com/alialavia/sqlproof/blob/main/docs/superpowers/plans/2026-09-10-scale-measurement.md Runs the unit and integration tests for scale argument resolvers and live probe. Expected to pass. ```bash uv run pytest tests/unit/test_scale_args.py tests/integration/test_scale_probe_live.py -v ``` -------------------------------- ### Anti-pattern: hand-rolled INSERT in a test helper Source: https://github.com/alialavia/sqlproof/blob/main/README.md Shows a fragile test helper that manually inserts a row, which silently breaks when a migration adds a NOT NULL column, causing a cryptic NotNullViolation later. ```python # Anti-pattern: hand-rolled INSERT in a test helper. def insert_project(db, owner_id, *, name): db.execute( "INSERT INTO projects (id, user_id, name) VALUES (%s, %s, %s)", new_id(), owner_id, name, ) ``` -------------------------------- ### SqlProof Convenience Constructors Source: https://github.com/alialavia/sqlproof/blob/main/SPEC.md Three constructors for creating SqlProof instances: from_schema_file, from_connection_string, and from_config. Each requires either a schema file or a connection string. ```python SqlProof.from_schema_file("./schema.sql") SqlProof.from_connection_string(os.environ["DATABASE_URL"]) SqlProof.from_config(SqlProofConfig(...)) ``` -------------------------------- ### Implement scale_analysis entry point in src/sqlproof/scale/__init__.py Source: https://github.com/alialavia/sqlproof/blob/main/docs/superpowers/plans/2026-09-10-scale-measurement.md Public entry point for scale measurement. It opens its own autocommit connection because the sweep issues TRUNCATE, COPY, and ANALYZE. Raises ValueError if the SqlProof instance was constructed without a connection_string. ```python # src/sqlproof/scale/__init__.py """Scale measurement: is this function's growth curve acceptable? The output is an assertion, not a report -- CI goes red when someone writes a query that will not survive growth, the way `assert_no_survivors()` works for mutation testing. """ from __future__ import annotations from collections.abc import Mapping, Sequence from typing import Any import psycopg from sqlproof.scale.args import heaviest, median_key, random_key from sqlproof.scale.result import ScaleResult from sqlproof.scale.sweep import run_sweep __all__ = [ "ScaleResult", "heaviest", "median_key", "random_key", "scale_analysis", ] def scale_analysis( proof: Any, function: str, *, sizes: Mapping[str, int], args: Sequence[Any] = (), **kwargs: Any, ) -> ScaleResult: """Measure how `function` scales, using `proof`'s schema and database. Opens its own autocommit connection: the sweep issues TRUNCATE, COPY and ANALYZE, which want a lifecycle of their own rather than sharing the property runner's transaction. """ dsn = proof.config.connection_string if dsn is None: msg = ( "scale_analysis needs a real database: construct SqlProof with " "a connection_string rather than a schema file." ) raise ValueError(msg) with psycopg.connect(dsn, autocommit=True) as conn: return run_sweep(conn, proof.schema_info, function, sizes=sizes, args=args, **kwargs) ``` -------------------------------- ### Run Postgres-Backed Integration Tests Source: https://github.com/alialavia/sqlproof/blob/main/README.md Runs optional integration tests using the SQLPROOF_TEST_DATABASE_URL environment variable, plus benchmark tests. Integration tests create and drop a temporary schema named sqlproof_it_*. ```bash SQLPROOF_TEST_DATABASE_URL='postgresql://postgres:postgres@127.0.0.1:5432/postgres' uv run pytest tests/integration uv run pytest tests/benchmarks ``` -------------------------------- ### Run unit tests and full suite with coverage Source: https://github.com/alialavia/sqlproof/blob/main/CONTRIBUTING.md Runs unit tests (no database required, fast) and the full test suite with coverage gate matching CI. The coverage command requires a coverage threshold of 95%. ```bash # Unit tests only — no database required, fast (~3s) uv run pytest tests/unit ``` ```bash # Full suite with coverage gate (matches CI) uv run pytest --cov=sqlproof --cov-fail-under=95 ``` -------------------------------- ### Property test with SqlProof and pytest Source: https://github.com/alialavia/sqlproof/blob/main/README.md Uses SqlProof.from_schema_file to load the schema, then decorates a pytest test with @sqlproof to generate rows and run the property under Hypothesis. The test asserts no orphan line items exist. ```python from sqlproof import SqlProof, sqlproof proof = SqlProof.from_schema_file("./schema.sql") @sqlproof(proof, sizes={"orders": 20, "line_items": 50}, runs=50) def test_no_orphan_line_items(db): rows = db.query(""" SELECT li.id FROM line_items li LEFT JOIN orders o ON li.order_id = o.id WHERE o.id IS NULL """) assert rows == [] ``` -------------------------------- ### sqlproof scenarios CLI commands Source: https://github.com/alialavia/sqlproof/blob/main/AGENTS.md Shows and loads scenarios from the command line. Use 'show' to validate against the schema without a database and print row counts and named row keys. Use 'up' to load into a database; it refuses tables that already hold rows. Never pass --truncate-existing without asking the user. ```bash sqlproof scenarios show tiered_customers --schema-file supabase/schemas/schema.sql # no DB sqlproof scenarios up tiered_customers --dsn "$SQLPROOF_DATABASE_URL" ```