How to fix "createMany does not exists..." in prisma? - prisma

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

Related

Prisma, how to preserve foreign data?

It's been a few months since I started prisma and I'm still confused.
In a normal database, foreign key data also exists in table data. However, according to the prisma document, in prisma, the data does not exist at the database level.
So where is it stored? It seems that the things I do "connect:id:1" are stored in the Prisma client. If I delete the prisma dependency and install it again with npm install, will all these relational data be deleted too?? How can I make it as safe as possible????
And it seems too dangerous when I migrate later. what am I misunderstanding?
ADDED
const user = await prisma.user.create({
data: {
email: 'vlad#prisma.io',
posts: {
connect: [{ id: 8 }, { id: 9 }, { id: 10 }],
},
},
include: {
posts: true, // Include all posts in the returned object
},
})
in this case, id 8, id 9, id 10, Where are all these stored? Is there any way to check other than prisma studio or select query? I don't know where it is physically stored. It's not even in the planet scale database.
// In the workbench, the foriegn key is actually saved and can be exported. I don't know how it's not at the database level, but where it is referenced and stored.
Considering this Schema:
generator client {
provider = "prisma-client-js"
}
datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
}
model User {
id Int #id #default(autoincrement())
name String
email String #unique
posts Post[]
}
model Post {
id Int #id #default(autoincrement())
title String
published Boolean #default(true)
author User #relation(fields: [authorId], references: [id])
authorId Int
}
There is a one-to-many relationship between User and Posts.
according to the prisma document, in prisma, the data does not exist
at the database level.
Only the relation fields do not exist at the database level, so in this case posts in User model and author in Post model would not exist at database level. But the foreign key exists at the database level, so in this case authorId is actually stored in the database.
Based on the create query you have shared:
in this case, id 8, id 9, id 10, Where are all these stored?
The connect statement in create query is essentially linking the records.
So to elaborate Posts with id 8,9,10 would have the authorId value of the new user record which is created.
So the data is stored in database, you can always check which posts are created by a specific author. You just need to query all the posts which has authorId set to the id which you are querying for.

panic: reflect: call of reflect.Value.Interface on zero Value on GORM .Create()

I'm new to go and Backend and I'm Trying to make many-to-many relation between tables. I used this repo to make model:https://github.com/harranali/gorm-relationships-examples/tree/main/many-to-many
I Used GORM with postgresql.
My model:
type Book struct {
gorm.Model
Title string `json:"title"`
Author string `json:"author"`
Description string `json:"description"`
Category string `json:"Category"`
Publisher string `json:"publisher"`
AuthorsCard []*AuthorsCard `gorm:"many-to-many:book_authorscard;" json:"authorscard"`
}
type AuthorsCard struct {
gorm.Model
Name string `json:"name"`
Age int `json:"age"`
YearOfBirth int `json:"year"`
Biography string `json:"biography"`
}
After connecting to database and AutoMigrating:
func init() {
config.Connect()
db = config.GetDB()
db.AutoMigrate(&models.Book{}, &models.AuthorsCard{})
}
I've created Function to see how that relation works:
func TestCreate() {
var AuthorsCard = []models.AuthorsCard{
{
Age: 23,
Name: "test",
YearOfBirth: 1999,
Biography: "23fdgsdddTEST",
},
}
db.Create(&AuthorsCard)
var testbook = models.Book{
Title: "Test",
Author: "tst",
Description: "something",
}
db.Create(&testbook)
db.Model(&testbook).Association("AuthorsCard").Append(&AuthorsCard)
}
But got This Error:
panic: reflect: call of reflect.Value.Interface on zero Value [recovered]
panic: reflect: call of reflect.Value.Interface on zero Value
How can I deal with this "Null" problem and make proper relation?
UPD: The First part of a problem was connected to a version of GORM, After I changed old version(github.com/jinzhu/gorm v1.9.16) to new version (gorm.io/gorm v1.23.6) the problem with reflect Error gone.
but now, when I want to create new book, I get this Error:
/go/pkg/mod/gorm.io/driver/postgres#v1.3.7/migrator.go:119 ERROR: there is no unique constraint matching given keys for referenced table "authors_cards" (SQLSTATE 42830)
[28.440ms] [rows:0] CREATE TABLE "book_authorscard" ("book_id" bigint,"authors_card_id" bigint,PRIMARY KEY ("book_id","authors_card_id"),CONSTRAINT "fk_book_authorscard_authors_card" FOREIGN KEY ("authors_card_id") REFERENCES "authors_cards"("id"),CONSTRAINT "fk_book_authorscard_book" FOREIGN KEY ("book_id") REFERENCES "books"("id"))
[GIN-debug] [WARNING] Creating an Engine instance with the Logger and Recovery middleware already attached.
UPD 2:
I decided to make a Migrator().DropTable(). That's kinda worked, and all Errors have gone. But still I get "authorscard": null as a response.
By reading the release note of Gorm v2 (https://gorm.io/docs/v2_release_note.html), I think that you are trying to use v2 feature with an old version (<v2). Try to use Gorm latest version.

Invalid `prisma.mytable.create()` invocation: Foreign key constraint failed on the field: `(not available)` when using cockroachdb

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

How to order by field called "count" in Prisma?

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.

Unable to solve Prisma 1 - 1 and 1 - n relation error

I have 3 Prisma2 tables where User can have lots of Sheet and only one Doc
model User {
id Int #default(autoincrement()) #id
firstName String
lastName String
email String #unique
sheets Sheet[]
docs Doc?
}
model Sheet {
id Int #default(autoincrement()) #id
user_sheets Int
User User #relation(fields: [user_sheets], references: [id])
sheetName String
}
model Doc {
id Int #default(autoincrement()) #id
user_doc Int?
User User? #relation(fields: [user_doc], references: [id])
docName String
}
I am using Prisma2 Client like this to get all sheets and docs of the user with specific email id:
import { PrismaClient } from '#prisma/client'
const prisma = new PrismaClient();
const users = await prisma.user.findMany({
where: {
email: email
},
include: {
sheets: true,
docs: true,
}
});
I have already done migrate-save, migrate-up and generate
The error I am getting is this:
PrismaClientValidationError:
Invalid `prisma.user.findMany()` invocation in
webpack-internal:///./pages/api/resume.js:12:47
{
include: {
sheets: true
~~~~~~
docs: true
~~~~~~
}
}
Unknown field `sheets` for include statement on model User.
This model has no relations, so you can't use include with it.
Please help me understand and resolve it as I used the prisma2 doc as well as followed this tutorial: https://www.youtube.com/watch?v=jeHJbYLCgzI
but with no luck the error continues to haunt me.
Issue Resolved Update
After I do prisma migrate save, prisma migrate up and prisma generate, I stopped the server running via terminal and restarted the server after which the model started working. Figured the issue was due to not restarting the server again after Prisma generates a client using new migrations.
Big thank you to #nburk for possible suggestions.