Full Stack Development

Prisma and ORM

by Tomas Trescak t.trescak@westernsydney.edu.au

Databases

/

ORM and Prisma


  • Why ORMS?
    • Tricky (raw) Queries
    • Security
  • Prisma
    • Modern
    • TypeSafe
    • Secure?
  • Blog .. let's Continue!

Databases

/

What is ORM?

    SELECT * FROM posts
prisma.post.findMany()

SELECT * FROM posts WHERE id = 1
prisma.post.findUnique({ where: { id: 1 } })
  
  • Mapping of database objects to functions
  • Type-safe, efficient data management

Prisma

/

Setup

    pnpm i prisma --save-dev 
pnpm i @prisma/client
pnpm prisma init
  
terminal

Prisma

/

Schema

    // prisma/schema.prisma
datasource db {
  provider = "sqlite"
  url      = env("DATABASE_URL")
}

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

model Post {
  id        Int      @id @default(autoincrement())
  title     String
  content   String
  date      DateTime
  tags      Tag[]    @relation("PostTags")
}

model Tag {
  id        Int      @id @default(autoincrement())
  name      String   @unique
  posts     Post[]   @relation("PostTags")
}
  
src/prisma/schema.prisma

Prisma

/

Setup

    pnpm prisma db push
pnpm prisma generate
  
terminal
    DATABASE_URL=./data.db
  
.env

Prisma

/

Example

    import { PrismaClient } from '@prisma/client';
const prisma = new PrismaClient();

async function getPost(postId: number) {
  const post = await prisma.post.findUnique({
    where: { id: postId },
    include: { tags: true },
  });
  return post;
}

// Test it
getPost(1).then(console.log);
  
/src/app/post/[id]/page.tsx
  • Goal - Fetch a Post

Prisma

/

Example

    import { PrismaClient } from '@prisma/client';
const prisma = new PrismaClient();

async function getTechPosts() {
  const posts = await prisma.post.findMany({
    where: {
      tags: { some: { name: "tech" } },
      date: { gte: new Date("2025-01-01") },
    },
    include: { tags: true },
  });
  return posts;
}

// Test it
getTechPosts().then(console.log);
  
/src/app/posts/[tag]/page.tsx
  • Goal - Fetch Posts by Tag

Prisma

/

Mutations

    import { PrismaClient } from '@prisma/client';
const prisma = new PrismaClient();

async function addPost(title: string, content: string, tagNames: string[]) {
  const post = await prisma.post.create({
    data: {
      title,
      content,
      date: new Date(),
      tags: { connect: tagNames.map(name => ({ name })) },
    },
  });
  return post;
}

// Test it
addPost("My Tech Post", "Cool stuff!", ["tech", "news"]);
  
/src/app/posts/[tag]/page.tsx
  • Goal - Create a Post

Prisma

/

Accessing DB

    pnpm prisma studio
  
terminal
  • Prisma Studio
  • VS Code Plugin
  • Many ... many .... SWs

Prisma

/

Wrap Up

  • Simple and Type-Safe
  • Best Practices
  • Next Steps