Skip to content

Commit

Permalink
Add explain plan support for Postgres 14 (#76)
Browse files Browse the repository at this point in the history
  • Loading branch information
amari authored Dec 16, 2022
1 parent 4e47108 commit ef6fa91
Showing 1 changed file with 9 additions and 3 deletions.
12 changes: 9 additions & 3 deletions internal/pginfer/explain.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package pginfer
import (
"context"
"fmt"

"github.com/jschaf/pggen/internal/ast"
)

Expand All @@ -23,22 +24,27 @@ type Plan struct {
Outputs []string // the output expressions if any
}

type ExplainQueryResultRow struct {
Plan map[string]interface{} `json:"Plan,omitempty"`
QueryIdentifier *uint64 `json:"QueryIdentifier,omitempty"`
}

// explainQuery executes explain plan to get the node plan type and the format
// of the output columns.
func (inf *Inferrer) explainQuery(query *ast.SourceQuery) (Plan, error) {
explainQuery := `EXPLAIN (VERBOSE, FORMAT JSON) ` + query.PreparedSQL
ctx, cancel := context.WithTimeout(context.Background(), defaultTimeout)
defer cancel()
row := inf.conn.QueryRow(ctx, explainQuery, createParamArgs(query)...)
explain := make([]map[string]map[string]interface{}, 0, 1)
explain := make([]ExplainQueryResultRow, 0, 1)
if err := row.Scan(&explain); err != nil {
return Plan{}, fmt.Errorf("explain prepared query: %w", err)
}
if len(explain) == 0 {
return Plan{}, fmt.Errorf("no explain output")
}
plan, ok := explain[0]["Plan"]
if !ok {
plan := explain[0].Plan
if len(plan) == 0 {
return Plan{}, fmt.Errorf("explain output had no 'Plan' node")
}

Expand Down

0 comments on commit ef6fa91

Please sign in to comment.