From 6e0d6b9890207a77a4244d2f294f5763046796cb Mon Sep 17 00:00:00 2001 From: Konstantin Wohlwend Date: Sun, 29 Dec 2024 12:20:35 -0800 Subject: [PATCH] Better support for Supabase Studio index advisor --- apps/backend/src/prisma-client.tsx | 9 ++++++++- docker/dependencies/postgres-with-extensions/Dockerfile | 2 ++ 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/apps/backend/src/prisma-client.tsx b/apps/backend/src/prisma-client.tsx index 3167a6aec..e1703250b 100644 --- a/apps/backend/src/prisma-client.tsx +++ b/apps/backend/src/prisma-client.tsx @@ -67,7 +67,9 @@ async function rawQueryArray[]>(queries: Q): Promise<[] }, async () => { if (queries.length === 0) return [] as any; - const query = Prisma.sql` + // Prisma does a query for every rawQuery call by default, even if we batch them with transactions + // So, instead we combine all queries into one using WITH, and then return them as a single JSON result + const withQuery = Prisma.sql` WITH ${Prisma.join(queries.map((q, index) => { return Prisma.sql`${Prisma.raw("q" + index)} AS ( ${q.sql} @@ -83,6 +85,11 @@ async function rawQueryArray[]>(queries: Q): Promise<[] `; }), "\nUNION ALL\n")} `; + + // Supabase's index advisor only analyzes rows that start with "SELECT" (for some reason) + // Since ours starts with "WITH", we prepend a SELECT to it + const query = Prisma.sql`SELECT * FROM (${withQuery}) AS _`; + const rawResult = await prismaClient.$queryRaw(query) as { type: string, json: any }[]; const unprocessed = new Array(queries.length).fill(null).map(() => [] as any[]); for (const row of rawResult) { diff --git a/docker/dependencies/postgres-with-extensions/Dockerfile b/docker/dependencies/postgres-with-extensions/Dockerfile index e26193e96..b81ab1de5 100644 --- a/docker/dependencies/postgres-with-extensions/Dockerfile +++ b/docker/dependencies/postgres-with-extensions/Dockerfile @@ -18,6 +18,8 @@ RUN cd /index_advisor && make install RUN echo "CREATE EXTENSION pg_stat_statements;" >> /docker-entrypoint-initdb.d/init.sql RUN echo "CREATE EXTENSION hypopg;" >> /docker-entrypoint-initdb.d/init.sql RUN echo "CREATE EXTENSION index_advisor;" >> /docker-entrypoint-initdb.d/init.sql +RUN echo "CREATE ROLE anon;" >> /docker-entrypoint-initdb.d/init.sql +RUN echo "CREATE ROLE authenticated;" >> /docker-entrypoint-initdb.d/init.sql # Add args to Postgres entrypoint ENTRYPOINT ["sh", "-c", "\