Skip to content

Conversation

@andrewmbenton
Copy link
Collaborator

This builds upon the database connection work for sqlc vet with the sqlc/db-prepare rule. If you have a PostgreSQL or MySQL database connection configured, you can now write vet rules (CEL expressions) that depend on the output from running EXPLAIN ... on your queries.

Depending on your database engine, the output will be available from the postgresql.explain or mysql.explain variables within your CEL expression. So rules like the following in your sqlc config are now possible:

...
rules:
- name: postgresql-query-too-costly
  message: "Query cost estimate is too high"
  rule: "postgresql.explain.plan.total_cost > 1.0"
- name: postgresql-no-seq-scan
  message: "Query plan results in a sequential scan"
  rule: "postgresql.explain.plan.node_type == 'Seq Scan'"
- name: mysql-query-too-costly
  message: "Query cost estimate is too high"
  rule: "has(mysql.explain.query_block.cost_info) && double(mysql.explain.query_block.cost_info.query_cost) > 2.0"
- name: mysql-must-use-primary-key
  message: "Query plan doesn't use primary key"
  rule: "has(mysql.explain.query_block.table.key) && mysql.explain.query_block.table.key != 'PRIMARY'"

See the documentation added to docs/howto/vet.md for more information.

@andrewmbenton andrewmbenton merged commit fc99f20 into main Jul 21, 2023
@andrewmbenton andrewmbenton deleted the andrew/vet-explain branch July 21, 2023 18:19
alfonsodev pushed a commit to ExponentiaTeam/sqlc that referenced this pull request Oct 13, 2025
…am environment (sqlc-dev#2489)

* A working prototype of sqlc vet with explain output

* Some improvements to sqlc vet with explain

* Clean up the PostgreSQLExplain proto message

* Improve vet handling of MySQL explain output

* Add a few more fields to the MySQLExplain proto message

* Wrap a little more context around CEL programs in vet rules

* Use proto messages for postgres and mysql cel env vars

* Introduce SQLCDEBUG=dumpexplain=1

* Cleaning up a little

* Adding some documentation for sqlc vet with `EXPLAIN ...` output

* Disable triggering MySQL explain vet rule in authors example
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

2 participants