I am fetching an issue where I have to generate dynamic ORDER BY clause for multiple columns.
Here is my sample query:
SELECT *
FROM user
WHERE gender = 'male'
ORDER BY created_at ASC, updated_at DESC
LIMIT 10 OFFSET 0;
Here, ORDER BY values will be dynamic and it is coming from user end.
My Progress:
const orderBy: string = 'ORDER BY created_at ASC, updated_at DESC';
SELECT *
FROM user
WHERE gender = 'male'
${orderBy}
LIMIT 10 OFFSET 0;
Here, if I pass the ORDER BY clause as ${orderBy}
, then it takes it as a value. It shows an error.
The SLONIK-generated SQL is like the below:
{
sql: "\n SELECT *\nFROM user\nWHERE gender = 'male'\n $1\nLIMIT 10 OFFSET 0;\n",
type: 'SLONIK_TOKEN_SQL',
values: [ 'ORDER BY created_at ASC, updated_at DESC' ]
}
Thanks in advance.