Sergey Pletnev
Sergey Pletnev

Reputation: 41

How can I get the all fields from Prisma class?

I have these two tables in Prisma schema:

model Accounts {
  id Int @id @default(autoincrement())
  name String @db.VarChar(100)
  description String? @db.VarChar(255)
  timeZone Int @default(0)
  tableBusinessApplication AccountsBusinessApplications[]
}

model AccountsBusinessApplications {
  id Int @id @default(autoincrement())
  account Accounts @relation(fields: [accountId], references: [id])
  accountId Int
  name String @db.VarChar(100)
  identification String @db.VarChar(100)
  secretKey String @db.VarChar(32)
}

I have the follow piece of code:

const name = 'Accounts'
prisma[name].findFirst({
  where: { id: 1}
}).then(result => { console.log(result) })

and as a result I have:

{
  id: 1,
  name: 'test',
  description: 'test description',
  timeZone: 0
}

but I don't see 'tableBusinessApplication' inside. How can I get all data if I know only first class name "Accounts" and I can't use 'Include' in Query?

I try to find how to get a list of fields using prisma class, but it seems like there is nothing.

Upvotes: 4

Views: 8176

Answers (4)

James Tan
James Tan

Reputation: 1366

The provided solutions are outdated for Prisma v5.6.0. Below is my incomplete but functional code for reading from a Prisma schema and generating JSON, which I use for template generation with Hygen.

import { readFileSync, writeFileSync } from 'fs'
import { join } from 'path'

interface Field {
  name: string;
  type: string;
  isUnique: boolean;
  isObjectId: boolean;
}

interface UniqueConstraint {
  fields: string[];
}

interface Index {
  fields: string[];
}

interface Model {
  name: string;
  tableName?: string; // Database table name if specified
  fields: Field[];
  uniqueConstraints: UniqueConstraint[];
  indexes: Index[];
}

// Basic parsing of model definitions
const parseModels = (schema: string): Model[] => {
  const modelRegex = /model (\w+) {([\s\S]*?)^}/gm
  let match
  const models: Model[] = []

  while ((match = modelRegex.exec(schema)) !== null) {
    const modelName = match[1]
    const modelBody = match[2]

    const fields = modelBody.trim().split('\n')
      .filter(line => line && !line.startsWith('@') && !line.startsWith('@@'))
      .map((line) => {
        const [name, type] = line.trim().split(/\s+/)
        const isUnique = line.includes('@unique')
        const isObjectId = line.includes('@db.ObjectId');

        if (name.includes('@@')) {
          return null
        }
        return { name, type, isUnique, isObjectId }
      }).filter(field => field !== null)

    // Extract table mapping
    const tableMappingMatch = modelBody.match(/@@map\(["'](.+?)["']\)/)
    const tableName = tableMappingMatch ? tableMappingMatch[1] : undefined

    // Extract unique constraints
    const uniqueConstraints: UniqueConstraint[] = []
    const uniqueRegex = /@@unique\(\[([^\]]+)\]\)/g
    let uniqueMatch
    while ((uniqueMatch = uniqueRegex.exec(modelBody)) !== null) {
      const fields = uniqueMatch[1].split(',').map(field => field.trim())
      uniqueConstraints.push({ fields })
    }

    // Extract indexes
    const indexes: Index[] = []
    const indexRegex = /@@index\(\[([^\]]+)\]\)/g
    let indexMatch
    while ((indexMatch = indexRegex.exec(modelBody)) !== null) {
      const fields = indexMatch[1].split(',').map(field => field.trim())
      indexes.push({ fields })
    }

    models.push({ name: modelName, tableName, fields, uniqueConstraints, indexes })
  }

  return models
}

const parsePrismaSchema = (schemaPath: string): Model[] => {
  const schema = readFileSync(schemaPath, 'utf8')
  return parseModels(schema)
}

const main = () => {
  const schemaPath = join(__dirname, '../../prisma/schema.prisma')
  const models = parsePrismaSchema(schemaPath)
  const schemaJsonPath = join(__dirname, '../../prisma/schema.json')
  const schemaJson = JSON.stringify(models, null, 2)
  // console.log(schemaJson)
  writeFileSync(schemaJsonPath, schemaJson)
}

main()

Upvotes: 0

As of Prisma 5:

const allowedFields = Object.keys(prisma[this.modelName].fields)

Upvotes: 5

techpet
techpet

Reputation: 81

As of Prisma 4:

import { Prisma } from '@prisma/client';

console.log("Account fields:", Prisma.dmmf.datamodel.models.find(model => model.name === "Account").fields)

Upvotes: 8

Nurul Sundarani
Nurul Sundarani

Reputation: 7608

You can use Prisma's DMMF property to get the name of the fields of a model.

import { PrismaClient } from '@prisma/client';

const prisma = new PrismaClient();


// A `main` function so that you can use async/await
async function main() {

  // @ts-ignore
  console.log('dmmf', prisma._dmmf.modelMap.Accounts.fields);
}
main()
  .catch((e) => {
    throw e;
  })
  .finally(async () => {
    await prisma.$disconnect();
  });

Here's the output

dmmf [
  {
    name: 'id',
    kind: 'scalar',
    isList: false,
    isRequired: true,
    isUnique: false,
    isId: true,
    isReadOnly: false,
    type: 'Int',
    hasDefaultValue: true,
    default: { name: 'autoincrement', args: [] },
    isGenerated: false,
    isUpdatedAt: false
  },
  {
    name: 'name',
    kind: 'scalar',
    isList: false,
    isRequired: true,
    isUnique: false,
    isId: false,
    isReadOnly: false,
    type: 'String',
    hasDefaultValue: false,
    isGenerated: false,
    isUpdatedAt: false
  },
  {
    name: 'description',
    kind: 'scalar',
    isList: false,
    isRequired: false,
    isUnique: false,
    isId: false,
    isReadOnly: false,
    type: 'String',
    hasDefaultValue: false,
    isGenerated: false,
    isUpdatedAt: false
  },
  {
    name: 'timeZone',
    kind: 'scalar',
    isList: false,
    isRequired: true,
    isUnique: false,
    isId: false,
    isReadOnly: false,
    type: 'Int',
    hasDefaultValue: true,
    default: 0,
    isGenerated: false,
    isUpdatedAt: false
  },
  {
    name: 'tableBusinessApplication',
    kind: 'object',
    isList: true,
    isRequired: true,
    isUnique: false,
    isId: false,
    isReadOnly: false,
    type: 'AccountsBusinessApplications',
    hasDefaultValue: false,
    relationName: 'AccountsToAccountsBusinessApplications',
    relationFromFields: [],
    relationToFields: [],
    isGenerated: false,
    isUpdatedAt: false
  }
]

Please note that DMMF is an internal API and may have changes in future versions.

Upvotes: 1

Related Questions