database-js icon indicating copy to clipboard operation
database-js copied to clipboard

UNIX_TIMESTAMP() results get parsed to JavaScript string, should be parsed as Number

Open vBohu opened this issue 1 year ago • 4 comments

From MySQL docs for UNIX_TIMESTAMP(): "The return value is an integer"

typeof RESULT_FROM_UNIX_TIMESTAMP === 'string' should be 'number'

Simple Number(RESULT_FROM_UNIX_TIMESTAMP) should do the trick to parse something like "1740868514" to 1740868514 Alternatively parseInt()

vBohu avatar Mar 01 '25 22:03 vBohu

The issue is they are int64 values which JavaScript can't safely represent. All int64's are parsed into string types so you can cast them how you'd like.

mattrobenolt avatar Mar 01 '25 22:03 mattrobenolt

See https://github.com/planetscale/database-js/issues/175 for example. There's been a few discussions around BigInt that got rejected.

mattrobenolt avatar Mar 01 '25 22:03 mattrobenolt

Maximum value is 4294967295 though, right? Because stored dates can only go up to 2106-02-07 06:28:15 UTC

That is easily within JS's safe range

vBohu avatar Mar 02 '25 14:03 vBohu

Right, I understand your point, but this is what MySQL says in our response:

    "result": {
        "fields": [
            {
                "name": "unix_timestamp()",
                "type": "INT64",
                "charset": 63,
                "flags": 32769
            }
        ],
        "rows": [
            {
                "lengths": [
                    "10"
                ],
                "values": "MTc0MDk0MDk2MQ=="
            }
        ]
    },

So our type is INT64. We treat INT64 as a string to be safe since we don't know if it's safe to be represented as a Number in JS or not. We document how to do your own cast function since you, the caller, would know this is going to be in a safe range. https://github.com/planetscale/database-js#custom-type-casting-function

But we can't very easily infer that, just because the function you called is unix_timestamp(), the type responded is still an INT64.

Conversely, if you do select now(), this actual type returned is a DATETIME rather than an INT64:

    "result": {
        "fields": [
            {
                "name": "now()",
                "type": "DATETIME",
                "charset": 63,
                "flags": 129
            }
        ],
        "rows": [
            {
                "lengths": [
                    "19"
                ],
                "values": "MjAyNS0wMy0wMiAxODo0NTo1MA=="
            }
        ]
    },

mattrobenolt avatar Mar 02 '25 18:03 mattrobenolt