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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant