Query items of a collection before a certain date on Fauna Db? - faunadb

I looked on google and tried different thing but I cannot figure out how to query all the item of a collection that have the key dueDate before the a certain Date.
On Mysql I would do something like :
select * from table_name where dueDate < "2001-01-01 00:00:00"
That query on mysql would return the items with the Date Inferior to 2001-01-01
I tried to do use that query on Fauna :
q.Map(
q.Paginate(
q.Match(q.Index(indexesQuery1)),
{ before: Date('2021-01-15T17:34:00+08:00')
} ),
q.Lambda("X", q.Get(q.Var("X"))) ) )
indexQuery1 is : getNewWordDemoIso(dueDate: Date!)
But It returns an empty Array,
Also I saved all my Date all Fauna the date format called : iso 8601
Also Im using javascript
Any ideas !?
thanks !!

When you perform an "Create", you need parse your ISOString Date for an FaunaDB Date format.
You migth need something like this:
const newTransaction = await fauna.query<TransactionObject>(
q.Create(q.Collection("transactions"), {
data: {
...transaction,
firstDueDate: q.Date(transaction.firstDueDate),
lastDueDate: q.Date(transaction.lastDueDate),
createdAt: q.ToDate(q.Now())
}
})
);
This will work for you as you said you are using JS/TS.
ps: (import {query as q} from 'faunadb')

Related

SQL Server get a JSON of all distinct columns grouped by a different column

I have a table that looks like this:
What I want to do is convert it to a JSON that has all distinct years as keys, and an array of Make as value for each key. So based on the image, it would be something like this:
{ "1906": ["Reo", "Studebaker"], "1907": ["Auburn", "Cadillac", "Duryea", "Ford"], ... }
Could someone please help me on how to write a query to achieve this? I've never worked with converting SQL -> JSON before, and all I know is to use FOR JSON to convert a query to JSON.
I managed to solve this for whoever needs something similar. However, I think this way is inefficient and I would love for someone to tell me a better method.
I first ran this SQL query:
WITH CTE_Make AS
(
SELECT [Year], [Make]
FROM VehicleInformation
GROUP BY [Year], [Make]
)
SELECT
( SELECT
[Year] AS Year,
STRING_AGG([Make],',') AS MakeList
FOR JSON PATH,
WITHOUT_ARRAY_WRAPPER)
FROM CTE_Make
GROUP BY [Year]
This gave me the JSON in a different format from what I wanted. I stored this in a file "VehicleInformationInit.json", and loaded it in JS as variable vehicleInfoInitJsonFile and ran the following code in JavaScript:
var dict = {};
$.getJSON(vehicleInfoInitJsonFile, function
(result) {
result.forEach(x => {
var makeList = x.MakeList.split(',');
dict[x.Year] = makeList;
})
var newJSON = JSON.stringify(dict);
});
I simply copied the contents of newJSON by attaching a debugger into my required file. However, you can easily use fs and store it in a file if you want to.

Prisma queryRaw returning date as string

Issue: When I use prisma.$queryRaw, it returns my date as a string, even though I specify the query's return type. If I use prisma.find then it returns it correctly. But, I have to use queryRaw because of the complexity of the query.
schema.prisma has the date defined like such:
effectiveDate DateTime? #map("effective_date") #db.Date
So, the model object has the field defined like effectiveDate: Date | null
The query looks something like this:
const catalogCourses: CatalogCourse[] = await prisma.$queryRaw<CatalogCourse[]>`
SELECT
id,
campus,
effective_date as "effectiveDate",
...rest of the query ommitted here because it's not important
If I then do something like
console.log(`typeof date: ${typeof catalogCourses[0].effectiveDate}, value ${catalogCourses[0].effectiveDate}`)
The result shows typeof date: string, value 2000-12-31. Why isn't it a date? I need to be able to work with it as a Date, but if I do effectiveDate.getTime() for example, it errors during runtime, saying 'getTime is not a function', which it is doc. If I try and do new Date(effectiveDate), that doesn't work either because typescript sees the field as a Date object already. EDIT: I was incorrect about why the previous statement wasn't working; doing new Date(effectiveDate) does work.
I do see in the prisma docs that it says:
Type caveats when using raw SQL When you type the results of
$queryRaw, the raw data does not always match the suggested TypeScript
type.
Is there a way for queryRaw to return my date as a Date object?

Search for exact string value in JSON

I have a column stored in JSON that looks like
column name: s2s_payload
Values:
{
"checkoutdate":"2019-10-31",
"checkindate":"2019-10-30",
"numtravelers":"2",
"domain":"www.travel.com.mx",
"destination": {
"country":"MX",
"city":"Manzanillo"
},
"eventtype":"search",
"vertical":"hotels"
}
I want to query exact values in the array rather than returning all values for a certain data type. I was using JSON_EXTRACT to get distinct counts.
SELECT
COUNT(JSON_EXTRACT(s2s_payload, '$.destination.code')) AS total,
JSON_EXTRACT(s2s_payload, '$.destination.code') AS destination
FROM
"db"."events_data_json5_temp"
WHERE
id = '111000'
AND s2s_payload IS NOT NULL
AND yr = '2019'
AND mon = '10'
AND dt >= '26'
AND JSON_EXTRACT(s2s_payload, '$.destination.code')
GROUP BY
JSON_EXTRACT(s2s_payload, '$.destination.code')
If I want to filter where ""eventtype"":""search"" how can I do this?
I tried using CAST(s2s_payload AS CHAR) = '{"eventtype"":""search"}' but that didn't work.
You need to use json_extract + a CAST to get actual value to compare against:
CAST(json_extract(s2s_payload, '$.eventtype') AS varchar) = 'search'
or, same with json_extract_scalar (and thus with no need for a CAST):
json_extract_scalar(s2s_payload, '$.eventtype')

Sequelize Average of Date Difference

I have the following (abstract) sequelize model:
{
startTime: Date,
endTime: Date,
}
Now I want to get the average duration of all existing entities. In SQL I'd model this like SELECT AVG("end_time" - "start_time") FROM "MyTable";. But I don't know how I can do this with sequelize.
I've made some attempts on using sequelize.fn() but did not come to a conclusion.
So my goal is to have something like:
MyModel.findAll({
attributes: ['averageTime' <<< now what?]
});
Oh and I'm using PostgreSQL 9.6.
Best,
Philipp
You can't use findAll or findOne as they return instance(s) of the model and you need to get some scalar value.
Raw query can be used to do what you need like this:
sequelize.query(
'SELECT AVG("end_time" - "start_time") FROM "MyTable"',
{ type: sequelize.QueryTypes.SELECT}
).then(function(result) {
// process result here
})

Truncate DateTime in NHibernate QueryOver SelectGroup

I have a fairly run-of-the-mill QueryOver query containing the following,
.SelectList(list => list
.SelectGroup(() => txn.GroupField)
.SelectGroup(() => txn.Date))
.List<object[]>()
This query works as expected however I now have a requirement to group by the truncated Date as some of the Date's for these objects may contain a time component. This seems like it should be a trivial change but I can't find a way that is supported by NHibernate.
The obvious solution would be the change below but is not supported.
.SelectGroup(() => txn.Date.Date))
Any ideas?
Thanks
Your QueryOver could look like this:
Status alias = null;
var query = QueryOver.Of(() => alias)
.Select(Projections.GroupProperty(
Projections.SqlFunction("date", NHibernateUtil.Date, Projections.Property(() => alias.Date))));
Output (pseudo sql):
SELECT
...
FROM [Status] this_
GROUP BY dateadd(dd, 0, datediff(dd, 0, this_.Date))
Hope this helps, cheers!
You might want to add a helper property to your map, using the Formula command, to be able to use the date (instead of datetime) in queries.
here's an example from my code; it uses a decimal value, but this works fine with any subquery:
model class has this property, to be mapped to a formula:
public virtual decimal Profit
{
get { return this.SellPrice - this.Cost; }
set { return; }
}
fluentNHibernate map:
//SellPrice and Cost are columns in the object's table
Map(v => v.Profit).Formula("(SellPrice - Cost)"); // this field is calculated, not read
be sure to put the formula between () brackets though.
If you'd make your formula a select query that trunks the datetime into a date, you could then group by that property in your query.