{"id":22688245,"url":"https://github.com/emanuelefavero/prisma","last_synced_at":"2026-04-20T09:32:41.800Z","repository":{"id":69318142,"uuid":"596935953","full_name":"emanuelefavero/prisma","owner":"emanuelefavero","description":"A cheat sheet repository of prisma ORM","archived":false,"fork":false,"pushed_at":"2023-09-29T19:24:20.000Z","size":55,"stargazers_count":91,"open_issues_count":0,"forks_count":9,"subscribers_count":3,"default_branch":"main","last_synced_at":"2025-03-29T16:13:18.164Z","etag":null,"topics":["database","db","orm","prisma","prisma-orm","supabase","typescript"],"latest_commit_sha":null,"homepage":"","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/emanuelefavero.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE.md","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2023-02-03T08:57:59.000Z","updated_at":"2025-03-08T10:46:03.000Z","dependencies_parsed_at":"2025-02-04T16:45:16.394Z","dependency_job_id":"6ab25673-e48e-4dac-b37e-4f84c47e25d6","html_url":"https://github.com/emanuelefavero/prisma","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/emanuelefavero/prisma","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/emanuelefavero%2Fprisma","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/emanuelefavero%2Fprisma/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/emanuelefavero%2Fprisma/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/emanuelefavero%2Fprisma/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/emanuelefavero","download_url":"https://codeload.github.com/emanuelefavero/prisma/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/emanuelefavero%2Fprisma/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":32041352,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-04-20T00:18:06.643Z","status":"online","status_checked_at":"2026-04-20T02:00:06.527Z","response_time":94,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["database","db","orm","prisma","prisma-orm","supabase","typescript"],"created_at":"2024-12-10T00:13:36.326Z","updated_at":"2026-04-20T09:32:41.776Z","avatar_url":"https://github.com/emanuelefavero.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Prisma\n\nThis is a cheat sheet repo for the [Prisma](https://www.prisma.io/) database [ORM](https://en.wikipedia.org/wiki/Object%E2%80%93relational_mapping?useskin=vector).\nPrisma is a database toolkit that makes it easy to query, migrate and model your database\n\n\u003e Prisma can use any database, but this cheat sheet is focused on PostgreSQL (_Note: Very little would change with a different database, that's the magic of Prisma_)\n\n## Table of Contents\n\n- [Prisma](#prisma)\n  - [Table of Contents](#table-of-contents)\n  - [Installation](#installation)\n    - [Initialize Prisma](#initialize-prisma)\n  - [Setup a Database](#setup-a-database)\n    - [IF you already have data in your database](#if-you-already-have-data-in-your-database)\n    - [\\*Prisma VS Code Extension](#prisma-vs-code-extension)\n  - [Define your Database Schema](#define-your-database-schema)\n  - [Initialize your database](#initialize-your-database)\n  - [Install Prisma Client](#install-prisma-client)\n  - [Use Prisma Client](#use-prisma-client)\n  - [Schema **Models**](#schema-models)\n    - [Enums](#enums)\n  - [**CRUD** Operations](#crud-operations)\n    - [CREATE](#create)\n    - [UPDATE](#update)\n    - [CONNECT, DISCONNECT, SET](#connect-disconnect-set)\n    - [DELETE](#delete)\n    - [READ](#read)\n  - [**FILTERS**](#filters)\n  - [Resources](#resources)\n  - [License](#license)\n\n## Installation\n\n- setup a new project with `npm init -y`\n- install Prisma and needed dev dependencies with `npm i -D prisma @prisma/client`\n\n\u003e Note: For a Typescript project, you'll need to install `typescript` and `ts-node` as well as well as any other dev dependencies you need for your project (such as `@types/node` for a Node project)\n\u003e\n\u003e It is also recommended to install `nodemon` for development\n\n- Full Command for a Node Typescript Project\n\n```bash\nnpm i -D prisma typescript ts-node @types/node nodemon\n```\n\n- create a `tsconfig.json` file:\n\n```json\n{\n  \"compilerOptions\": {\n    \"sourceMap\": true,\n    \"outDir\": \"dist\",\n    \"strict\": true,\n    \"lib\": [\"esnext\"],\n    \"esModuleInterop\": true\n  }\n}\n```\n\n### Initialize Prisma\n\n- this will create a `prisma` folder with a `schema.prisma` file\n\n```bash\nnpx prisma init --datasource-provider postgresql\n```\n\n\u003e _--datasource-provider is optional and will default to `postgresql`_\n\n## Setup a Database\n\n- Setup any database you want to use with Prisma and get the connection string\n\n\u003e Note: I've created a new database with [Supabase](https://supabase.com/) which is a firebase-like database service that uses PostgreSQL\n\u003e\n\u003e - Create a new database with [Supabase](https://supabase.com/)\n\u003e\n\u003e - Go to `Project Settings` / `Database` / `Connection string` / `URI` and copy the `URI` string\n\n- Add your database connection URI string to `.env`\n\n```bash\nDATABASE_URL=\"postgresql://USER:PASSWORD@HOST:PORT/DATABASE?schema=SCHEMA\"\n```\n\n\u003e Note: After 2023, you probably need to copy/paste another DATABASE_URL from supabase\n\n#### IF you already have data in your database\n\n- run `npx db pull` if you already have data in your database and you want to generate the Prisma schema\n\n- add your schema in `schema.prisma`\n\n### \\*Prisma VS Code Extension\n\nInstall the [prisma vs-code extension](https://marketplace.visualstudio.com/items?itemName=Prisma.prisma) for syntax highlighting and more\n\nAdd the following to your `settings.json` file to enable this extension for `.prisma` files:\n\n```json\n\"[prisma]\": {\n  \"editor.defaultFormatter\": \"Prisma.prisma\"\n}\n```\n\n## Define your Database Schema\n\n- Define your database models\n\n```prisma\nmodel User {\nid String @id @default(uuid())\nname String\n}\n\n```\n\n\u003e Note: uuid is of type String, autoincrement is of type Int\n\n## Initialize your database\n\n\u003e **Remember to run this command after any changes to your schema**\n\n```bash\nnpx prisma migrate dev\n```\n\n\u003e if prisma complains, run this command: `npx prisma migrate dev --name init`\n\n## Install Prisma Client\n\n```bash\nnpm i @prisma/client\n```\n\n\u003e When you install Prisma Client, it automatically generates a client for your defined models, if you need to regenerate the client, run `npx prisma generate`\n\n## Use Prisma Client\n\n- create a `prisma.ts` or any file you want to use Prisma in\n\n- import the client\n\n```ts\nimport { PrismaClient } from '@prisma/client'\n```\n\n- create a new instance of the client\n\n```ts\nconst prisma = new PrismaClient()\n```\n\n\u003e Note: Tell prisma to log all database queries\n\u003e **Useful WHEN debugging**\n\n```ts\nconst prisma = new PrismaClient({\n  log: ['query', 'info', 'warn'],\n})\n```\n\n- use the client to query your database\n\n```ts\nasync function main() {\n  const allUsers = await prisma.user.findMany()\n  console.log(allUsers)\n  // ... WRITE HERE ALL YOUR QUERIES\n}\nmain()\n  .catch((e) =\u003e {\n    throw e\n  })\n  .finally(async () =\u003e {\n    await prisma.$disconnect()\n  })\n```\n\n\u003e Note: Check the example project in this repo for prisma client and schema models examples\n\n## Schema **Models**\n\n- `schema.prisma` file\n\n```prisma\nmodel User {\nid String @id @default(uuid()) // @id sets the primary key\n// id Int @id @default(autoincrement())\nemail String @unique // @unique sets the field as unique\nname String? // ? optional\ncreatedAt DateTime @default(now()) // * default value (now)\nupdatedAt DateTime @updatedAt // * auto update this field on update\n\nposts Post[] // * one user to many posts relation\n\n// ? BLOCK LEVEL ATTRIBUTE\n@@unique([age, name]) // now we cannot have two users with the same age and name\n@@index([email]) // index this field for faster queries when filtering and sorting\n}\n\nmodel Post {\nid String @id @default(uuid())\ntitle String\ncontent String?\npublished Boolean @default(false)\ncreatedAt DateTime @default(now())\nupdatedAt DateTime @updatedAt\n\n// * one user to many posts relation\nauthor User @relation(fields: [authorId], references: [id])\nauthorId String\n}\n\n```\n\n\u003e Note: uuid is of type String, autoincrement is of type Int\n\n### Enums\n\n- define a custom enum type in your schema\n\n```prisma\nenum Role {\n  USER\n  ADMIN\n}\n\nmodel User {\n  id String @id @default(uuid())\n  role Role @default(USER)\n}\n```\n\n\u003e Note: Enums are useful for determining the role of a user, or the status of a post (draft, published, etc...)\n\n## **CRUD** Operations\n\n### CREATE\n\n```ts\n// * CREATE\nconst createUser = await prisma.user.create({\n  data: {\n    name: 'Pam',\n    email: 'pam@paper.com',\n    age: 26,\n\n    // * Create a userPreference object at the same time. (relation)\n    userPreference: {\n      create: {\n        emailUpdates: true,\n      },\n    },\n  },\n\n  // * Include the userPreference object in the response\n  // include: {\n  //   userPreference: true,\n  // },\n\n  // * Only show the name and the id of userPreference in the response\n  select: {\n    name: true,\n    userPreference: { select: { id: true } },\n  },\n})\n\nconst createUsers = await prisma.user.createMany({\n  data: [\n    {\n      name: 'Michael',\n      email: 'michael@paper.com',\n      age: 41,\n    },\n    {\n      name: 'Dwight',\n      email: 'dwight@paper.com',\n      age: 35,\n    },\n  ],\n\n  // ? You can't use include or select with createMany\n})\n```\n\n### UPDATE\n\n```ts\n// * UPDATE\n// Update One\nconst updateOne = await prisma.user.update({\n  where: {\n    email: 'michael@paper.com',\n  },\n\n  data: {\n    age: {\n      increment: 1, // ? increment, decrement, multiply, divide, append, prepend, delete, remove, disconnect, connect, set\n    },\n  },\n})\n\n// Update Many\nconst updateMany = await prisma.user.updateMany({\n  where: {\n    age: { gt: 40 },\n  },\n\n  data: {\n    email: '...@paper.com',\n  },\n})\n```\n\n### CONNECT, DISCONNECT, SET\n\n```ts\n// * CONNECT, DISCONNECT, SET\nconst connect = await prisma.user.update({\n  where: {\n    email: 'pam@paper.com',\n  },\n\n  data: {\n    userPreference: {\n      connect: {\n        id: '9c7c2634-5cab-428d-8ca8-0db26bc3c684', // ? userPreferenceId from pam\n      },\n    },\n  },\n})\n\nconst disconnect = await prisma.user.update({\n  where: {\n    email: 'pam@paper.com',\n  },\n\n  data: {\n    userPreference: {\n      disconnect: true, // ? now pam's userPreference is null\n    },\n  },\n})\n```\n\n### DELETE\n\n```ts\n// * DELETE\n// * delete all\nconst deleteAll = await prisma.user.deleteMany()\n\n// * delete many that match a condition\nconst deleteAllUsersAged40Plus = await prisma.user.deleteMany({\n  where: {\n    age: { gt: 40 },\n  },\n})\n\n// * delete one\n// You need a unique identifier to delete one (you can setup a unique identifier in the schema.prisma file by adding @unique to the field)\nconst deleteOne = await prisma.user.delete({\n  where: {\n    email: 'pam@paper.com',\n  },\n})\n```\n\n### READ\n\n```ts\n// * READ\n// * find all users\nconst findUsers = await prisma.user.findMany()\n\n// * find one user by an unique field (email)\nconst findUser = await prisma.user.findUnique({\n  where: {\n    email: 'pam@paper.com',\n  },\n})\n\n// * find user by multiple unique fields that we specified\n// ? @@unique([age, name])\nconst findUserByMultipleUniqueFields = await prisma.user.findUnique({\n  where: {\n    age_name: {\n      age: 26,\n      name: 'Pam',\n    },\n  },\n})\n\n// * find users, sort and limit results\nconst findSortAndLimitResults = await prisma.user.findMany({\n  take: 2, // limit\n  skip: 1, // skip\n  orderBy: {\n    age: 'desc', // sort\n  },\n})\n\n// ? findFirst - find a user by any field that is not unique\n// ? distinct - return only distinct results (only first occurence of each result with a particular field)\n```\n\n## **FILTERS**\n\n```ts\n// * FILTERS\n// * not\nconst notFilter = await prisma.user.findMany({\n  where: {\n    name: { not: 'Pam' },\n  },\n})\n\n// * in, notIn\nconst inFilter = await prisma.user.findMany({\n  where: {\n    name: { in: ['Pam', 'Dwight'] },\n  },\n})\n\n// * lt, lte, gt, gte\nconst ltFilter = await prisma.user.findMany({\n  where: {\n    age: { lt: 30 },\n  },\n})\n\n// * contains, startsWith, endsWith\nconst containsFilter = await prisma.user.findMany({\n  where: {\n    name: { contains: 'a' },\n  },\n})\n\n// * AND, OR, NOT\nconst andFilter = await prisma.user.findMany({\n  where: {\n    AND: [{ name: 'Pam' }, { age: { lt: 30 } }],\n  },\n})\n\n// ARRAY FILTERING\n// * some, none, every\n// ! hypothetical example\n// const someFilter = await prisma.user.findMany({\n//   where: {\n//     posts: {\n//       some: {\n//         title: 'Hello World',\n//       },\n//     },\n//   },\n// })\n```\n\n## Resources\n\n- [Prisma Docs](https://www.prisma.io/docs/)\n- [Prisma Quick Start](https://www.prisma.io/)\n- [Prisma Playground](https://playground.prisma.io/)\n\n## License\n\n- [MIT](LICENSE.md)\n\n\u0026nbsp;\n\n---\n\n\u0026nbsp;\n\n[**Go To Top \u0026nbsp; ⬆️**](#prisma)\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Femanuelefavero%2Fprisma","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Femanuelefavero%2Fprisma","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Femanuelefavero%2Fprisma/lists"}