Prisma constraint not available - postgresql

I`m using Prisma with NestJS and PostgreSQL
In my schema.prisma i have this
model User {
userId Int #id #default(autoincrement())
firstName String? #db.VarChar(25)
lastName String? #db.VarChar(25)
login String #unique #db.VarChar(60)
email String #unique
password String
createdAt DateTime #default(now())
updatedAt DateTime #updatedAt
role Role? #default(ADMIN)
createdUsers User[] #relation("createdBy")
createdBy User? #relation("createdBy", fields: [creatorId], references: [userId])
creatorId Int?
}
enum Role {
ADMIN
MANAGER
WAREHOUSE
USER
}
So when a make create request like this
{
login: "A",
email: "A",
password: "A"
}
it saves in DB - that`s ok. By after the same request i get this error "Unique constraint failed on the (not available)". So shouldn't there be a not unique column name instead of (not available) or that is ok case? Where am i wrong?
I was trying drop table Users and make different unique combs, don`t know what else i can do...
UPD:
async create(createUserDto: CreateUserDto) {
return this.prisma.user.create({
data: {
...createUserDto
}
})
}
export class CreateUserDto {
#IsNotEmpty()
login: string;
#IsNotEmpty()
#IsEmail()
email: string;
#IsNotEmpty()
#MinLength(6)
password: string;
}
UPD 2.0
Finally, moved to TypeORM, it is bug like #num8er mentioned
https://github.com/prisma/prisma/issues/10829
Ty for all the replies

Related

Prisma connect product to users with quantity

I have a list of products, and a list of users and I want to be able to relate users to what products they have but also what quantity they have of each product.
I've setup my user schema like this:
model users {
id String #id #default(uuid())
email String #unique
password String
test_products test_products[]
users_to_test_products users_to_test_products[]
}
I've implicitly stated the relation so that I can add in a quantity field
model users_to_test_products {
users users #relation(fields: [user_id], references: [id])
user_id String
test_products test_products #relation(fields: [product_id], references: [product_id])
product_id String
quantity Int
##id([user_id])
}
and I've setup my product list like this:
model test_products {
product_id String #id
name String?
users users[]
users_to_test_products users_to_test_products []
}
I assumed I could make an update call, connecting the user to the test product and passing in the quantity but it seems that I can't and my approach is completely wrong.
await prisma.users.update({
data: {
test_products: {
connect: UserProducts.map((product) => {
return {
product_id: product.product_id,
quantity: product.quantity
}
}),
},
},
where: {
id: userId
},
})
note: UserProducts is just an object array eg [{ product_id: "tTer3434", quantity: 8 }]
Can anyone point me in the right direction on the approach I need to take please?

How to retrieve parent table using child table in Gorm

i'm new to Golang and facing retriving child table data that container id refer to parent table id. In the documentation shows that only the parent can retrieve child using preload method but didn't show how to retrieve reversed back.
(one to many relationship)
Parent Table
type User struct {
Id uuid.UUID `gorm:"type:uuid;default:gen_random_uuid()" json:"id"`
Username string `json:"username"`
Password string `json:"password,omitempty"`
Email string `json:"email"`
Gender string `json:"gender"`
Alias string `json:"alias"`
RefreshToken *string `json:"refresh_token,omitempty"`
AccessToken *string `json:"access_token,omitempty"`
DateOfBirth *time.Time `json:"date_of_birth"`
LastLoggedIn *time.Time `json:"last_logged_in"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
Account []Account `json:"account"`
}
Child Table
type Account struct {
Id uuid.UUID `gorm:"type:uuid;default:gen_random_uuid()" json:"id"`
Name string `json:"name"`
Balance float32 `json:"balance"`
UserId string `json:"user_id"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
Was hoping that can return json like this:
[{
"Id":"xxx",
....
User: {"Id":"xxx"}
}]
I'm not sure is this possible or not but prisma did it, sorry for disturb your time and have a nice day!
You can add which fields you want to preload and how deep to go. Check nested preloading.
In your case, you could do it like the below.
add User field to Account struct:
type Account struct {
Id uuid.UUID `gorm:"type:uuid;default:gen_random_uuid()" json:"id"`
Name string `json:"name"`
Balance float32 `json:"balance"`
UserId string `json:"user_id"`
User *User `json:"user"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
in your method:
var users []User
// Preload Account field inside User struct, and User field inside Account struct
err := db.Preload("Account.User").Find(&users).Error

Prisma relations: define relations without using "connect" syntax

I use Postgres with Prisma and I want to ask if there is a way to use upsert or create functions and define relations without the connect field.
I have these models:
model User {
id Int #id #default(autoincrement())
posts Post[]
}
model Post {
id Int #id #default(autoincrement())
author User #relation(fields: [authorId], references: [id])
authorId Int // relation scalar field (used in the `#relation` attribute above)
}
and I want to do something like this:
prisma.Post.upsert({where: { authorId: 12 }, update: {}, create: { authorId: 12 })
assuming User with ID 12 does exists in the DB I want it to create a new record successfully but it fails because it wants it in this syntax:
prisma.Post.upsert({where: { authorId: 12 }, update: {}, create: { author: { connect: { id: 12}}}})
is this achievable somehow?
Thanks.

How to write a migration to add not null in table field GOLANG

I want to alter a column in User Model
type User struct {
gorm.Model
Email string `gorm:"unique;type:varchar(50)"`
Password string
Active bool
FirstName string `gorm:"type:varchar(10)"`
LastName string `gorm:"type:varchar(10)"`
Age int
Gender bool `gorm:"type:boolean"`
MaritalStatus bool `gorm:"type:boolean"`
Address string `gorm:"type:varchar(10)"`
City string `gorm:"type:varchar(10)"`
State string `gorm:"type:varchar(10)"`
Country string `gorm:"type:varchar(10)"`
ContactNoOne string `gorm:"type:varchar(13)"`
ContactNoTwo string `gorm:"type:varchar(13)"`
}
I want to make Email field as not nullable. How to write migration for that?
add not null on tag gorm
type User struct {
...
Email string `gorm:"unique;type:varchar(50);not null"`
...
}
doc : https://gorm.io/docs/models.html
Edit your model, then us AutoMigrate
db.AutoMigrate(&User{})
Documentation: https://gorm.io/docs/migration.html

Nested writes in Prisma orm

My schema looks like this:
model Transaction {
id BigInt #id #default(autoincrement())
description String? #db.VarChar(256)
category Category? #relation(fields: [categoryId], references: [id])
createdById Int #map("fk_created_by")
createdBy UserAccount #relation("category_fk_created_byTouser_account", fields: [createdById], references: [id]
}
model Category {
id Int #id #default(autoincrement())
name String #db.VarChar(40)
categoryFilters CategoryFilter[]
}
model CategoryFilter {
id BigInt #id #default(autoincrement())
words String #db.VarChar(255)
categoryId Int? #map("fk_category_id")
}
My question is why this works:
await prisma.workspaceTransaction.create({
data: {
description: 'any',
createdBy: {
connect: {
id: 1
}
},
category: {
create: {
name: 'Este é um teste',
createdById: 1,
categoryFilters: {
createMany: {
data: [
{
words: 'Novo teste'
}
]
}
}
}
}
}
})
And this not?
await prisma.workspaceTransaction.create({
data: {
description: 'any',
createdById: 1,
category: {
create: {
name: 'Este é um teste',
createdById: 1,
categoryFilters: {
createMany: {
data: [
{
words: 'Novo teste'
}
]
}
}
}
}
}
})
The only difference between those two examples is in createdBy command. And i can create Transaction without nested objects with createdById argument. Any one know why this works this way? Or there is something i am missing?
The error given is:
Unknown arg createdById in data.createdById for type TransactionCreateInput
In the second example, you are directly writing a foreign key (createdById) which is considered unsafe, what if there is no UserAccount corresponding to createdById.
While using connect in the first example it would throw an error if Prisma cannot find an UserAccount corresponding to id 1.
First example is the preferred approach.