planetscale/database-js

LAST_INSERTED_ID comes back as string

arackaf opened this issue · 4 comments

The types returned by the http driver usually line up well with what's in the db, but for some reason LAST_INSERT_ID comes back as a string

const newId = await tx.execute("SELECT LAST_INSERT_ID() as id");
console.log(newId.rows, typeof newId.rows[0].id);

which prints

image

Hello @arackaf! Thanks for the issue.

This is actually lining up with what's returned by LAST_INSERT_ID. According to the MySQL docs, the type of LAST_INSERT_ID() is an unsigned big integer. Within our driver, we handled all 64-bit integers as strings, because of JavaScript limitations. This way, the user can handle that returned BigInt in their own way. Let me know if you have anymore questions!

Ohhhh that makes sense. JS numbers are 64 bit floating point, so I'm assuming the problem is that a 64 bit integer can exceed that, and cause overflow?

Sorry for the superfluous issue, but hopefully it'll help someone down the line

Yeah, and more specifically because the API itself is JSON, you can't correctly represent a 64 bit integer as a Number in JSON. So it's common to handle them as strings so the language can re-interpret them into a more... correct type.

Does JavaScript even have a native 64 bit integer we can use reliably and do the transformation automatically?

Yup, that's exactly it. And the JSON spec itself doesn't define integer precision so it's a bit of wild west depending on the interpreter. Lord default to a float64 to match what JavaScript supports.