Get started with Prisma - Step 1 - Migrations
Step 1 - Migrations
2022-05-22
What's this?
Today we'll cover migrations in Prisma. We'll create a couple of models, add some data and perform respective queries. We'll extend the current schema with clients and product reviews.
Instructions
I suppose you've already read the instructions of step 0 here and you've got some response from the hello-world-like example.
If you're bored do a git fetch and switch to the step1 branch (git checkout step1), copy .env.example to .env, run yarn prisma generate and skip the next steps.
Otherwise...
- First we need to create an initial migration, so let's do it: 
yarn prisma migrate dev --name initial-migration. This will require you to delete existing data. For convenience, I've already supplied a dump in theprismafolder, namedmydb_initial.sql. - Run 
cat db/mydb_initial.sql | sqlite3 ./db/mydb.sqliteto reimport data. - Now let's add the 
Clientstable. Add this to theprisma/schema.prismafile: 
model Client {
  Id           Int     @id @default(autoincrement())
  ClientName String?
  ClientSurname  String?
}
- Run 
yarn prisma migrate devto generate the respective migration and of course generate a new@prisma/clientfor this application. - Now the Prisma client knows how to handle the 
Clienttable. - Now let's add the 
Reviewmodel and make changes to theProductandClientmodels. Add these lines to theprisma/schema.prismafile: 
model Review {
  grade        Int
  clientId     Int
  productId    Int
  client     Client        @relation(fields: [clientId], references: [Id])
  product     Product        @relation(fields: [productId], references: [Id])
  @@id([clientId, productId])
}
Change Client as shown below:
model Client {
  Id           Int     @id @default(autoincrement())
  ClientName String?
  ClientSurname  String?
  Review       Review[]
}
Change Product as follows:
model Product {
  Id              Int     @id @default(autoincrement())
  ProductName     String?
  SupplierId      Int
  CategoryId      Int
  QuantityPerUnit String?
  UnitPrice       Decimal
  UnitsInStock    Int
  UnitsOnOrder    Int
  ReorderLevel    Int
  Discontinued    Int
  Review          Review[]
}
- Run 
yarn prisma migrate dev --name add-reviews, check the new migration that was made insideprisma/migrations. - Now the Prisma client knows how to handle the updated 
ClientandProductmodels and their M:N relation through theReviewmodel. 
What I can do next?
- Run 
yarn prisma studioto start Prisma Studio and check the changes. Add some clients and some reviews. - Run 
yarn tsc ./src/index.tsand thennode dist/index.jsto see the Clients and the Reviews table on the console. - Play around and have fun with the 
src/step1.ts 
Crafted with ❤ in Crete. © 2022-2024