Skip to content

How to use "?" placeholders with bigint values? #46

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

Closed
cakoose opened this issue Oct 11, 2019 · 6 comments
Closed

How to use "?" placeholders with bigint values? #46

cakoose opened this issue Oct 11, 2019 · 6 comments
Labels

Comments

@cakoose
Copy link

cakoose commented Oct 11, 2019

Some of our columns are bigints and we're currently using BigNumber.js to work with those values.

My first attempt:

const n = new BigNumber('26000000000000000')
connection.query(`SELECT ?;`, [n], ...)
// SELECT `s` = 1, `e` = 16, `c` = 260, `_isBigNumber` = true

DoingBigNumber.toString() fixes that:

connection.query(`SELECT ?;`, [n.toString()], ...)
// SELECT '26000000000000000'

But the problem is that quoting numbers causes MySQL to treat the value differently, and lose precision when doing arithmetic (bug):

SELECT 26000000000012345;            // 26000000000012345
SELECT '26000000000012345';          // 26000000000012345
SELECT 12345 + 26000000000000000;    // 26000000000012345
SELECT 12345 + '26000000000000000';  // 2.6000000000012344e16

Is there a way to use a "?" placeholder to produce an unquoted bigint value?

@dougwilson
Copy link
Member

Something like the following:

console.log(SqlString.format('SELECT ?', [SqlString.raw(n.toString())]))

@cakoose
Copy link
Author

cakoose commented Oct 11, 2019

Ah, thanks! That does work, but one concern is that we'd lose some protection against SQL injection.

Does the "mysql" package allow replacing "sqlstring" with a different quoting function? I could write a custom function that handles all the standard types and also handles BigNumber.js.

@dougwilson
Copy link
Member

@cakoose
Copy link
Author

cakoose commented Oct 11, 2019

Thanks, again!

@dougwilson
Copy link
Member

No problem at all! Node.js updated the JavaScript and supports native BigInts now. I don't think this lib works with them, but I should be able to add support, which would mean if you're able to use the native BitInts, then you can use this without modification. It would be like console.log(SqlString.format('SELECT ?', [26000000000000000n]))

@cakoose
Copy link
Author

cakoose commented Oct 12, 2019

Yeah, BigInts currently come through quoted as well. Would be nice to fix that.

(It'll take us a while to migrate from BigNumber.js to native BigInt, so we'll need to use one of the other workarounds for now...)

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

2 participants