Federico Bellucci
Federico Bellucci

Reputation: 685

How do I add a conditional set clause to a slonik sql query?

I'm building a postgres query using slonik to update a user table. The passwordHash column should be changed only if the passwordHash variable is not null, otherwise it should be left untouched.

I've tried with a nested rule:

import { createPool, sql } from 'slonik'

const dbPool = createPool()

const updateUser = await dbPool.connect(async (conn) => {
  return conn.one(sql`
    UPDATE users 
    SET "name" = ${name},
      "email" = ${email},
      ${passwordHash ? sql`"passwordHash" = ${passwordHash},` : ''}
    WHERE "id" = ${id} 
    RETURNING *
  `)
})

But I'm getting the error: syntax error at or near "$3"

What's the correct way to do that?

Upvotes: 1

Views: 611

Answers (1)

Jan Paepke
Jan Paepke

Reputation: 2027

probably a bit late, but you could use coalesce.

const updateUser = await dbPool.connect(async (conn) => {
  return conn.one(sql`
    UPDATE users 
    SET "name" = ${name},
      "email" = ${email},
      "passwordHash" = coalesce(${passwordHash}, passwordHash)
    WHERE "id" = ${id} 
    RETURNING *
  `)
})

if passwordHash can also be undefined, go coalesce(${passwordHash ?? null}, passwordHash)

Upvotes: 0

Related Questions