Getting DateTime difference in OrientDB - node.js

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.

Related

Prisma how to add hours while comparing columns in the same table

I am using NestJS and Prisma[4.4.0].
My table:
id: int
created_at: Timestamp
first_active: Timestamp
Query that I want to implement
select count(*) from {table} where id = {id} and first_active <= {created_at} + 48hours
I want to get a count of users which were active within 48 hours of creation.
With https://www.prisma.io/docs/reference/api-reference/prisma-client-reference#compare-columns-in-the-same-table now I can access the column name.
Example
where: {
// find all users where 'name' is in a list of tags
id: ${id},
first_active: {
this.prisma.table.fields.created_at // Not sure how to + 48 hours
}
},
any suggestion on how I can add time (72 hours) to the created_at
You will need to perform two queries to accomplish this, for now. First, retrieve the created_at, then add the necessary hours.
You could create a feature request if you would like to see this functionality added to Prisma.

How to pass param inside single quotes to a postgres query?

In my node app, i need to run below query and and i'm passing parameters dynamically. But it's not fetching the parameters since they are referenced inside single quotes. Suggest a solution for this.
const text = `UPDATE glacier_restore_progress
SET
status='completed',
restore_end=CURRENT_TIMESTAMP,
restore_expire=DATE_TRUNC('minutes', current_timestamp + interval '$1 minutes')
WHERE file_path = '$2' AND date_trunc('minutes', current_timestamp - interval '$1 minutes') <= restore_start`;
const values = [restoreDuration, fileKey];
await pool.query(text, values);
and the error i get is,
"bind message supplies 2 parameters, but prepared statement \"\" requires 0"
You are absolutely right; parameters cannot be inside quotes. There are a few ways we can solve this:
Taking the similarly broken example SELECT * FROM employees WHERE CURRENT_TIMESTAMP - start_date < INTERVAL '$1 years';
Have the client submit the "full" value: SELECT * FROM employees WHERE CURRENT_TIMESTAMP - start_date < INTERVAL $1;
Construct string in the query: SELECT * FROM employees WHERE CURRENT_TIMESTAMP - start_date < INTERVAL ($1 || ' years');
(interval specific) Use the fact the unit can be specified as its own keyword: SELECT * FROM employees WHERE CURRENT_TIMESTAMP - start_date < INTERVAL $1 MINUTE
My preference in this case is 1, however the most faithful to your question is 3. Be careful to use MINUTE and not MINUTES. Option 2, using the concatentation operator, is a good hack to have in your toolbelt. All answers tested in Postgres 13.
In addition to this, your parameter is likely going to bound as a number, which will get you an error. You may need to cast it to text, like so $1::TEXT
Your full query would be:
UPDATE glacier_restore_progress
SET
status = 'completed',
restore_end = CURRENT_TIMESTAMP,
restore_expire = DATE_TRUNC('minutes', CURRENT_TIMESTAMP + INTERVAL $1::TEXT MINUTE)
WHERE file_path = $2
AND DATE_TRUNC('minutes', current_timestamp - INTERVAL $1 MINUTE) <= restore_start
use this,
const text = `UPDATE glacier_restore_progress
SET
status='completed',
restore_end=CURRENT_TIMESTAMP,
restore_expire=DATE_TRUNC('minutes', current_timestamp + interval '1 minutes' * $1)
WHERE file_path = $2 AND date_trunc('minutes', current_timestamp - interval '1 minutes' * $1) <= restore_start`;
const values = [restoreDuration, fileKey];
await pool.query(text, values);
this convention is mentioned here refrence

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".

Cosmos Db Sql Query produces drastically different results when using order by

I have a Cosmos Db instance with > 1 Million JSON Documents stored in it.
I am trying to pull data of a certain time frame as to when the document was created based on the _ts variable which is auto-generated when the document is inserted. It represents the UNIX timestamp of that moment.
I am unable to understand, why both these queries produce drastically different results:
Query 1:
Select *
from c
where c._ts > TimeStamp1
AND c._ts < TimeStamp2
Produces 0 results
Query 2
Select *
from c
where c._ts > TimeStamp1
AND c._ts < TimeStamp2
order by c._ts desc
Produces the correct number of results.
What I have tried?
I suspected that might be because of the default CosmosDb index on the data. So, I rewrote the index policy to index only that variable. Still the same problem.
Since my end purpose is to group by on the returned data from the query, then I tried to use group by with order by alone or in a subquery. Surprisingly, according to the docs, CosmosDb yet doesn't support using group by with order by.
What I need help on?
Why am I observing such a behavior?
Is there a way to index the Db in such a way that the rows are returned.
Beyond this, is there a way to still use group by and order by together (Please don't link the question to another one because of this point, I have gone through them and their answers are not valid in my case).
#Andy and #Tiny-wa, Thanks for replying.
I was able to understand the unintended behavior and it was showing up because of the GetCurrentTimestamp() used to calculate the TimeStamps. The documentation states that
This system function will not utilize the index. If you need to
compare values to the current time, obtain the current time before
query execution and use that constant string value in the WHERE
clause.
Although, I don't fully understand what this means but I was to solve this by creating a Stored Procedure where the Time Stamp is fetched before the SQLAPI query is formed and executed and I was able to get the rows as expected.
Stored Procedure Pseudocode for that is like:
function FetchData(){
..
..
..
var Current_TimeStamp = Date.now();
var CDbQuery =
`Select *
FROM c
where (c._ts * 10000000) > DateTimeToTicks(DateTimeAdd("day", -1, TicksToDateTime(` + Current_TimeStamp + ` * 10000)))
AND (c._ts * 10000000) < (` + Current_TimeStamp + ` * 10000)`
var isAccepted = collection.queryDocuments(
collection.getSelfLink(),
XQuery,
function (err, feed, options) {
..
..
..
});
}

Postgres data query using epoch timestamp as input from client?

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)

Resources