brianc / node-postgres

PostgreSQL client for node.js.
https://node-postgres.com
MIT License
12.19k stars 1.22k forks source link

SELECT EXTRACT EPOCH #2841

Open IPoyda opened 1 year ago

IPoyda commented 1 year ago

Hi I think I've faced an issue with below code block; Per documentation for postgres EPOCH method should return a number

https://www.postgresql.org/docs/8.1/functions-datetime.html#:~:text=40%27)%3B%0AResult%3A%2047-,epoch,-For%20date%20and

But what I receive in reality is[ { extract: '982384720.000000' } ]. So the value here is a type of string while the expected type is a number.

Thanks in advance for your response.

const { Pool } = require("pg");

const connectDb = async () => {
    try {
        const pool = new Pool({
            host: "***",
            database: "***",
            user: "***",
            password: "***",
        });

        await pool.connect()

        const res = await pool.query('SELECT EXTRACT(EPOCH FROM TIMESTAMP WITH TIME ZONE \'2001-02-16 20:38:40-08\');')
        console.log(res.rows)
        process.exit(0);
    } catch (error) {
        console.log(error)
    }
}

connectDb()

pg: 8.8.0 Postgres: 14.5 OS: MacOs Node + NPM: node v16.13.1 (npm v8.1.2)

cakerug commented 1 year ago

+1 this is also happening to me

boromisp commented 1 year ago

The current documentation for postgres says: "The extract function returns values of type numeric.". Numeric vaules cannot always be accurately represented by javascript numbers, so this library leaves them as strings. If you are sure, the value you are extracting should fit into a javascript number, cast it into a double / int / whatever in your query.

Fyi the return type of extract seems to have changed in postgres 14.

cakerug commented 1 year ago

Ah got it! Thanks!