Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

I can't build sql queries with dynamic column sort and sort order. #495

Open
cococov opened this issue Nov 17, 2023 · 1 comment
Open

I can't build sql queries with dynamic column sort and sort order. #495

cococov opened this issue Nov 17, 2023 · 1 comment

Comments

@cococov
Copy link

cococov commented Nov 17, 2023

Due to pagination I need to make queries with different sort orders and even different column, but currently the @vercel/postgres clean my query, deleting my dynamic order.

// Works
await sql`SELECT * FROM metagame_cards ORDER BY occurrences DESC LIMIT ${query.pageSize} OFFSET ${query.page * query.pageSize}`;

// Doesn't work
await sql`SELECT * FROM metagame_cards ORDER BY ${columnSort} DESC LIMIT ${query.pageSize} OFFSET ${query.page * query.pageSize}`;

// Doesn't work
await sql`SELECT * FROM metagame_cards ORDER BY ${columnSort} ${sortOrder} LIMIT ${query.pageSize} OFFSET ${query.page * query.pageSize}`;

Is there a way to (at least in a dangerous way) do this?

@tcc-sejohnson
Copy link
Collaborator

We currently have a PR providing this functionality:

const orderbyColumn = identifiers('occurrences');
const orderbyDirection = sortOrder === 'DESC' ?  fragment`DESC` : fragment`ASC`;
await sql`SELECT * FROM metagame_cards ORDER BY ${orderByColumn} ${orderByDirection} LIMIT ${query.pageSize} OFFSET ${query.page * query.pageSize}`;

However, we don't know if that's going to be merged yet -- there's a good bit of security auditing to do and probably some discussions around API!

For now, you can use sql.query directly. It means you'll have to do some manual string-concatenation, which isn't the best, but it's the best workaround until something better like the above is merged!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants