In some situations it’s not obvious how to use the RETURNING SQL clause with Gorm and databases that support it, like CockroachDB.
The particular use case where I found it challenging is the following: I want to update multiple records with a WHERE clause, ORDER BY clause and LIMIT clause and immediately return the updated records without a second query.
The simplified CockroachDB table schema without indices and noise is:
My initial attempts were as follows.
|
|
Gorm builds the SQL statement successfully, but for some reason doesn’t include the ORDER BY and LIMIT clauses, which are very important in my particular case. Ok, let’s try with a raw SQL statement.
|
|
Gorm executes the complete correct query, but I couldn’t find a way to return/populate the records slice - it was always empty (tried with different arrangements and examples from the docs). Without any deep investigation on why that happens, it seems that Gorm just ignores the RETURNING data when executing raw SQL statements.
What finally worked for me seems a bit like a hack, but it does the job. By using the ORDER BY and LIMIT clauses directly in the WHERE clause, the query works correctly as I need it.
|
|
The examples use Updates with
map[string]interface{}
but the issue described here is not affected by that. Using struct or other ways for updating produces the same results.
LIMIT
when using a RETURNING
clause so another solution could be used, like SELECT FOR UPDATE
-> then update, and return the updated record.