Mahmoud
07/13/2021, 3:02 PMschema.prismamongodbmongoDbpreviewFeaturesgenerator// Set the database provider to "mongodb"
datasource db {
  provider = "mongodb"
  url      = env("DATABASE_URL")
}
// We want to generate a Prisma Client
// Since mongodb is a preview feature, we need to enable it.
generator client {
  provider        = "prisma-client-js"
  previewFeatures = ["mongoDb"]
}
// Create our Post model which will be mapped to a collection in the database.
// The id attributes tell Prisma it's a primary key and to generate 
// object ids by default when inserting posts.
model Post {
  id    String @id @default(dbgenerated()) @map("_id") @db.ObjectId
  slug  String @unique
  title String
  body  String
}.envMahmoud
07/27/2021, 10:57 AMMahmoud
08/10/2021, 5:12 PMinteractiveTransactionsgenerator client {
  provider        = "prisma-client-js"
  previewFeatures = ["interactiveTransactions"]
}namedConstraints@@unique@@indexnamedConstraintsnamedConstraintsgenerator client {
  provider        = "prisma-client-js"
  previewFeatures = ["namedConstraints"]
}prisma db pullMahmoud
08/24/2021, 4:54 PMfullTextSearchdatasource db {
  provider = "postgresql"
  url      = env("DATABASE_URL")
}
generator client {
  provider        = "prisma-client-js"
  previewFeatures = ["fullTextSearch"]
}searchString// returns all posts that contain the words cat *or* dog.
const result = await prisma.post.findMany({
  where: {
    body: {
      search: 'cat | dog',
    },
  },
})prisma introspectprisma db pullprisma introspectprisma db pullschema.prismaprisma db pullprisma introspectDaniel Norman
prisma db seedDaniel Norman
Daniel Norman
User:Post@relation()referentialIntegrity2.24.0planetScaleModereferentialIntegrityreferentialIntegrity = "prisma"prismareferentialIntegritydatasource db {
  provider             = "mysql"
  url                  = env("DATABASE_URL")
  referentialIntegrity = "prisma"
}
generator client {
  provider        = "prisma-client-js"
  previewFeatures = ["referentialIntegrity"]
}prismafullTextSearch// Fetch all drafts with a title that contains the words fox or dog
posts, _ := client.Post.FindMany(
  db.Post.Title.Search("fox | dog"),
  db.Post.Status.Equals("Draft"),
).Exec(context.Background())
// Loop over the posts and print the title
for _, post := range posts {
  fmt.Println(post.Title)
}nikolasburk
prisma db pullmongoDbdatasourceprisma db pullconst userWithPostsCount = await prisma.user.findMany({
  include: {
    _count: {
      select: { posts: true },
    },
  },
})
// => [
//      { 
//        email: "<mailto:alice@prisma.io|alice@prisma.io>",
//        _count: { posts: 3 }
//      }
//    ]nikolasburk
3.3.0import { PrismaClient } from '@prisma/client'
const prisma = new PrismaClient()
addEventListener('fetch', (event) => {
  event.respondWith(handleRequest(event.request))
})
async function handleRequest(request: Request): Promise<Response> {
  await prisma.log.create({
    data: {
      level: 'Info',
      message: `${request.method} ${request.url}`,
    },
  })
  return new Response(`request method: ${request.method}!`)
}2.16.0ts
// Return a list of posts ordered by the author's email address
// in ascending order.
await prisma.post.findMany({
  orderBy: {
    author: {
      email: "asc",
    },
  },
})3.3.0model User {
  id   Int      @id @default(autoincrement())
  name String
  pets String[]
}user, err := client.User.FindFirst(
  db.User.Pets.HasSome([]string{"Fido", "Scooby"}),
).Exec(ctx)user, err := client.User.FindUnique(
  db.User.Name.Equals(1),
).Update(
  db.User.Items.Push([]string{"Charlemagne"}),
).Exec(ctx)nikolasburk
3.4.03.4.0ORDER BYcityconst groupBy = await prisma.user.groupBy({
  by: ['city'],
  _count: {
    city: true,
  },
  orderBy: {
    _count: {
      city: 'desc',
    },
  },
})prisma db pushprisma db push@unique@@unique@@indexprisma db pushlogs, _ := client.Log.FindMany(
  db.Log.Meta.Path([]string{"service"}),
	db.Log.Meta.Equals(db.JSON("\"api\"")),
).Exec(ctx)nikolasburk
3.5.0searchwhereconst query = "node.js developer"
const developers = await prisma.people.findMany({
  where: {
    bio: {
      // Only select people whose bio's contain "node.js developer"
      search: query,
    },
  },
  orderBy: {
    // Order that selection by query relevance.
    _relevance: {
      fields: ["bio"],
      search: query,
      sort: "desc",
    },
  },
})sortlengthmodel Post {
    title       String @db.VarChar(300)
    abstract    String @db.VarChar(3000)
    slug        String @db.VarChar(3000) @unique(sort: Desc, length: 42)
    author      String
    created_at  DateTime
    @@id([title(length: 100, sort: Desc), abstract(length: 10)])
    @@index([author, created_at(sort: Desc)])
}users, err := client.User.FindMany(
    User.Email.Equals("prisMa"),
    User.Email.Mode(QueryModeInsensitive), // sets case insensitivity
).Exec(ctx)Alex Ruheni
db pull+db pushmigratefullTextIndex@@fulltextgenerator js {
  provider        = "prisma-client-js"
  previewFeatures = ["fullTextIndex"]
}
model A {
  id      Int    @id
  title   String @db.VarChar(255)
  content String @db.Text
  
  @@fulltext([title, content])
}db pullextendedIndexesHashBTreegenerator js {
  provider        = "prisma-client-js"
  previewFeatures = ["extendedIndexes"]
}
model A {
  id    Int @id
  value Int  
  
  @@index([value], type: Hash)
}3.6.0BytesinnotIninnotInBytesconst audioTracks = raws.map(raw => {
  return Buffer.from(raw)
})
const result = await prisma.audio.find({
  where: {
    track: 
      in: audioTracks
    }
  }
})JsonJsonauditJsonconst trail = [
  { event: "signup" },
  { event: "subscribe" },
  { event: "invite friend" }
] as const
await prisma.user.create({
  data: {
    audit: trail
  }
})Alex Ruheni
3.7.03.7.0onDeleteonUpdatemodel User {
   id    String @id @default(dbgenerated()) @map("_id") @db.ObjectId
   posts Post[]
   name  String
 }
 model Post {
   id     String @id @default(dbgenerated()) @map("_id") @db.ObjectId
   author User   @relation(fields: [userId], references: [id], *onDelete: Cascade*)
   title  String
   userId String @db.ObjectId
 }onDelete: CascadeonDeleteonUpdatemongodbError parsing attribute "@relation": Reference causes a cycle.type3.7.0typetype MyId = String @id @default(dbgenerated(new_uuid()))
model A {
  id MyId
}BigIntAlex Ruheni
3.8.0fullTextIndexfullTextSearch@@fulltext()generator client {
  provider        = "prisma-client-js"
  previewFeatures = ["fullTextIndex", "fullTextSearch"]
}
datasource db {
  provider = "mysql"
  url      = env("DATABASE_URL")
}
model Post {
  id     Int    @id @default(autoincrement())
  title  String @unique
  @@fulltext([title])
}prisma db pushprisma migrate dev// search for titles that contain cat, but not fox
await prisma.post.findMany({
  where: {
    title: {
      search: "+cat -fox",
    },
  },
})dataProxyinteractiveTransactions3.8.0push3.8.0pushmodel Course {
  id          String   @id @default(dbgenerated()) @map("_id") @db.ObjectId
  title       String
  students    String[] @db.Array(ObjectId)
}// Add a new student to the course
await prisma.course.update({
  where: {
    id: 1
  },
  data: {
    students: {
      push: new ObjectID("...")
    }
  }
})Alex Ruheni
3.9.0prisma migrate diffprisma db executeprisma migrate diffprisma migrate diffprisma db execute3.9.0// To find zero or more documents matching a filter
const result = await prisma.user.findRaw({
  filter: { age: { $gt: 25 } },
  options: { projection: { _id: false } },
})
// To perform aggregation operations on a collection
await prisma.user.aggregateRaw({
  pipeline: [
    { $match: { status: 'registered' } },
    { $group: { _id: '$country', total: { $sum: 1 } } },
  ],
})
// To run a command against the database
await prisma.$runCommandRaw({
  aggregate: 'User',
  pipeline: [
    { $match: { name: 'Bob' } },
    { $project: { email: true, _id: false } },
  ],
  explain: false,
})3.9.0Alex Ruheni
3.10.03.10.0typedatasource db {
  provider = "mongodb"
  url      = env("DATABASE_URL")
}
generator client {
  provider        = "prisma-client-js"
  previewFeatures = ["mongoDb"]
}
model Product {
  id     String  @id @default(auto()) @map("_id") @db.ObjectId
  name   String
  photos Photo[]
}
type Photo {
  height Int
  width  Int
  url    String
}photos// Create a new product with an embedded list of photos
const product = await prisma.product.create({
  data: {
    name: "Forest Runners",
    price: 59.99,
    // Create an embedded list of photos in the product
    photos: [
      { height: 100, width: 200, url: "1.jpg" },
      { height: 300, width: 400, url: "2.jpg" },
    ],
  },
})3.4.0prisma db pulltype-composite-type-depth=0--composite-type-depth=2@default(dbgenerated())@default(auto())dbgeneratedreferences3.10.0@relationfieldsreferencesfieldsreferencesmodel Post {
  id           String   @id @map("_id") @default(auto()) @db.ObjectId
  category_ids String[] @db.ObjectId
  categories   Category[]      @relation(fields: [category_ids], references: [id])
}
    
model Category {
  id       String   @id @map("_id") @default(auto()) @db.ObjectId
  post_ids String[] @db.ObjectId
  posts    Post[] @relation(fields: [post_ids], references: [id])
}db.Array(ObjectId)@db.ObjectIddbgeneratedAlex Ruheni
3.11.03.11.0model Product {
  id     String  @id @default(auto()) @map("_id") @db.ObjectId
  photos Photo[]
}
model Order {
  id              String   @id @default(auto()) @map("_id") @db.ObjectId
  shippingAddress Address
  billingAddress  Address? /// optionally embedded document
}
type Photo {
  height Int
  width  Int
  url    String
}
type Address {
  street String
  city   String
  zip    String
}// find all orders with the same shipping address
const orders = await prisma.order.findMany({
  where: {
    shipping: {
      equals: {
        street: "555 Candy Cane Lane",
        city: "Wonderland",
        zip: "52337",
      },  
    },
  },
})// find all products that don't have photos
const product = prisma.product.findMany({
  where: {
    photos: {
      isEmpty: true
    }
  },
})3.11.0// sort orders by zip code in ascending order
const orders = await prisma.order.findMany({
  orderBy: {
    shippingAddress: {
      zip: "asc",
    },
  },
})PrismaClientconst prisma = new PrismaClient({
  log: [
    {
      emit: 'event',
      level: 'query',
    },
  ]
})
prisma.$on('query', (e) => console.log(e.query))mongosh3.11.0Json3.11.0migrate diff3.11.0--exit-codemigrate diffMatt Mueller (Prisma Client PM)
3.11.1undefinedundefinedundefinedmodel Address {
    id     Int    @id @map("_id")
    city   String
    street String? // Note that street is optional
}nullundefined{ "_id": 1, "city": "San Fransisco", "street": "Market st." }
{ "_id": 2, "city": "Seattle", "street": null }
{ "_id": 3, "city": "Chicago" }3.11.1where: { street: null }_id: 2_id: 33.11.1_id: 2isSetisSetisSet: boolundefinedundefinedawait prisma.address.findMany({
  where: {
    OR: [
      { street: { isSet: false } },
      { street: null }
    ]
  }
})isSetunset3.11.1unsetawait prisma.address.update({
  where: {
    id: 10,
  },
  data: {
    street: {
      unset: true,
    },
  },
})streetundefinedupdateManymodel Product {
  id          Int  @id @map("_id")
  name        String  @unique
  photos      Photo[]
}
type Photo {
  height Int    @default(200)
  width  Int    @default(100)
  url    String
}url1.jpgconst product = prisma.product.update({
  where: {
    id: 10,
  },
  data: {
    photos: {
      updateMany: {
        where: {
          url: '1.jpg',
        },
        data: {
          url: '2.png',
        },
      },
    },
  },
})deleteManyupdateManyheightconst product = prisma.product.update({
  where: {
    id: 10,
  },
  data: {
    photos: {
      deleteMany: {
        where: {
          height: 100,
        },
      },
    },
  },
})Alex Ruheni
3.12.03.12.0datasource db {
   provider = "mongodb"
   url      = env("DATABASE_URL")
 }
generator client {
   provider        = "prisma-client-js"
-  previewFeatures = ["mongoDb"]
 }db pushtype Address {
  street String
  number Int
}
model User {
  id      Int     @id
  email   String
  address Address
  @@index([email, address.number])  /// normal index
  @@unique([email, address.street])  /// unique index
  @@fulltext([email, address.street]) /// full-text index
}Note: Prisma Client does not yet fully support this feature and will be rolled out in a future release๐ Improved connection pooling resiliency In
3.12.0Alex Ruheni
3.13.0migrate diffdb execute--preview-featureprisma migrate diffprisma db execute3.5.0extendedIndexesdatasource db {
  provider = "sqlserver"
  url      = env("DATABASE_URL")
}
generator client {
  provider        = "prisma-client-js"
  previewFeatures = ["extendedIndexes"]
}
model Post {
  id      Int     @default(autoincrement()) @id(clustered: false)
  title   String
  content String?
}prisma migrate devCREATE TABLE [Post] (
  id INT NOT NULL,
  [title] VARCHAR(255) NOT NULL,
  [content] NVARCHAR(1000),
  CONSTRAINT [Post_pkey] PRIMARY KEY NONCLUSTERED (id)
)extendedIndexesprisma db pull3.13.0Alex Ruheni
3.14.0npx prisma db pullGINGiSTSP-GiSTBRINtype@@indexdatasource db {
  provider = "postgresql"
  url      = env("DATABASE_URL")
}
generator client {
  provider        = "prisma-client-js"
  previewFeatures = ["extendedIndexes"]
}
model Post {
  id      Int     @id
  title   String
  content String?
  tags    Json?
  
  @@index([tags], type: Gin)
}CREATE TABLE "Post" (
    "id" INTEGER NOT NULL,
    "title" TEXT NOT NULL,
    "content" TEXT,
    "tags" JSONB,
    CONSTRAINT "Post_pkey" PRIMARY KEY ("id")
);
CREATE INDEX "Post_tags_idx" ON "Post" USING GIN ("tags");queryRawimprovedQueryRawgenerator client {
  provider        = "prisma-client-js"
  previewFeatures = ["improvedQueryRaw"]
}improvedQueryRawfindManyDateTimeDate,BytesBufferimprovedQueryRawimprovedQueryRawBigIntBytesDecimalawait prisma.$executeRaw`INSERT INTO "Table" ("bigint", "bytes", "decimal") VALUES (${BigInt("123")}, ${Buffer.from([1, 2, 3])}, ${Decimal("12.23")});`This improvement is available without the๐ Learn more in the release notes For more info and links to documentation, you can read the release notes. ๐ Help us spread the word about Prisma ๐ To help spread the word about Prisma, weโd very much appreciate it if you would star the repo ๐ And if youโre excited about the features in this weekโs release, then help us and share your excitement on Twitter. ๐ฐ Join us on Thursday for the โWhatโs new in Prismaโ livestream This week, @nikolasburk and @Sabin Adams will discuss the latest release and other news from the Prisma ecosystem in a this Thursday at 5 pm Berlin | 8 am San Francisco.Preview feature flag.improvedQueryRaw
Alex Ruheni
3.15.0--data-proxynpx prisma generate --data-proxy@prisma/client/edge@prisma/clientimport { PrismaClient } from '@prisma/client/edge'generator client {
  provider        = "prisma-client-js"
  previewFeatures = ["metrics"]
}import { PrismaClient } from '@prisma/client'
const prisma = new PrismaClient()
const metrics = await prisma.$metrics.json()
console.log(metrics)migrate resetMichelle Greer
Alex Ruheni
4.0.04.0.0extendedIndexesfilterJsonimprovedQueryRawmodel User {
  id             Int      @id @default(autoincrement())
  posts          Post[]
  favoriteColors String[] @default(["red", "blue", "green"])
}4.0.0@defaultfindUniqueOrThrowfindFirstOrThrowfindUniqueOrThrowfindUniqueRecordNotFoundfindFirstOrThrowfindFirstRecordNotFoundrejectOnNotFoundDbNullJsonNullAnyNulltypesqlitereferencesreferences@prisma/sdk@prisma/internalsschemaAlex Ruheni
4.1.0orderByNullsgenerator client {
  provider        = "prisma-client-js"
  previewFeatures = ["orderByNulls"]
}prisma generateawait prisma.post.findMany({
  orderBy: {
    updatedAt: { 
      sort: 'asc',
      nulls: 'last'
    },
  },
})Alex Ruheni
4.2.0interactiveTransactionsisolationLevelawait prisma.$transaction(
  async (prisma) => {
    // Your transaction...
  },
  {
    isolationLevel: Prisma.TransactionIsolationLevel.Serializable,
    maxWait: 5000,
    timeout: 10000,
  }
)prisma.$metrics()metrics()$queryRaw()$executeRaw()$queryRawUnsafe()$executeRawUnsafe()Alex Ruheni
4.3.0fieldReferencegenerator client {
  provider        = "prisma-client-js"
  previewFeatures = ["fieldReference"]
}
model Invoice {
  id     Int @id @default(autoincrement)
  paid   Int
  due    Int
}// Filter all invoices that haven't been paid yet
await prisma.invoice.findMany({
  where: {
    paid: {
      lt: prisma.invoice.fields.due // paid < due
    }
  }
})filteredRelationCount// Count all published user posts 
await prisma.user.findMany({
  select: {
    _count: {
      posts: { where: { published: true } },
    },
  },
})multiSchematracingtracingdatasourcegeneratormodelenumtype1.70janpio
4.4.0isolationLevel4.2.0prisma.$transaction([ ])await prisma.$transaction(
  [
    // sequential operations
    prisma.user.create({ data: {/** args */ } }),
    prisma.post.create({ data: {/** args  */ } })
  ],
  {
    isolationLevel: Prisma.TransactionIsolationLevel.Serializable
  }
)P2034PrismaClientKnownRequestErrorTasin Ishmam
10/18/2022, 6:03 PM4.5.0wherefindUniqueupdatedeletewhere4.5.0wheregenerator js {
  provider        = "prisma-client-js"
  previewFeatures = ["extendedWhereUnique"]
}generator client {
  provider        = "prisma-client-js"
  previewFeatures = ["postgresqlExtensions"]
}
datasource db {
  provider = "postgresql"
  url      = env("DATABASE_URL")
}extensionsdatasourcedatasource db {
  provider   = "postgresql"
  url        = env("DATABASE_URL")
  extensions = [hstore(schema: "myHstoreSchema"), pg_tgrm, postgis(version: "2.1")]
}datasourcerelationModedatasourcereferentialIntegrityrelationModereferentialIntegritygenerator js {
  provider        = "prisma-client-js"
  previewFeatures = ["referentialIntegrity"]
}datasource db {
  provider     = "mysql"
  url          = env("DATABASE_URL")
  relationMode = "prisma"
}NoActionrelationMode = "prisma"relationMode4.3.0Tasin Ishmam
10/20/2022, 2:30 PM