Is there a way to iterate over all tables in a sch...
# orm-help
j
Is there a way to iterate over all tables in a schema with the prisma client itself? So without using raw queries?
r
Do you just want the table names or the data?
j
Basically I want to call a function on each table
So names would be enough
@Ryan Sorry, don't know if I should tag you in these treads or if that's aggressive. I often overlook them myself though 😅
r
One option is to use
dmmf
to get table names:
Copy code
const prisma = new PrismaClient();

console.log(prisma._dmmf);
In this object, you would get all the table names.
j
Thanks for your answer. I actually tried that, as well as iterating over the prisma object and then filtering the attributes that begin with an underscore. But how would I use thes strings then? Because
prisma[tableNam]
doesn't seem to work?
r
It will work as long as the tableName matches the model name
You won't get TypeScript autocomplete but it will work
j
Copy code
export async function deleteAllTables(
  prismaClient: PrismaClient
): Promise<void> {
  for (const key of prismaClient._dmmf) {
    prismaClient[key].deleteMany({})
  }
}
This doesn't work. Especially since _dmmf doesn't seem to be iterable
r
It’s inside a specific key in
_dmmf
. You need to log this entire object to get where the models are exactly located.
j
Yeah, sorry, should've added: that is
enumMap
as far as I can tell and it doesn't seem to be iterable as well
Copy code
TypeError: prismaClient._dmmf.enumMap is not iterable

      107 |   prismaClient: PrismaClient
      108 | ): Promise<void> {
    > 109 |   for (const key of prismaClient._dmmf.enumMap) {
          |                                        ^
      110 |     prismaClient[key].deleteMany({})
      111 |   }
      112 | }
r
It would be an object, so you would need to use
Object.entries
to make it iterable.
j
Ah, makes sense. I will try that, thanks!
👍 1