package/license000644 0000002127 3560116604 010627 0ustar00000000 000000 The MIT License (MIT) Copyright (c) Ben Drucker (bendrucker.me) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. package/index.js000644 0000010725 3560116604 010732 0ustar00000000 000000 'use strict' module.exports = PostgresInterval function PostgresInterval (raw) { if (!(this instanceof PostgresInterval)) { return new PostgresInterval(raw) } Object.assign(this, parse(raw)) } const properties = ['years', 'months', 'days', 'hours', 'minutes', 'seconds'] PostgresInterval.prototype.toPostgres = function () { const filtered = properties.filter(key => Object.prototype.hasOwnProperty.call(this, key) && this[key] !== 0) // In addition to `properties`, we need to account for fractions of seconds. if (this.milliseconds && !filtered.includes('seconds')) { filtered.push('seconds') } if (filtered.length === 0) return '0' return filtered .map(function (property) { let value = this[property] || 0 // Account for fractional part of seconds, // remove trailing zeroes. if (property === 'seconds' && this.milliseconds) { value = (value + this.milliseconds / 1000).toFixed(6).replace(/\.?0+$/, '') } // fractional seconds will be a String, all others are Number const isSingular = String(value) === '1' // Remove plural 's' when the value is singular return value + ' ' + (isSingular ? property.replace(/s$/, '') : property) }, this) .join(' ') } const propertiesISOEquivalent = { years: 'Y', months: 'M', days: 'D', hours: 'H', minutes: 'M', seconds: 'S' } const dateProperties = ['years', 'months', 'days'] const timeProperties = ['hours', 'minutes', 'seconds'] // according to ISO 8601 PostgresInterval.prototype.toISOString = PostgresInterval.prototype.toISO = function () { return toISOString.call(this, { short: false }) } PostgresInterval.prototype.toISOStringShort = function () { return toISOString.call(this, { short: true }) } function toISOString ({ short = false }) { const datePart = dateProperties .map(buildProperty, this) .join('') const timePart = timeProperties .map(buildProperty, this) .join('') if (!timePart.length && !datePart.length) return 'PT0S' if (!timePart.length) return `P${datePart}` return `P${datePart}T${timePart}` function buildProperty (property) { let value = this[property] || 0 // Account for fractional part of seconds, // remove trailing zeroes. if (property === 'seconds' && this.milliseconds) { value = (value + this.milliseconds / 1000).toFixed(6).replace(/0+$/, '') } if (short && !value) return '' return value + propertiesISOEquivalent[property] } } const NUMBER = '([+-]?\\d+)' const YEAR = `${NUMBER}\\s+years?` const MONTH = `${NUMBER}\\s+mons?` const DAY = `${NUMBER}\\s+days?` // NOTE: PostgreSQL automatically overflows seconds into minutes and minutes // into hours, so we can rely on minutes and seconds always being 2 digits // (plus decimal for seconds). The overflow stops at hours - hours do not // overflow into days, so could be arbitrarily long. const TIME = '([+-])?(\\d+):(\\d\\d):(\\d\\d(?:\\.\\d{1,6})?)' const INTERVAL = new RegExp( '^\\s*' + // All parts of an interval are optional [YEAR, MONTH, DAY, TIME].map((str) => '(?:' + str + ')?').join('\\s*') + '\\s*$' ) // All intervals will have exactly these properties: const ZERO_INTERVAL = Object.freeze({ years: 0, months: 0, days: 0, hours: 0, minutes: 0, seconds: 0, milliseconds: 0.0 }) function parse (interval) { if (!interval) { return ZERO_INTERVAL } const matches = INTERVAL.exec(interval) || [] const [ , yearsString, monthsString, daysString, plusMinusTime, hoursString, minutesString, secondsString ] = matches const timeMultiplier = plusMinusTime === '-' ? -1 : 1 const years = yearsString ? parseInt(yearsString, 10) : 0 const months = monthsString ? parseInt(monthsString, 10) : 0 const days = daysString ? parseInt(daysString, 10) : 0 const hours = hoursString ? timeMultiplier * parseInt(hoursString, 10) : 0 const minutes = minutesString ? timeMultiplier * parseInt(minutesString, 10) : 0 const secondsFloat = parseFloat(secondsString) || 0 // secondsFloat is guaranteed to be >= 0, so floor is safe const absSeconds = Math.floor(secondsFloat) const seconds = timeMultiplier * absSeconds // Without the rounding, we end up with decimals like 455.99999999999994 instead of 456 const milliseconds = Math.round(timeMultiplier * (secondsFloat - absSeconds) * 1000000) / 1000 return { years, months, days, hours, minutes, seconds, milliseconds } } PostgresInterval.parse = parse package/package.json000644 0000001211 3560116604 011541 0ustar00000000 000000 { "name": "postgres-interval", "main": "index.js", "version": "4.0.0", "description": "Parse Postgres interval columns", "license": "MIT", "repository": "bendrucker/postgres-interval", "author": { "name": "Ben Drucker", "email": "bvdrucker@gmail.com", "url": "https://www.bendrucker.me" }, "engines": { "node": ">=12" }, "scripts": { "test": "standard && tape test.js" }, "keywords": [ "postgres", "interval", "parser" ], "dependencies": {}, "devDependencies": { "standard": "^16.0.0", "tape": "^5.0.0" }, "files": [ "index.js", "index.d.ts", "readme.md" ] } package/readme.md000644 0000003034 3560116604 011037 0ustar00000000 000000 # postgres-interval [![tests](https://github.com/bendrucker/postgres-interval/workflows/tests/badge.svg)](https://github.com/bendrucker/postgres-interval/actions?query=workflow%3Atests) > Parse Postgres interval columns ## Install ```sh npm install --save postgres-interval ``` ## Usage ```js var parse = require('postgres-interval') var interval = parse('01:02:03') // => { hours: 1, minutes: 2, seconds: 3 } interval.toPostgres() // 1 hour 2 minutes 3 seconds interval.toISOString() // P0Y0M0DT1H2M3S interval.toISOStringShort() // PT1H2M3S ``` This package parses the default Postgres interval style. If you have changed [`intervalstyle`](https://www.postgresql.org/docs/current/runtime-config-client.html#GUC-INTERVALSTYLE), you will need to set it back to the default: ```sql set intervalstyle to default; ``` ## API #### `parse(pgInterval)` -> `interval` ##### pgInterval *Required* Type: `string` A Postgres interval string. #### `interval.toPostgres()` -> `string` Returns an interval string. This allows the interval object to be passed into prepared statements. #### `interval.toISOString()` -> `string` Returns an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601#Durations) compliant string, for example `P0Y0M0DT0H9M0S`. Also available as `interval.toISO()` for backwards compatibility. #### `interval.toISOStringShort()` -> `string` Returns an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601#Durations) compliant string shortened to minimum length, for example `PT9M`. ## License MIT © [Ben Drucker](http://bendrucker.me) package/index.d.ts000644 0000004613 3560116604 011165 0ustar00000000 000000 declare namespace PostgresInterval { export interface IPostgresInterval { years: number; months: number; days: number; hours: number; minutes: number; seconds: number; milliseconds: number; /** * Returns an interval string. This allows the interval object to be passed into prepared statements. * * ```js * var parse = require('postgres-interval') * var interval = parse('01:02:03') * // => { hours: 1, minutes: 2, seconds: 3 } * interval.toPostgres() * // 1 hour 2 minutes 3 seconds * ``` */ toPostgres(): string; /** * Returns an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601#Durations) compliant string, for example P0Y0M0DT0H9M0S. * * Also available as {@link toISOString toISOString}. * * ```js * var parse = require('postgres-interval') * var interval = parse('01:02:03') * // => { hours: 1, minutes: 2, seconds: 3 } * interval.toISO() * // P0Y0M0DT1H2M3S * ``` */ toISO(): string; /** * Returns an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601#Durations) compliant string, for example P0Y0M0DT0H9M0S. * * Also available as {@link toISO toISO} for backwards compatibility. * * ```js * var parse = require('postgres-interval') * var interval = parse('01:02:03') * // => { hours: 1, minutes: 2, seconds: 3 } * interval.toISOString() * // P0Y0M0DT1H2M3S * ``` */ toISOString(): string; /** * Returns an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601#Durations) compliant string shortened to minimum length, for example `PT9M`. * * ```js * var parse = require('postgres-interval') * var interval = parse('01:02:03') * // => { hours: 1, minutes: 2, seconds: 3 } * interval.toISOStringShort() * // PT1H2M3S * ``` */ toISOStringShort(): string; } } /** * Parse Postgres interval columns. * * ```js * var parse = require('postgres-interval') * var interval = parse('01:02:03') * // => { hours: 1, minutes: 2, seconds: 3 } * interval.toPostgres() * // 1 hour 2 minutes 3 seconds * interval.toISOString() * // P0Y0M0DT1H2M3S * interval.toISOStringShort() * // PT1H2M3S * ``` * * @param raw A Postgres interval string. */ declare function PostgresInterval(raw: string): PostgresInterval.IPostgresInterval; export = PostgresInterval;