Skip to content

Conversation

@cespare
Copy link

@cespare cespare commented Jan 31, 2025

sqlx has a handy feature that is mentioned in the README examples under the name "batch insert". I believe it comes from #285.

    personStructs := []Person{
        {FirstName: "Ardie", LastName: "Savea", Email: "[email protected]"},
        {FirstName: "Sonny Bill", LastName: "Williams", Email: "[email protected]"},
        {FirstName: "Ngani", LastName: "Laumape", Email: "[email protected]"},
    }

    _, err = db.NamedExec(`INSERT INTO person (first_name, last_name, email)
        VALUES (:first_name, :last_name, :email)`, personStructs)

Essentially, it recognizes VALUES (:first_name, :last_name, :email) and expands it out into a VALUES clause of the appropriate length.

It's called "batch insert" because the purpose is to support these kinds of INSERT queries. However, INSERT is not the only case where VALUES is used. Suppose I want to update several different rows at once using a single query. I could do this:

UPDATE t
SET
  first_name = u.first_name,
  last_name = u.last_name
FROM (
  VALUES (123, "Sonny Will", "Billiams"),
         (234, "Ngani", "Smith")
) AS u(id, first_name, last_name)
WHERE t.id = u.id

(I'm used to Postgres; not sure if this works in other DBs or not.)

I'd like to be able to use sqlx's VALUES-expansion for this as well:

UPDATE t
SET
  first_name = u.first_name,
  last_name = u.last_name
FROM (
  VALUES (:id, :first_name, :last_name)
) AS u(id, first_name, last_name)
WHERE t.id = u.id

The only reason this doesn't work today is that the regex which recognizes the VALUES list expect it to follow a ), as in an INSERT query.

This is related to a prior fix in this area: #734.

This lets it be used in non-INSERT scenarios as well. See the test for
such an example.
Copy link

@mrj0 mrj0 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

lgtm! VALUES thankfully isn't used in sql too often and enabling this postgres syntax would be handy.

Should it be mentioned in the readme?

mrj0 added a commit to Vinovest/sqlx that referenced this pull request Mar 21, 2025
@ccoVeille
Copy link

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

Successfully merging this pull request may close these issues.

3 participants