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

sql method throw error with template string #90

Closed
gyhyfj opened this issue May 7, 2024 · 2 comments
Closed

sql method throw error with template string #90

gyhyfj opened this issue May 7, 2024 · 2 comments

Comments

@gyhyfj
Copy link

gyhyfj commented May 7, 2024

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`
  1. 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
Copy link
Contributor

@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
Copy link
Contributor

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

@gyhyfj gyhyfj closed this as completed May 18, 2024
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