Replies: 2 comments
-
|
The issue is that For dynamic column names you need sql.unsafe(): That should give you what you expect. BUT: Since unsafe does exactly what it says, you want to make sure those column names aren't coming from user input directly. If they are, whitelist them first: The reason this works differently than Knex is that Knex has its own query builder that knows the difference between a column reference and a value. Bun's sql template literals are more bare metal, they just do parameterised queries, and SQL parameters can only be values not identifiers. So anything structural (column names, table names, ORDER BY directions, etc) needs the unsafe escape hatch. |
Beta Was this translation helpful? Give feedback.
-
|
The issue is that For dynamic column names you need const cityFieldsList = ["id", "title"]
const columns = cityFieldsList.join(", ")
const cities = await sql`SELECT ${sql.unsafe(columns)} FROM city LIMIT ${2}`That should give you what you expect. Important though: since const allowedColumns = ["id", "title", "name", "population"]
const requestedColumns = ["id", "title"] // from user or wherever
const safeColumns = requestedColumns.filter(col => allowedColumns.includes(col))
if (safeColumns.length === 0) {
throw new Error("no valid columns")
}
const cities = await sql`SELECT ${sql.unsafe(safeColumns.join(", "))} FROM city LIMIT ${2}`The reason this works differently than Knex is that Knex has its own query builder that knows the difference between a column reference and a value. Bun's sql template literals are more bare metal, they just do parameterized queries, and SQL parameters can only be values not identifiers. So anything structural (column names, table names, ORDER BY directions, etc) needs the unsafe escape hatch. |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
in Knexjs I do it this way
in Bun I do it this way
I receive
[{"json":["id","title"]},{"json":["id","title"]}]How to set a variable to an array of strings for select.
P.S. I only present one option here, but I have used many of them.
Beta Was this translation helpful? Give feedback.
All reactions