Skip to content

Commit

Permalink
Better handling of millis and micros (#68)
Browse files Browse the repository at this point in the history
* Clean up TIMESTAMP issues
ZJONSSON#65
ZJONSSON#45
* Use MAX_SAFE_INTEGER for testing toPrimitive_TIME_MILLIS
  • Loading branch information
wilwade authored May 12, 2022
1 parent d382d0f commit 73cf70d
Showing 1 changed file with 10 additions and 5 deletions.
15 changes: 10 additions & 5 deletions lib/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -386,7 +386,8 @@ function toPrimitive_TIME_MILLIS(value: string | number) {
if (typeof value === `string`) {
v = parseInt(value, 10);
}
if (v < 0 || v > 0xffffffffffffffff || typeof v !== 'number') {
// Year 2255 bug. Should eventually switch to bigint
if (v < 0 || v > (Number.MAX_SAFE_INTEGER - 1) || typeof v !== 'number') {
throw 'invalid value for TIME_MILLIS: ' + value;
}

Expand Down Expand Up @@ -461,18 +462,22 @@ function toPrimitive_TIMESTAMP_MICROS(value: Date | string | number | bigint) {
}

/* convert from integer */
{
try {
// Will throw if NaN
const v = BigInt(value);
if (v < 0n /*|| isNaN(v)*/) {
throw 'invalid value for TIMESTAMP_MICROS: ' + value;
if (v < 0n) {
throw 'Cannot be less than zero';
}

return v;
} catch (e) {
throw 'invalid value for TIMESTAMP_MICROS: ' + value;
}
}

function fromPrimitive_TIMESTAMP_MICROS(value: number | bigint) {
return typeof value === 'bigint' ? new Date(Number(value / 1000n)): new Date(value / 1000);
if (typeof value === 'bigint') return new Date(Number(value / 1000n));
return new Date(value / 1000);
}

function toPrimitive_INTERVAL(value: INTERVAL) {
Expand Down

0 comments on commit 73cf70d

Please sign in to comment.