Tips on using Prisma
- Install
prisma
and@prisma/client
differently:
npm install prisma --save-dev
npm install @prisma/client
- Set up a new Prisma project and specify
MySQL
as the datasource provider:
npx prisma init --datasource-provider mysql
- For some unknow reason, this won't work:
import { PrismaClient } from '@prisma/client';
But this works for me:
import { PrismaClient } from '../src/generated/prisma/index.js';
- Add this fragment to
package.json
:
"prisma": {
"seed": "node prisma/seed.js"
},
- To further speed up models creation, paste in JSON object and ask AI. For example:
user
from {JSON} Placeholder
{
"id": 1,
"name": "Leanne Graham",
"username": "Bret",
"email": "Sincere@april.biz",
"address": {
"street": "Kulas Light",
"suite": "Apt. 556",
"city": "Gwenborough",
"zipcode": "92998-3874",
"geo": {
"lat": "-37.3159",
"lng": "81.1496"
}
},
"phone": "1-770-736-8031 x56442",
"website": "hildegard.org",
"company": {
"name": "Romaguera-Crona",
"catchPhrase": "Multi-layered client-server neural-net",
"bs": "harness real-time e-markets"
}
}
And in return:
model User {
id Int @id @default(autoincrement())
name String
username String
email String @unique
phone String
website String
address Address? @relation(fields: [addressId], references: [id])
addressId Int?
company Company? @relation(fields: [companyId], references: [id])
companyId Int?
}
model Address {
id Int @id @default(autoincrement())
street String
suite String
city String
zipcode String
geo Geo? @relation(fields: [geoId], references: [id])
geoId Int?
}
model Geo {
id Int @id @default(autoincrement())
lat String
lng String
}
model Company {
id Int @id @default(autoincrement())
name String
catchPhrase String
bs String
}
Paste in schema.prisma
and run commands:
npx prisma format
npx prisma validate
Strange Enough! For some unknown reason npx prisma format
can fix foreign key reference errors and turn out to be a perfectly valid schema.
- To create tables in target database with:
npx prisma db push
Or in more sophisticated way:
npx prisma migrate dev --name initial_import
Epilogue
"the ridiculous confusion which, in some circumstances, can determine the course of a man’s life."
The Trial by Franz Kafka
As you can see, Prisma is on my tech stack not because I am in favor of ORM, to be honest, I craft and run SQL statements more. The underplaying reason is to secure our investment, ie. the code. It is catastrophic to migrate backend database for any non-trivial projects. How can one change the horse but stay on saddle? Prisma alleviates to some extent, I believe...