sqlx icon indicating copy to clipboard operation
sqlx copied to clipboard

Relax constraint on VALUE clause expansion

Open cespare opened this issue 9 months ago • 0 comments

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.

cespare avatar Jan 31 '25 09:01 cespare