Prisma ORM Schema File and Basic Structure


Prisma ORM Schema File and Basic Structure

Today, for robust database access in Node.js and TypeScript projects, many developers prefer Prisma ORM. The Prisma ORM schema file lies at the heart of the database modeling in your project. In this file, everything from database connection settings to models is defined, and your application's interaction with the database becomes standardized. In this article, what the Prisma ORM schema file is, its basic structure, and how to edit the schema file will be explained in detail with examples.

What Is the Prisma ORM Schema File?

The Prisma ORM schema file is typically located in the root directory of your project as schema.prisma. This file consists of three main parts: datasource, generator, and model. The Datasource section contains the database connection information, the generator section gives code generation instructions, and the model section defines the database tables. This way, changes in models can automatically be reflected to the database.

Basic Prisma Schema File Structure

Datasource and Generator Definition

// schema.prisma

datasource db {
  provider = "postgresql"
  url      = env("DATABASE_URL")
}

generator client {
  provider = "prisma-client-js"
}

In the code above, a datasource named db and a generator named client are defined. In the datasource section, the database type and connection URL are specified. The generator points to the package where Prisma Client will be generated.

Creating a Model

model User {
  id        Int      @id @default(autoincrement())
  email     String   @unique
  name      String?
  createdAt DateTime @default(now())
}

Here, a model named User is defined. The id field is auto-incremented and is the primary key. The email is unique, the name field is optional, and createdAt defaults to the current time.

Conclusion: The Power of the Schema File

Thanks to the Prisma ORM schema file and basic structure, database management in projects becomes much easier and more readable. By editing your schema file, you can create and update your database tables with prisma migrate commands. To scale your project and write sustainable code, it is recommended to use the Prisma ORM schema structure effectively.