I'm having hard times to find out how to order by count field in Prisma.
The query looks like this:
const where = // ...
const limit = // ...
const skip = // ...
const data = await this.prisma.translation.findMany({
where,
take: limit,
skip: offset,
orderBy: {
count: 'asc'
// ^ here is the issue, because count seems to be reserved for aggregations
}
});
Prisma model:
model Translation {
id String
count Int #default(0)
}
I found the docs here https://www.prisma.io/docs/reference/api-reference/prisma-client-reference#orderby but it does not say anything how to say to prisma that the count does not mean aggregation but a column name.
The error I'm getting:
Invalid `prisma.translation.findMany()` invocation:\n\n\n Failed to validate the query: `Assertion error: Attempted conversion of non-map ParsedInputValue (Single(String(\"asc\"))) into map failed..` at ``
PS. I found this issue on GitHub that is still open https://github.com/prisma/prisma/issues/7806, gonna ask also there for some workaround or something...
Thanks for any help :-)
This has been fixed in Prisma Version 3.0.1.
If you need to solve this in Prisma v2, you could change the field name in prisma and use the #map annotation to point to the count column in your database table.
Example Prisma schema
model Translation {
id Int #id #default(autoincrement())
transactionCount Int #default(0) #map(name: "count")
}
Inside your prisma code you would use transactionCount instead of count. But there won't be any change to the underlying database, which will still have the column named count.
For more info, take a look at the Prisma docs for using custom field names.
Related
I'm planning to create a seeder for my projects table. I'm using createMany to insert multiple data in just a query (see code below). But the problem is, it does not recognize createMany and throws and error after running a jest test.
Another thing that is confusing me, there was no typescript error in my code. And I can create also single data using create function.
I already been to prisma documentation, but I can't determine what was wrong in my code. Could someone help me figure it out. (comments would also help).
error TS2339: Property 'createMany' does not exist on type 'ProviderDelegate<RejectOnNotFound | RejectPerOperation | undefined>'.
schema.prisma
generator client {
provider = "prisma-client-js"
}
datasource db {
provider = "sqlite"
url = "file:./dev.db"
}
model Provider {
id Int #id #default(autoincrement())
user_id Int
name String
space_key String
api_key String
projects Project[]
created_at DateTime #default(now())
updated_at DateTime #updatedAt
##unique([user_id, api_key])
}
my usage
import { PrismaClient } from '#prisma/client'
const prisma = new PrismaClient()
...
await prisma.provider.createMany({
data: [
{
user_id: 1,
name: 'Nicole Sal',
space_key: 'nic_spa',
api_key: 'nic_api',
created_at: new Date(),
updated_at: new Date()
},
// ... more data here (same at above)
]
})
Ahh I see. just found this. createMany is not supported for SQLite.
createMany is not supported on SQLite unfortunately: #10710
Documented here: https://www.prisma.io/docs/reference/api-reference/prisma-client-reference#remarks-10
https://github.com/prisma/prisma/issues/11507#issuecomment-1025587202
there is the following structure
#Id
private String beaconMac;
private SortedMap<LocalDate, Map<Integer, HistoryData>> history;
How i can read internal value from 'history' map by key? how to make a right query? or meybe in spring data there is a blank like
NestedObject repo.findNestedObjectByDate(LocalDate date);
Very grateful!
If I understand correctly, you want something like:
db.collection.find({
beaconMac: "C145109D4D5C"
},
{
"history.2020-20-02": 1,
beaconMac: 1
})
The first part is the match, in which you choose what documents you want. The second is the projection, in which you format the fields you want to see.
As You can see on this playground
I would like to find items in a Prisma db where the values for two columns are the same. The use case is to compare the 'created_at' and 'updated_at' fields to find items that have never been updated after their initial creation. In raw SQL I would do something like:
select updated_at,
cast(sign(sum(case when updated_at = created_at then
1
else
0
end)) as int) as never_modified
from tab
group by updated_at
Is it possible to achieve this in Prisma?
You would need to use Raw Queries to compare time values from the same table.
Here's an example of how you could achieve this, assuming a PostgreSQL database for the following query.
import { PrismaClient } from '#prisma/client'
const prisma = new PrismaClient()
async function initiateDatesComparisonRawQuery() {
const response =
await prisma.$queryRaw`SELECT * FROM "public"."Project" WHERE "created_at" = "updated_at";`;
console.log(response);
}
await initiateDatesComparisonRawQuery();
you can use the preview feature fieldReference of prisma.
schema.prisma
generator client {
provider = "prisma-client-js"
previewFeatures = ["fieldReference"]
}
your code
prisma.project.findMany({
where: { created_at: prisma.project.fields.updated_at }
})
I'm attempting to use Prisma with Cockroachdb locally. I understand that official support for CockroachDB is in the works.
I have a parallel local PostgreSQL database where everything is working correctly and I am able to generate Prisma migrations to run manually against Cockroachdb. All of this works and I end up with two apparently identical schemas.
However, any create operation in Prisma using the connect feature is failing with the following error:
Invalid `prisma.mylinkedtable.create()` invocation:
Foreign key constraint failed on the field: `(not available)`
Here are key parts of my schema.prisma:
datasource db {
provider = "postgresql"
url = "postgresql://user:pass#localhost:26257/mydb"
}
generator client {
provider = "prisma-client-js"
previewFeatures = ["cockroachdb"]
}
model MyLinkedEntity {
id Int #id #default(autoincrement())
myEntity MyEntity #relation(fields: [myEntityId], references: [id])
myEntityId Int
// ...
}
model MyEntity {
id Int #id #default(autoincrement())
// ...
}
The code that is triggering the foreign key constraint:
const entity = await prisma.myEntity.findFirst({})
await prisma.myLinkedEntity.create({
data: {
myEntityId: entity.id,
// ...
}
}
If I go about it slightly diffently and try to link using the connect feature:
await prisma.myLinkedEntity.create({
data: {
myEntity: {
connect: {
id: entity.id
}
},
// ...
}
}
I get a different error:
Invalid `prisma.myLinkedEntity.create()` invocation:
An operation failed because it depends on one or more records that were required but not found. No 'MyEntity' record(s) (needed to inline the relation on 'MyLinkedEntity' record(s)) was found for a nested connect on one-to-many relation 'MyEntityToMyLinkedEntity'.
What gives?
It looks like the related rows are not being created first.
Could you try using connectOrCreate instead? https://www.prisma.io/docs/concepts/components/prisma-client/relation-queries#connect-or-create-a-record
It could also be something wrong with the Prisma model. I'm not not sure if order matters, but I notice you have the relation defined before the ID it's referencing.
One final, unrelated, point: you should not use auto incrementing ints as keys in CockroachDB. See https://www.cockroachlabs.com/docs/v21.2/schema-design-table#primary-key-best-practices
I have not clearly issue during query using two criterials like Id and Other. I use a Repository storing some data like id,iso,value. I have created an index("_id","Iso") to performs queries but queries are only returning my cursor if i use only one criterial like _id, but is returning nothing if a use two (_id, Iso) (commented code).
Are the index affecting the response or the query method are failing?
use :v1.6.5 and C# official.
Sample.
//Getting Data
public List<BsonObject> Get_object(string ID, string Iso)
{
using (var helper = BsonHelper.Create())
{
//helper.Db.Repository.EnsureIndex("_Id","Iso");
var query = Query.EQ("_Id", ID);
//if (!String.IsNullOrEmpty(Iso))
// query = Query.And(query, Query.EQ("Iso", Iso));
var cursor = helper.Db.Repository.FindAs<BsonObject>(query);
return cursor.ToList();
}
}
Data:
{
"_id": "2345019",
"Iso": "UK",
"Data": "Some data"
}
After that I have Updated my data using Update.Set() methods. I can see the changed data using MongoView. The new data are correct but the query is always returning the sames olds values. To see these values i use a page that can eventually cached, but if add a timestamp at end are not changing anything, page is always returning the same olds data. Your comments are welcome, thanks.
I do not recall offhand how the C# driver creates indexes, but the shell command for creating an index is like this:
db.things.ensureIndex({j:1});
Notice the '1' which is like saying 'true'.
In your code, you have:
helper.Db.Repository.EnsureIndex("_Id","Iso");
Perhaps it should be:
helper.Db.Repository.EnsureIndex("_Id", 1);
helper.Db.Repository.EnsureIndex("Iso", 1);
It could also be related to the fact that you are creating indexes on "_Id" and the actual id field is called "_id" ... MongoDB is case sensitive.
Have a quick look through the index documentation: http://www.mongodb.org/display/DOCS/Indexes