unjs / db0

📚 Lightweight SQL Connector
https://db0.unjs.io
MIT License
171 stars 18 forks source link

`sql` method throw error with template string #90

Closed gyhyfj closed 6 months ago

gyhyfj commented 6 months ago

Environment

node 20.12.1 nitropack 2.9.6 better-sqlite3 9.6.0

Reproduction

  1. The following code works well without template string:

    const { rows } = await db.sql`SELECT * FROM bilibili_like`
  2. The following code throws error without template string:

    const tableName = 'bilibili_like'
    const { rows } = await db.sql`SELECT * FROM ${tableName}`

    Error:

    [nitro] [unhandledRejection] SqliteError: near "?": syntax error
    at Database.prepare (/root/code/nitro-app/node_modules/.pnpm/better-sqlite3@9.6.0/node_modules/better-sqlite3/lib/methods/wrappers.js:5:21)
    at Object.prepare (file:///root/code/nitro-app/node_modules/.pnpm/db0@0.1.4_better-sqlite3@9.6.0/node_modules/db0/connectors/better-sqlite3.mjs:24:29)
    at Object.sql (file:///root/code/nitro-app/node_modules/.pnpm/db0@0.1.4_better-sqlite3@9.6.0/node_modules/db0/dist/index.mjs:34:38)
    at Object.run (file:///root/code/nitro-app/.nitro/dev/index.mjs:928:17)
    at runTask (file:///root/code/nitro-app/.nitro/dev/index.mjs:610:36) {
    code: 'SQLITE_ERROR'
    }

Describe the bug

sql method throw error with template string

Additional context

No response

Logs

No response

amandesai01 commented 6 months ago

@gyhyfj please use staticParameters while using template literals in sql queries.

TLDR; fix like this:

const tableName = 'bilibili_like'
const { rows } = await db.sql`SELECT * FROM {${tableName}}`

Explanation: when you use template literals, db0 automatically converts them to prepared statements and tableNames are not allowed to be part of prepared statements.

Detailed Discussion: #77

amandesai01 commented 6 months ago

This issue can be closed now. Documentation initiative is being tracked in #77