db0 icon indicating copy to clipboard operation
db0 copied to clipboard

can't pass table name from variable without `{}`

Open cpreston321 opened this issue 10 months ago • 4 comments

Environment

Reproduction

I will add one here soon.

Describe the bug

// DOESNT WORK
// routes/tables/[name].get.ts
export default defineEventHandler(async (event) => {
  try {
    const db = useDatabase()
    const name = getRouterParam(event, 'name')
    const query = getQuery(event)
    const limit = (query?.limit ?? 10) as number

    const table = await db.sql`SELECT * FROM ${name} LIMIT ${limit}`

    return table.rows ?? []
  }
  catch (error) {
    createError({
      status: 500,
      name: 'ServerError',
      cause: 'Internal Server Error',
    })
  }
})
// DOES WORK
// routes/tables/[name].get.ts
export default defineEventHandler(async (event) => {
  try {
    const db = useDatabase()
    const name = getRouterParam(event, 'name')
    const query = getQuery(event)
    const limit = (query?.limit ?? 10) as number

    const table = await db.sql`SELECT * FROM {${name}} LIMIT {${limit}}`

    return table.rows ?? []
  }
  catch (error) {
    createError({
      status: 500,
      name: 'ServerError',
      cause: 'Internal Server Error',
    })
  }
})

Additional context

It seems to work fine if I add the {} around the variable but maybe that was intended and isn't documented.

Logs

near "?": syntax error

  at Database.prepare (node_modules/better-sqlite3/lib/methods/wrappers.js:5:21)
  at Object.prepare (node_modules/db0/connectors/better-sqlite3.mjs:24:29)
  at Object.sql (node_modules/db0/dist/index.mjs:34:38)
  at Object.handler (server/api/tables/[name].get.ts:9:1)
  at node_modules/h3/dist/index.mjs:1890:43
  at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
  at async node_modules/h3/dist/index.mjs:1962:19
  at async Object.callAsync (node_modules/unctx/dist/index.mjs:72:16)
  at async Server.toNodeHandle (node_modules/h3/dist/index.mjs:2249:7)

cpreston321 avatar Apr 11 '24 14:04 cpreston321