Postgres data query using epoch timestamp as input from client? - node.js

I am in need to select all rows from table a that have updated_at newer than a given (epoch) timestamp, '1549312452' for example.
I am using node.js. When the client sends up that timestamp, I have the server convert it to date:
var date = new Date(timestmapInt * 1000);
I then run the following query:
`select * from a where a.updated_at > ${date}`
When I hit the endpoint I get this error:
"syntax error at or near \"Feb\""
So, in general, how can I query records newer than a certain date if my incoming parameter is 1549312452 in Postgresql?

You can pass the raw epoch to to_timestamp:
select * from a where a.updated_at > to_timestamp(1549312452)

Related

psycopg2 SELECT query with inbuilt functions

I have the following SQL statement where i am reading the database to get the records for 1 day. Here is what i tried in pgAdmin console -
SELECT * FROM public.orders WHERE createdat >= now()::date AND type='t_order'
I want to convert this to the syntax of psycopg2but somehow it throws me errors -
Database connection failed due to invalid input syntax for type timestamp: "now()::date"
Here is what i am doing -
query = f"SELECT * FROM {table} WHERE (createdat>=%s AND type=%s)"
cur.execute(query, ("now()::date", "t_order"))
records = cur.fetchall()
Any help is deeply appreciated.
DO NOT use f strings. Use proper Parameter Passing
now()::date is better expressed as current_date. See Current Date/Time.
You want:
query = "SELECT * FROM public.orders WHERE (createdat>=current_date AND type=%s)"
cur.execute(query, ["t_order"])
If you want dynamic identifiers, table/column names then:
from psycopg2 import sql
query = sql.SQL("SELECT * FROM {} WHERE (createdat>=current_date AND type=%s)").format(sql.Identifier(table))
cur.execute(query, ["t_order"])
For more information see sql.

convert and Insert date format in nodejs into Oracle timestamp

let date = moment(new Date()).format("YYYY-MM-DD hh:mm:ss.000000000 A");
// when i tried to insert date in table it is null
// TImestamp format in OracleDB is 14-03-22 3:53:08.901008000 PM
INSERT INTO STUDENT VALUES(join_date) ( '14-03-22 3:53:08.901008000 PM')
How can get date format like YYYY-MM-DD HH:MM:SS.FF3 AM/PM because in oracle it supports this kind of timestamp
In Oracle, a TIMESTAMP is a binary data type that consists of 7 - 13 bytes (century, year-of-century, month, day, hour, minute, second and between zero and six bytes for fractional seconds). It ALWAYS contains those components and it is NEVER stored in a particular format.
The client application you are using (i.e. SQL/Plus, SQL Developer, NodeJS, Java, etc.) may chose to DISPLAY the binary value with a default format but this is a function of the client application and NOT a function of the database. (Some client applications may use the NLS_TIMESTAMP_FORMAT session parameter from the database as their default format model but the implicit conversion from binary-to-string for display purposes is still something that the client application does, not the database, and not all clients use the database session variables for their defaults.)
You should either:
Use a timestamp literal:
INSERT INTO STUDENT (join_date) VALUES (TIMESTAMP '2022-03-14 15:53:08.901008000');
Explicitly convert your formatted string to a timestamp binary data type using the TO_TIMESTAMP function with a format model:
INSERT INTO STUDENT (join_date)
VALUES (
TO_TIMESTAMP('14-03-22 3:53:08.901008000 PM', 'DD-MM-RR HH12:MI:SS.FF9 AM')
)

Convert psql query into typeorm using query builder

I need to get data on daily/weekly/monthly basis. So i used date_trunc() and generate_series() to get this type of record. I made psql query but i need to convert it into typeorm code as i'm new to typeorm stack. Below is the query
SELECT sequential_dates.date, events.count
FROM (select date_trunc('MONTH', months) AS date
from generate_series('2021-05-03' :: DATE, '2021-05-31' :: DATE, '1 MONTH') as months ) sequential_dates
LEFT JOIN(
select date_trunc('MONTH', events."createdAt") AS date, count(events.id) as count
from events where events."type" = 'LOGIN'
group by date
) events
on sequential_dates.date = events.date
If it's not possible to express this using the TypeOrm API, then you can make raw queries:
const rawData = await repository.query(`SELECT * FROM USERS`);
You'll have to handle the rawData manually (similar to https://typeorm.io/#/select-query-builder/getting-raw-results).
Docs: https://typeorm.io/#/repository-api. Search for "query - Executes a raw SQL query".

Date type displaying with timezone on node-postgres module

I have stored input data in date format in postgres database, but when I am showing the date in browser it's showing date with timezone and converting it from utc. For example I have stored the date in 2020-07-16 format. But when i am showing the date it becomes 2020-07-15T18:00:00.000Z. I have tried using select mydate::DATE from table to get only date but its still showing date with timezone. I am using node-postgres module in my node app. I suspect it's some configuration on node-postgres module? From their doc:
node-postgres converts DATE and TIMESTAMP columns into the local time
of the node process set at process.env.TZ
Is their any way i can configure it to only parse date? If i query like this SELECT TO_CHAR(mydate :: DATE, 'yyyy-mm-dd') from table i get 2020-07-16 but thats lot of work just to get date
You can make your own date and time type parser:
const pg = require('pg');
pg.types.setTypeParser(1114, function(stringValue) {
return stringValue; //1114 for time without timezone type
});
pg.types.setTypeParser(1082, function(stringValue) {
return stringValue; //1082 for date type
});
The type id can be found in the file: node_modules/pg-types/lib/textParsers.js
It is spelled out here:
https://node-postgres.com/features/types
date / timestamp / timestamptz
console.log(result.rows)
// {
// date_col: 2017-05-29T05:00:00.000Z,
// timestamp_col: 2017-05-29T23:18:13.263Z,
// timestamptz_col: 2017-05-29T23:18:13.263Z
// }
bmc=# select * from dates;
date_col | timestamp_col | timestamptz_col
------------+-------------------------+----------------------------
2017-05-29 | 2017-05-29 18:18:13.263 | 2017-05-29 18:18:13.263-05
(1 row)

Getting DateTime difference in OrientDB

I have the following Carts table schema of orientDB. All I wanted to do is to select those records where
(CurrentTime - timeStamp) >= expiration
I had also tried to achive my goal thorugh converting to unix timestamp and tried following queries
SELECT * FROM Carts WHERE eval("('+new Date().getTime()+' timeStamp.asLong())/1000") >= expiration
And also by following technique but when :parameter is passed in eval funtion it convert it into '?' and don't return required data.
db.query(
'SELECT eval("'+new Date().getTime()+' - timeStamp.asLong()") as DIFF, :nowTimeStamp as NOW, timeStamp.asLong() as THEN FROM Carts ',
{
params: {
nowTimeStamp: new Date().getTime()
}
}).then(callback);
Try this query:
SELECT * FROM Carts WHERE eval("SYSDATE().asLong() / 1000 - timeStamp.asLong() / 1000") >= expiration
Hope it helps.

Resources