porsager / porsager/postgres

Simple queries are still prepared when setting search_path

Open
#943 1 comment 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
JavaScript
Stars
8.7k
Forks
374
Avg merge
11d 16h
Merged PRs (30d)
1

Description

Hey,

while building a tool for managing a multi-tenant database I've found behaviour that doesn't seem intended. It can be triggered by this minimal reproduction:

const postgres = require("postgres");

const sql = postgres(null, {
	host: "localhost",
	port: 5432,
	user: "postgres",
	password: "VUYmFyBt8FHZ4Sr3EdFcWSMc",
	database: "firatcms",
	prepare: false,
	connection: {
		// search_path: "project_aq940fcg89", // Commenting in this line breaks
	},
});

const run = async () => {
	// await sql`SET search_path TO project_aq940fcg89;`; // Commenting in this line breaks
	await sql`	CREATE TABLE IF NOT EXISTS "abc" (
		"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
		"version" int NOT NULL
	);
	ALTER TABLE "abc" DROP CONSTRAINT IF EXISTS "version_unique";
	ALTER TABLE "abc" ADD CONSTRAINT "version_unique" UNIQUE ("version");`.simple();
};

run().then(() => {
	sql.end();
});

The main issue is that I have a query with multiple statements in there and I'd expect it to be not prepared. Firstly because I set prepare: false but also because I added .simple(). In the real code, I use sql.unsafe without a second arg and I checked there that the produced query always has simple: true which is correct as it's based on whether I pass in arguments or not.

After trying it out a bit more, I've found that this issue only occurs when I have a search path set either via the connection or via SET search_path

I tried debugging it myself for an hour now but it's probably some Postgres internals that I don't understand good enough

Contributor guide

No contributing guide indexed for this repository

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the minimal JavaScript reproduction in the issue, comparing prepare: false and .simple() with search_path set through connection or SET search_path. Trace the query handling and PostgreSQL behavior for this combination; done means the multi-statement query remains unprepared in both search_path cases, with regression coverage for the reported reproduction.

Written by the indexing model from the issue text.

Assessment

Tech stack
javascript, postgresql
Domain
databases
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.