Created
November 5, 2021 10:42
-
-
Save tcard/ecc7f426d3ea6da62f4ded5888af3f03 to your computer and use it in GitHub Desktop.
This bad boy will open a Postgres plan visualizer in your browser (Mac) for the given query
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func ViewPlan(ctx context.Context, db sqler.Queryer, s string, params ...interface{}) { | |
explain, err := func() (string, error) { | |
rows, err := db.Query(ctx, `EXPLAIN (ANALYZE, COSTS, VERBOSE, BUFFERS, FORMAT JSON) `+s, params...) | |
if err != nil { | |
return "", err | |
} | |
defer rows.Close() | |
var explain strings.Builder | |
for rows.Next() { | |
var v string | |
err := rows.Scan(&v) | |
if err != nil { | |
return "", err | |
} | |
fmt.Fprintln(&explain, v) | |
} | |
return explain.String(), nil | |
}() | |
if err != nil { | |
fmt.Println("ExplainAnalyze:", err) | |
return | |
} | |
go func() (err error) { | |
defer func() { | |
if err != nil { | |
fmt.Println(err) | |
} | |
}() | |
body, _ := json.Marshal(map[string]interface{}{ | |
"plan": explain, | |
"query": s, | |
}) | |
resp, err := (&http.Client{ | |
CheckRedirect: func(req *http.Request, via []*http.Request) error { | |
return http.ErrUseLastResponse | |
}, | |
}).Post( | |
"https://explain.dalibo.com/new", | |
"application/json", bytes.NewReader(body), | |
) | |
if err != nil { | |
return err | |
} | |
defer resp.Body.Close() | |
err = exec.Command("open", resp.Header.Get("Location")).Run() | |
if err != nil { | |
return err | |
} | |
return nil | |
}() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment