|
| 1 | +// @flow |
| 2 | + |
| 3 | +// Regexp construction enhanced from `postgres-interval`, which is licensed |
| 4 | +// under the MIT license and is copyright (c) Ben Drucker <bvdrucker@gmail.com> |
| 5 | +// (bendrucker.me). |
| 6 | + |
| 7 | +const NUMBER = "([+-]?\\d+)"; |
| 8 | +const YEAR = `${NUMBER}\\s+years?`; |
| 9 | +const MONTH = `${NUMBER}\\s+mons?`; |
| 10 | +const DAY = `${NUMBER}\\s+days?`; |
| 11 | +// NOTE: PostgreSQL automatically overflows seconds into minutes and minutes |
| 12 | +// into hours, so we can rely on minutes and seconds always being 2 digits |
| 13 | +// (plus decimal for seconds). The overflow stops at hours - hours do not |
| 14 | +// overflow into days, so could be arbitrarily long. |
| 15 | +const TIME = "([+-])?(\\d+):(\\d\\d):(\\d\\d(?:\\.\\d{1,6})?)"; |
| 16 | + |
| 17 | +const INTERVAL = new RegExp( |
| 18 | + "^\\s*" + |
| 19 | + // All parts of an interval are optional |
| 20 | + [YEAR, MONTH, DAY, TIME].map(str => "(?:" + str + ")?").join("\\s*") + |
| 21 | + "\\s*$" |
| 22 | +); |
| 23 | + |
| 24 | +export type Interval = { |
| 25 | + years: number, |
| 26 | + months: number, |
| 27 | + days: number, |
| 28 | + hours: number, |
| 29 | + minutes: number, |
| 30 | + seconds: number, |
| 31 | +}; |
| 32 | + |
| 33 | +// All intervals will have exactly these properties: |
| 34 | +const BASE: Interval = Object.freeze({ |
| 35 | + years: 0, |
| 36 | + months: 0, |
| 37 | + days: 0, |
| 38 | + hours: 0, |
| 39 | + minutes: 0, |
| 40 | + seconds: 0.0, |
| 41 | +}); |
| 42 | + |
| 43 | +export function parseInterval(interval: string): Interval { |
| 44 | + const result = { ...BASE }; |
| 45 | + |
| 46 | + if (!interval) { |
| 47 | + return result; |
| 48 | + } |
| 49 | + |
| 50 | + const matches = INTERVAL.exec(interval); |
| 51 | + if (!matches) { |
| 52 | + throw new Error(`Failed to parse interval '${interval}' from PostgreSQL`); |
| 53 | + } |
| 54 | + |
| 55 | + const [ |
| 56 | + , |
| 57 | + years, |
| 58 | + months, |
| 59 | + days, |
| 60 | + plusMinusTime, |
| 61 | + hours, |
| 62 | + minutes, |
| 63 | + seconds, |
| 64 | + ] = matches; |
| 65 | + |
| 66 | + const timeMultiplier = plusMinusTime === "-" ? -1 : 1; |
| 67 | + |
| 68 | + if (years) result.years = parseInt(years, 10); |
| 69 | + if (months) result.months = parseInt(months, 10); |
| 70 | + if (days) result.days = parseInt(days, 10); |
| 71 | + if (hours) result.hours = timeMultiplier * parseInt(hours, 10); |
| 72 | + if (minutes) result.minutes = timeMultiplier * parseInt(minutes, 10); |
| 73 | + // Seconds can be decimal; all other values are integer |
| 74 | + if (seconds) result.seconds = timeMultiplier * parseFloat(seconds); |
| 75 | + |
| 76 | + return result; |
| 77 | +} |
0 commit comments