Is it ok to use sql.raw to create a fully dynamic ORDER BY query?
letfield="createdAt"letdir="DESC"// generated like field.startsWith("+") ? "ASC" : "DESC"letorderToken=sql`
ORDER BY ${sql.identifier(field)}${sql.raw(dir)}'
`letq=sql`
SELECT * FROM "post"
${orderToken}
LIMIT 3
`
letfield='createdAt';letdir=field.startsWith('+')?sql`ASC`:sql`DESC`;letorderToken=sql`
ORDER BY ${sql.identifier([field])}${dir}'
`;letq=sql`
SELECT * FROM "post"
${orderToken}
LIMIT 3
`;
Thanks. What about optional ORDER BY? For WHERE you started with TRUE so the absence of conditions results in WHERE (true) which is syntactically correct and has no performance implications. I can't find anything than can be used to order by default:
ORDER BY ??? default ???
Another attempt with ?: breaks the placeholder ordering in query:
SELECT ${makeProjection(pick)}
FROM ${sql.identifier([table])}
WHERE ${makeWhere(filter)}
${sort ? sql`ORDER BY ${makeOrder(sort)}` : ``} -- doesn't work
LIMIT ${makeLimit(limit)}
OFFSET ${makeOffset(offset)}
Is it ok to use
sql.raw
to create a fully dynamicORDER BY
query?You don't need to:
sql
tags can be nested.Thanks. What about optional
ORDER BY
? ForWHERE
you started withTRUE
so the absence of conditions results inWHERE (true)
which is syntactically correct and has no performance implications. I can't find anything than can be used to order by default:Another attempt with
?:
breaks the placeholder ordering in query:Causes
I cannot recall the original reason for this constraint. Will likely remove this constraint. Track github.com/gajus/slonik/issues/93.