Skip to content

Instantly share code, notes, and snippets.

@zxt-tzx
Last active February 22, 2025 14:01
Show Gist options
  • Save zxt-tzx/71c3009077afc6a482b70cb61ae77902 to your computer and use it in GitHub Desktop.
Save zxt-tzx/71c3009077afc6a482b70cb61ae77902 to your computer and use it in GitHub Desktop.
Drizzle helper functions: explain
import type { SQLWrapper } from "drizzle-orm";
import { sql } from "drizzle-orm";
import type { DbClient } from "@/db";
export const explainAnalyze = async <T extends SQLWrapper>(
db: DbClient,
query: T,
) => {
const debugResult = await db.execute(sql`EXPLAIN ANALYZE ${query.getSQL()}`);
// Process each row first to handle vectors
const processedRows = debugResult.map((row) => {
const plan = row["QUERY PLAN"];
if (typeof plan === "string" && plan.includes("[") && plan.includes(",")) {
const vectorMatch = plan.match(/\[([-\d.,e\s]+)\]/);
if (vectorMatch) {
const vectorStr = vectorMatch[0];
const count = (vectorStr.match(/,/g) || []).length + 1;
return {
"QUERY PLAN": plan.replace(
vectorStr,
`[Vector with ${count} dimensions]`,
),
};
}
}
return row;
});
// Then concatenate the processed results
const queryPlan = processedRows.map((row) => row["QUERY PLAN"]).join("\n");
// eslint-disable-next-line no-console
console.debug(JSON.stringify({ "QUERY PLAN": queryPlan }, null, 2));
return await query;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment