week 10.2 prisma
//using ORM : Simpler syntax (converts objects to SQL queries under the hood)
//codeCREATE TABLE users (
id SERIAL PRIMARY KEY,
name VARCHAR(100),
email VARCHAR(100) UNIQUE NOT NULL
);
ALTER TABLE users
ADD COLUMN phone_number VARCHAR(15);
id SERIAL PRIMARY KEY,
name VARCHAR(100),
email VARCHAR(100) UNIQUE NOT NULL
);
ALTER TABLE users
ADD COLUMN phone_number VARCHAR(15);
//As your app grows, you will have a lot of these
CREATE and ALTER commands.ORMs (or more specifically Prisma) maintains all of these for you.
fd
//Data mode in prisma
1. Data model
In a single file, define your schema. What it looks like, what tables you have, what field each table has, how are rows related to each other.
2. Automated migrations
Prisma generates and runs database migrations based on changes to the Prisma schema.
3. Type Safety
Prisma generates a type-safe database client based on the Prisma schema.

4. Auto-Completion

//installing prisima lets create simple todo app
1. initialize an empty node.js project
// npm init -y
1. Add depedency
// npm install prisma typescript ts-node @types/node --save-dev
1. initialize typescript
// npx tsc --init
Change `rootDit` to `src`
Change `outDir` to `dist`
Change `rootDit` to `src`
Change `outDir` to `dist`
1. initiallize a fresh prisma project
// npx prisma init
1. install all dependency use in index.ts or other file
//npm install --save-dev @types/express
+++++++++++++++++++++++++++++++++++++++++++++++++
if show error on node-module on that time you already instll all dpendency then use this code
1 . first install globally yarn
// npm install -g yarn
2. be present on your project directory and this command
// yarn install
3. then install npm dependency
// npm install
+++++++++++++++++++++++++++++++++++++++++++++++++
//If your final app will have a Users table, it would look like this in the
schema.prisma filemodel User {
id Int @id @default(autoincrement())
username String @unique
password String
firstName String
lastName String
}
id Int @id @default(autoincrement())
username String @unique
password String
firstName String
lastName String
}
// This is your Prisma schema file,
// learn more about it in the docs: https://pris.ly/d/prisma-schema
generator client {
provider = "prisma-client-js"
}
datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
}
model User {
id Int @id @default(autoincrement())
username String @unique
password String
firstName String
lastName String
}
model Todo {
id Int @id @default(autoincrement())
title String
description String
done Boolean @default(false)
userId Int
}
// learn more about it in the docs: https://pris.ly/d/prisma-schema
generator client {
provider = "prisma-client-js"
}
datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
}
model User {
id Int @id @default(autoincrement())
username String @unique
password String
firstName String
lastName String
}
model Todo {
id Int @id @default(autoincrement())
title String
description String
done Boolean @default(false)
userId Int
}
Generate migrations
You have created a single schema file. You haven’t yet run the
CREATE TABLE commands. To run those and create migration files , run //after this snippet they ask migration name use 'anyname
npx prisma migrate dev --create-only
//You can now edit it and apply it by running
npx prisma migrate dev
1. npx prisma migrate dev --name Initialize the schema1. npx prisma migrate dev --name [UserAndTodoAdded] //UserAndTodoAdded is name of migration Your DB should now have the updated schema if drift detected then your older migration will be removed and new created.
Once you’ve created the
prisma/schema.prisma, inside you write schema. you need to convert your schema into your client, now you can generate these clients that you can use in your "Node.js[index.ts] app"How to generate the client?
npx prisma generateThis generates a new
client for you.1. if you get warn Versions of prisma@5.14.0 and @prisma/client@5.13.0 don't match.
This might lead to unexpected behavior.
Please make sure they have the same version.
then you need to update you prisma/client version use this code
// npm install @prisma/client@5.14.0
//way to import in prisma
import { PrismaClient } from '@prisma/client'
const prisma = new PrismaClient()
const prisma = new PrismaClient()
[OR]
import { PrismaClient } from '@prisma/client/edge'
const prisma = new PrismaClient()
const prisma = new PrismaClient()
Insert
Write a function that let’s you insert data in the
Users table.Typescript will help you out, here’s a starter code -
import { PrismaClient } from "@prisma/client";
const prisma = new PrismaClient();
async function insertUser(username: string, password: string, firstName: string, lastName: string) {
const res = await prisma.user.create({
data:{
username,
password,
firstName,
lastName
}
})
console.log(res);
}
insertUser("harkirat@gmail.com", "password", "harkirat", "Singh")
//for run this code use tsc -b or npx tsc -b
// the node dist/index.js
Update
Write a function that let’s you update data in the
Users table.Starter code -
import { PrismaClient } from "@prisma/client";
const prisma = new PrismaClient();
interface UpdateParams {
firstName: string;
lastName: string;
}
async function updateUser(username: string, {
firstName,
lastName
}: UpdateParams) {
const res = await prisma.user.update({
where: { username },
data: {
firstName,
lastName
}
});
console.log(res);
}
updateUser("admin1", {
firstName: "new name",
lastName: "singh"
})

Get a user’s details
Write a function that let’s you fetch the details of a user given their email
Starter code
import { PrismaClient } from "@prisma/client";
const prisma = new PrismaClient();
async function getUser(username: string) {
const user = await prisma.user.findFirst({
where: {
username: username
}
})
console.log(user);
}
getUser("admin1");
Comments