Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to run a query with multiple statements? #1090

Closed
curiosport opened this issue Sep 30, 2021 · 2 comments
Closed

How to run a query with multiple statements? #1090

curiosport opened this issue Sep 30, 2021 · 2 comments

Comments

@curiosport
Copy link

I would like to execute 2 queries in a single statement that affect two different tables.

This is what I have and it works:

field := "Something"

_, _ = dbpool.Exec(
	context.Background(),
	`DELETE FROM example.table1 WHERE oneColumn = ($1);`,
	field,
)

_, _ = dbpool.Exec(
	context.Background(),
	`INSERT INTO example.table2 (otherColumn) values ($1);`,
	field,
)

This is what I want:

field := "Something"

_, _ = dbpool.Exec(
	context.Background(),
	`DELETE FROM example.table1 WHERE oneColumn = ($1); INSERT INTO example.table2 (otherColumn) values ($1);`,
	field,
)

And this is what I get:
"cannot insert multiple commands into a prepared statement"

It is not in my interest to have them run simultaneously I just want to simplify the code.

@jackc
Copy link
Owner

jackc commented Oct 2, 2021

I would like to execute 2 queries in a single statement

The wire protocol only allows binding params into a single statement.

If you really want to use a single round trip you could use a writable CTE or you could use a Batch to bundle both together. But unless you have a specific reason, I would leave it as two commands.

@curiosport
Copy link
Author

I understand it is to avoid SQL injections, but I was expecting pgx to have a For function that iterates on each command and executes them independently. But well, from your answer I see that the best for now is to use two commands. So thank you very much for the information.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants