Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select a UUID from a prepared statement in Postgres?

I'm trying to select a user based on a UUID:

const client = await this.pg.connect()
const { rowsAct } = await client.query(`SELECT * FROM users WHERE uid=$1`, [
  userUUID
])

I also tried without the variable:

const client = await this.pg.connect()
const { rowsAct } = await client.query(`SELECT * FROM users WHERE uid=$1`, [
  '4fcf0ca3-4e26-40a9-bbe5-78ff8fdb6e0f'
])

I tried using ::uuid casting but maybe I did it wrong. The returned rowsAct is always undefined.

I verified the userUUID variable was populated and was a valid uuid: console.log(typeof userUUID) // string

What am I doing wrong? How can I properly select a row form it's UUID?

Thanks!

like image 343
HypeWolf Avatar asked Oct 19 '25 09:10

HypeWolf


1 Answers

You'll need to wrap your argument in parentheses before applying the ::uuid type cast so that the prepared statement can properly interpolate argument.

SELECT * FROM users WHERE uid = ($1)::uuid

You can also cast the column itself to text but it's less performant since the query will have to cast each row.

SELECT * FROM users WHERE uid::text = $1
like image 118
Lumbi Avatar answered Oct 21 '25 22:10

Lumbi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!