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

db.prepare(string) function errors when trying to create a table with parameters #1269

Closed
AceKiron opened this issue Oct 2, 2024 · 3 comments
Labels

Comments

@AceKiron
Copy link

AceKiron commented Oct 2, 2024

Even a simple db.prepare('CREATE TABLE test (?)'); gives me an error on better-sqlite3 ^11.3.0.

        return this[cppdb].prepare(sql, this, false);
                           ^
SqliteError: near "?": syntax error
    at Database.prepare (C:\Users\aceki\Desktop\nitrite\node_modules\better-sqlite3\lib\methods\wrappers.js:5:21)
    at Object.createIfNotExists (C:\Users\aceki\Desktop\nitrite\migrate-table-sqlite.js:47:12)
    at module.exports (C:\Users\aceki\Desktop\nitrite\test\app\database\0_create_users_table.up.js:2:11)
    at C:\Users\aceki\Desktop\nitrite\index.js:134:28
    at FSReqCallback.oncomplete (node:fs:188:23) {
  code: 'SQLITE_ERROR'
}

Node.js v22.3.0
@neoxpert
Copy link
Contributor

neoxpert commented Oct 3, 2024

This is not a better-sqlite3 issue. The statement is just not correct. You cannot use a binding parameter to "replace" the column definition.

@AceKiron
Copy link
Author

AceKiron commented Oct 4, 2024

You cannot use a binding parameter to "replace" the column definition.

I know I'm late and that this issue has been closed now, but why can I not do that though? Why would that not work, but db.prepare('INSERT INTO people VALUES (?, ?, ?)') would? (I'm not 100% sure if that works, I just copied that from the docs).

@neoxpert
Copy link
Contributor

neoxpert commented Oct 4, 2024

It would not work for replacing a complete column definition, because binding parameters, aka dynamic parameters or dynamic variables, are used to replace the actual values within a statement but not for changing / defining structure.

While your insert statement could work using the binding parameters, it may fail if those parameters are not in the exact order of column definitions of the table. I strongly suggest to write verbose SQL statements and include column names at all times, e.g. db.prepare('INSERT INTO people (<name of column 1>, <name of column 2>, <name of column 3>) VALUES (?, ?, ?)').

While there might be some databases out there, that also allow for doing such things, like binding table or column names to a paramter, SQlite3 (the actual database used by this lib) does not.

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

No branches or pull requests

3 participants