prisma: "Field does not exist on enclosing type" / Relation tables bug
Bug description
I have some Question for prisma2 join table. and also one issue
- Schema:
//other
model LayoutSetting {
id Int @id @default(autoincrement())
order Int
route String @db.VarChar(255)
category LayoutSettingCategory @default(CategoryListRow)
title String @unique @db.VarChar(255)
relatedLayoutToProduct LayoutSettingLinkProduct[]
}
model LayoutSettingLinkProduct {
layoutId Int
productId Int
order Int
layout LayoutSetting @relation(fields: [layoutId], references: [id])
product Product @relation(fields: [productId], references: [id])
@@id([layoutId, productId])
@@index([order])
}
model Product {
id Int @id @default(autoincrement())
order Int
thumb String @db.VarChar(255)
infoURL String @db.VarChar(255)
title String @unique @db.VarChar(255)
desc String @db.VarChar(255)
createAt DateTime @default(now()) @db.DateTime(6)
updateAt DateTime @default(now()) @updatedAt @db.DateTime(6)
levelStart Int
levelEnd Int
language String @db.VarChar(255)
isTrackCollection Boolean @default(false)
infoThumb String @db.VarChar(255)
cover String @db.VarChar(255)
isProductRenewal Boolean @default(false)
//relatedLayoutToProduct LayoutSettingLinkProduct[] (it might be not nesseary need it)
//mediaList MediaCollection[] (it might be not nesseary need it)
//ownedProduct OwnedProduct[] (it might be not nesseary need it)
//tags Tag[]
}
After executing many transactions and queries as a batch program, the following errors occurred.
Invalid prisma.layoutSettingLinkProduct.deleteMany()
invocation:
Failed to validate the query: `Field does not exist on enclosing type.` at `Mutation.deleteManyLayoutSettingLinkProduct`
at cb (/Users/creejee/*****/renewal-project/*********/node_modules/@*****************/appsync-schema/prisma/generated/client/runtime/index.js:36952:17)
at runMicrotasks (<anonymous>)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async upsertLayout (/Users/creejee/*****/renewal-project/*********/util/batch/appsync/insertProductData.js:59:9)
at async task (/Users/creejee/*****/renewal-project/*********/util/batch/appsync/insertProductData.js:496:9) {
code: 'P2009',
clientVersion: '3.1.1',
meta: {
query_validation_error: 'Field does not exist on enclosing type.',
query_position: 'Mutation.deleteManyLayoutSettingLinkProduct'
}
}
The following sample code was written for problem trouble shooting, and there was no error at this time.
import { PrismaClient } from "./prisma/generated/client";
const prismaClient = new PrismaClient()
const layout = await prismaClient.layoutSetting.create({
data: {
title: "test",
order: 0,
route: "/",
},
});
const product = await prismaClient.product.create({
data: {
cover: "",
desc: "",
infoThumb: "",
infoURL: "",
language: "",
levelEnd: 0,
levelStart: 0,
order: 0,
thumb: "",
title: "",
},
});
if (layout && product) {
await prismaClient.layoutSettingLinkProduct.createMany({
data: {
layoutId: layout.id,
productId: product.id,
order: 1,
},
});
const { count } =
await prismaClient.layoutSettingLinkProduct.deleteMany({
where: {
layoutId: layout.id,
// productId: undefined,
},
});
console.log(count);
}
I don’t know what I need to solve the problem, and I don’t know why there’s no error in the sample code… Is this a bug? Or is it my fault?
How to reproduce
i’m trying reproduce but it does’t error
Expected behavior
it run success
Prisma information
I send it full schema and stdout log schemas@prisma.io
Environment & setup
- OS:
➜ ~ sw_vers
ProductName: macOS
ProductVersion: 11.6
BuildVersion: 20G165
➜ ~ uname
Darwin
- Database: mysql (aurora-serverless with ssh tunneling)
- Node.js version: v16.8.0
Prisma Version
prisma : 3.1.1
@prisma/client : 3.1.1
Current platform : darwin
Query Engine (Node-API) : libquery-engine c22652b7e418506fab23052d569b85d3aec4883f (at node_modules/@prisma/engines/libquery_engine-darwin.dylib.node)
Migration Engine : migration-engine-cli c22652b7e418506fab23052d569b85d3aec4883f (at node_modules/@prisma/engines/migration-engine-darwin)
Introspection Engine : introspection-core c22652b7e418506fab23052d569b85d3aec4883f (at node_modules/@prisma/engines/introspection-engine-darwin)
Format Binary : prisma-fmt c22652b7e418506fab23052d569b85d3aec4883f (at node_modules/@prisma/engines/prisma-fmt-darwin)
Default Engines Hash : c22652b7e418506fab23052d569b85d3aec4883f
Studio : 0.423.0
About this issue
- Original URL
- State: open
- Created 3 years ago
- Reactions: 8
- Comments: 117 (22 by maintainers)
If anyone is still having trouble, for me this was related to Nx monorepo caching the .prisma directory from a previous build. These caches are not easy to spot in your directory tree.
Some quick commands to try:
To find
.prisma
cachesFor me this returned
Delete
node_modules/.prisma
andnode_modules/.cache
directory, and then regenerate prisma clientWorking again for me 🎉
Hey all 20+ people that reported this problem here, as you can see with the labels we still do not have a good idea why this s happening - which is required for us to fix it. And we definitely want, you all staying on 3.0.2 is a workaround, but not something that should become a long term solution.
So, let’s take another look if we can figure this out. Everyone who posted here and still has the problem, please do the following things two times. Once for your project in its working state (with whatever version that was, or 3.0.2 if you went to that) and once with a failing newer version of Prisma (either the current 3.5.0 or whatever you tried before):
npx prisma -v
in your project directory and store the full output of thatDEBUG=*
, full instructions at https://pris.ly/d/debuggingPrismaClient
, instructions at https://pris.ly/d/loggingThen when you have these 2 data bits (version info and log output) for both cases, please post a comment here with the in total 4 output copies or send them to me at
jan@prisma.io
if you do not want to share them publicly.While you are at it, and you are comfortable with that, please archive your full failing project (including your node_modules!) into a zip file, upload it somewhere, and send the link to me at
jan@prisma.io
as well. Maybe we can figure out what is going wrong by looking at the code that is actually running on your computers.I know we are asking for a lot here, but this seems like the only way forward here and to finally hopefully be able to understand what is going on here. Thanks!
I faced the same issue. Turns out I had a
.prisma
folder indist
folder. After deleting the issue was fixed@janpio no the missing
.env
file message did not cause the failure but probably points to the problem.The project had two
.prisma/clients
one in./node_modules
and one in./apps/node_modules
which I accidentally created by runningnpx prisma generate
in./apps/
instead of the project root.I can confirm that removing the second client in ./apps/ did indeed resolve my problems. But I just tried to break a working install by running
npx prisma generate
in./apps
, but even after a full compile the code still ran. Thus is seems that it is not a one flick switch but might involve doing other things like runningnpm/yarn install
to change the order of package/module resolution.But having two generated clients based on (potentially) different schemas does explain quite a few of the issues I experienced. E.g why “old” queries kept on working, but new additions not. Or why even removing models did not work as expected.
Wonder if it would be worth to ensure that the client created by
prisma generate
is only written in folders containing a package.json, or if it’s not present traverses up to the closest ancestor with one?I am getting this error, here’s a minimal example, just using npm.
https://github.com/aantthony/prisma-bug
It seems to be triggered if there are two simultaneous requests to findUniqueOrThrow.
Looks like it’s fixed in 4.7.1. My example works now.
Thanks a lot! I run
find . -name .prisma
and it loggedso I deleted only
./.yarn/unplugged/@prisma-client-virtual-8a63005ea4/node_modules/.prisma
and now it’s working again on Prisma 3.9.0.oh my god, having the same problem now 😦
Having same issue, solved by deleting duplicated .prisma folders.
After having used 3.2.1 for a few weeks without any problems. I changed the name of one model today and since then I see the same problem for that renamed table and any other newly added model.
I haven’t made any changes to the used packages in the last days, but made frequent changes to the schema
Weirdly all previously existing tables remain working. Just newly added are not.
Even, if I reduce the
prisma.schema
to just one new modela
prisma db push
does yield to a broken client.While reverting from 3.2.1 to 3.1.1 did not help, I can confirm that downgrading to 3.0.2 does solve this issue, new and old tables do work as they should.
I’ve manually removed
/node_modules/.prisma
and/node_modules/@prisma/...
and reinstalled the packages for 3.2.1 and 3.1.1 this did not help, and fully reset the database (as in dropping the docker container and rebuilding it).Upgrading the working 3.0.2 to 3.2.1 does show the same problems.
-Changing the initially changed table"s name back to the working state did not help either.
npx prisma studio
does work in 3.2.1 and 3.1.1 new and old tables are working. It’s just the the client in jsthat raises the error …
Is there any other cache I could clear? What is the difference between studio and JS client?
Thank you!
For me, the issue seems introduced in Prisma 3.1.1 - prisma 3.0.2 works fine.
The issue occurs when creating multiple clients, probably since you’re using a monorepo with microservices and multiple schemas.
Why
By default, prisma generates the client under
node_modules/.prisma
.Since this is global, the last generated client will be used, so if you have multiple services that you want to run/test it won’t work.
A partial solution is to create a separate prisma client per service by specifying a relative path in
schema.prisma
:This will create a client per service, but you have to import it explicitly instead of
@prisma/client
, because@prisma/client
importsnode_modules/.prisma/client
When using this method, the client remembers the location it was generated in, and after you build it will still use the original folder. For example, if you have
apps/users/.prisma/client
, and your build goes todist/apps/users
, it will still try to use the client from the first folder.Once the application is built, the prisma client uses the
apps/users
folder as it’s working directoryIt finds the project root
/
and starts searching for.prisma/client
.It uses the first client it finds using alphanumeric sorting, so if we have
apps/auth/.prisma
andapps/users/.prisma
it will pick auth regardless of the current service.This means the
users
service will use theauth
client, causingField does not exist on enclosing type
.Only the first alphanumeric service will work
A workaround is to
find . -name .prisma
and delete all the folders. But this means you can only run a single service at a time and clean up after it, which is not acceptibleHow to fix
You need to build and develop using the same prisma path. We did this by:
copying the
prisma
folder to thedist
path before buildingGenerate the client using
npx prisma generate --schema=apps/users/prisma/schema.prisma
Add output path to your schema (will help for
jest
config)This will result in the following structure:
tsconfig.json
(not the global one)Unfortunately it’s a really long workaround, but still worth it to use prisma 😃
I can also confirm this issue.
I can reproduce this with MySQL 5.7 and Prisma 3.7.0
After I run
ls **/.prisma
and delete all other prisma directories, it starts working again.Also it works in 3.0.2 as mentioned in previous comments before I delete other prisma directories
I followed @novazembla instructions and added some console.log calls in ./node_modules/.prisma/client/index.js.
Got some interesting outputs, first line is the file path of client/index.js, second one is the path returned by findSync:
This project uses AWS CDK to create an infrastructure and deploy the code on it. Binaries are bundled and cached as assets in the cdk.out folder. It’s been a long time since I built the project with CDK, and the content of that folder is clearly outdated compared to the current state of the source code.
Here is a simplified tree hierarchy for the project:
myproject/ cdk.out dist node_modules src …
I removed the cdk.out folder, and gave it another try. here are the console output results:
Ok, findSync found another path in the dist folder this time. Luckily for me, the content of this folder is in sync with the code, and now all prisma calls pass, no more errors.
Still, I would have expected client/index.js to priorize it’s own path first.
If not found, then try a findSync and cross your fingers that the returned path makes sense.
Yes, a user before describes that cleaning up any possible
.prisma
packages in subfolders fixed the problem for them. This should obviously not be the case or fail in this way, but it seems it currently is.Yes, there is a postinstall hook that generates prisma generate & also I’ve removed many fields (which requires a regenerate every time). I had a look at the debugging guide in Prisma and this was my full trace… bit massive:
@janpio I’m going to dive deeper into this now, but this is the same issue I’m experiencing on the Calendso / Cal.com project @ https://github.com/calendso/calendso when I upgrade to Prisma 3 (3.2.1) - without any code changes I am greeted with: Failed to validate the query:
Field does not exist on enclosing type.
atQuery.findUniqueUser.User.locale
. This is on what I consider a exceedingly simple findUnique query:Keeping you updated, but if you’re interested in seeing it crash yourself is: just checkout
main
and update prisma to 3.@janpio I have been battling with this for a while. I am not sure how to reproduce this.
I went back to 3.0.2, and it all works now.
With 3.1.1 I didnt get it to work, even if I deleted all tables, prisma, prisma folder… etc. And for now I will not update for a while, I got to much to do on other parts.
Hi all, I’m also faced this issue when using
.findUniqueOrThrow
on version 4.7.0. Downgrade to version 4.6.1 to fix.Not sure if it help in something but n my case it is happening when I execute a plain node application with the full path, in the currency app directory if I execute
node app.js
it works, but when callingnode /path/to/app.js
I got this errorI found a predictable way of producing multiple
.prisma
folders within a yarn or pnpm monorepo. Given the following structure:package-1
is a package of the monorepo and depends onprisma
and@prisma/client
pnpm -r prisma generate
in/
pnpm prisma generate
in/packages/package-1
Conclusion
.prisma-directory is created in the node_modules folder, which is closest to the working directory which was used when executing the
pnpm
/yarn
run command.Expected
Created in the node_modules folder which is closest to the actual package directory
This might cause some of these issues. At least it’s causing issues with type checking in a monorepo and the developer has to make sure to always
cd packages/package-1
before using the prisma cli. As removing duplicate.prisma
-folders seems to fix the issue in OP, maybe this could be the cause?UPDATE: sorry, submitted too early by accident. Happy to provide a repo which reproduces this or open another issue if it turns out to be unrelated
I was able to create a reproduction for postgres in this repo: https://github.com/matthewmueller/prisma-ra
It’s an oddball, but it seems path-related.
@janpio what you need to do is the following
prisma db push
orprisma generate
in the project rootfindMany
on one of the models to see all works wellapps
,code
, you name it, let’s useapps
)cd
intoapps
and runprisma generate
prisma db push
in the project’s root folderfindMany
query for the new model in the test scriptapps
folder toxapps
findMany
queries are working as they shouldxapps
folder toapps
findMany
fails with the above error message. GOTO 7 😃Obviously you could also remove
apps/node_modules
and see that the new version is working.@janpio I believe if you cd in to any folder in a prisma project, and run
yarn prisma generate
it will create a new node_modules with your .prisma folder. This folder will then end up being the one referenced instead of the “true” root node_modules .prisma folder.Unsure if that was your request.
Curious thing…
nvm use v14.17.4
(not facing this issue) /nvm use v14.17.5
(this issue started happening)Maybe this helps someone
Oh, sorry, I missed some context here. Yeah, if it’s running the correct client in both cases and doesn’t run the outdated client, doesn’t mix the client and the Query Engine from different directories, etc, then I’m not sure why that happens. (FWIW, I don’t know what exactly would go wrong in that case either, it just sounds like something likely to break).
P.S. In any case it would probably uber-useful if the debug log would spit out the loaded schema path and maybe the root env path. It certainly would have helped me spot the problem sooner.
@hmica that exactly been it! Sure enough there was a stub in the
./apps/
subfolder and once removed the broken branch has been revived to working order. This also explains why the broken version was assuming that./apps/
is the root and tried to load the.env
from there.Hi, I just past my entire day on this one. I found that if I run
yarn prisma generate
from a sub directory it will generate stub in that sub directorywith .prisma/client on /home/user/work/my-project/my-sub-folder/node_modules/
but if I run
npx prisma generate
from that subdirectory it will complain that it can not find the prisma.schema file so it’s safer.So be sure that you don’t have .prisma/client duplication.
error logs are as follows.
@aqrln @janpio
Hey guys, please find my logs below. While generating this one I noticed a difference between the working and the non working versions. Although the code base is the same the broken version tries to load the environment variables from a different folder and fails to do so…
Non working
Working:
It’s a monorepo using the following workspace definition
Does the broken version assume that the project root is
/apps/
? Could this cause the issues?Anyhow, here is the full dump of the non working version.
And for comparison the working version’s debug output
I solved the issue for me:
prisma
and@prisma/client
npx prisma generate
🎉 It’s working (for me at least)
I have the same issue here with prisma 3.5.0, on Windows 10. Rolling back to 3.0.2 fixes the issue. Performing a findMany on all models, only one of them throws an error:
I have two macs, M1 and Intel. M1 has no problem with any version of prisma(3.0. 3.3, 3.4). But Intel has this ‘Field does not exist on enclosing type’ error. So I had to downgrade to 3.0.2.