https://www.prisma.io/ logo
Join SlackCommunities
Powered by
# orm-help
  • d

    Dhananjay Takalkar

    03/28/2022, 7:29 AM
    Can I use upsert without unique column values ?
    n
    • 2
    • 2
  • m

    Martin Hoang

    03/28/2022, 7:58 AM
    Hello there, is there option to use prisma with
    utf8
    charset, prisma is using
    utf8mb4
    and I just can't change existing table to use
    utf8mb4
    n
    • 2
    • 1
  • d

    Dev__

    03/28/2022, 8:01 AM
    I have 2 tables,
    TemporaryData
    and
    Data
    . Is there an easy way to copy the rows from
    TemporaryData
    to the
    Data
    table? The model structure will be exactly the same
    n
    • 2
    • 1
  • e

    Eko Nur Arifin

    03/28/2022, 8:46 AM
    hi there, anyone of u implement soft delete without we need descript all at middleware like current ? Thanks all https://www.prisma.io/docs/concepts/components/prisma-client/middleware/soft-delete-middleware
    n
    • 2
    • 3
  • b

    Blue Nebula

    03/28/2022, 8:47 AM
    is it a common pattern to run:
    Copy code
    prisma.table.upsert({
      where:{...},
      update:data,
      create:data
    });
    to add something to a table with an unique column, overwriting the row with the same unique value if it already exists?
    n
    • 2
    • 3
  • l

    louis-sanna-eki

    03/28/2022, 9:08 AM
    My prisma client is typed as any. What am I missing?
    n
    • 2
    • 4
  • s

    s1w

    03/28/2022, 1:29 PM
    Hey folks - I’m having an issue trying to bundle Prisma into a NextJS project. When the project is running (and instantiating a prisma client) in an API route - I’m getting
    ENOENT: no such file or directory, open ../path/to/prisma.schema
    (replaced path). More details in thread.
    j
    • 2
    • 4
  • s

    superbunches

    03/28/2022, 4:34 PM
    The last few days I’ve been dealing with an error trying to add a new model to my schema, and I went through a very interesting troubleshooting process to find the solution. TL;DR - Either multiple Prisma clients or an extra node server running at
    localhost:3000
    was causing PrismaClient and my project to be out of sync. I’ll do my best to describe what happened in a thread 👇
    j
    • 2
    • 16
  • m

    Mykyta Machekhin

    03/28/2022, 6:01 PM
    Hi guys. I found out that data modify methods (
    .create, .update
    etc) are not work at all if I don’t use
    await
    ,
    .then
    or
    .catch
    on this methods. Can someone explain me why is it?
    a
    s
    n
    • 4
    • 7
  • a

    Andrew Knackstedt

    03/29/2022, 3:07 AM
    Hi, Is there any way to make Prisma work with MSSQL/SQL Server with the Azure AD Token flow instead of the username/password flow? We won't be able to use Prisma with our application unless we can use this authorization scheme. I looked through the code, and it seems this is not yet possible, but should be possible with a minor adjustment to the Prisma APIS (which would be a semver major change). https://github.com/prisma/prisma/issues/12562 I made said issue before realizing there was a Slack workspace
    n
    • 2
    • 4
  • c

    Chris Bitoy

    03/29/2022, 5:56 AM
    Hello, Trying to write nested data into my db following Prisma docs, but have been getting this error message (below) , and I don’t know how else to make it work. It is telling me that a sub category that I defined in the schema ‘sub’ is undefined. I was thinking I wouldn’t have to loop through the sub categories array in order to get the values that I wanted - can you shoot me syntax that can get me out of this snag? Error:
    Copy code
    Invalid `prisma.category.create()` invocation:
    
    {
      data: {
    +   name: String,
    ?   description?: String | null,
    ?   url?: String | null,
        subCategories: {
          createMany: {
            data: {
              '0': {
    +           name: String,
    ?           description?: String | null,
    ?           url?: String | null,
    ?           image?: String | null,
                sub: {
                ~~~
                  createMany: {
                    data: [
                      {
                        name: undefined,
                        description: undefined,
                        url: undefined,
                        image: undefined
                      }
                    ]
                  }
                },
    ?           id?: Int,
    ?           subId?: Int | null,
    ?           createdAt?: DateTime,
    ?           updatedAt?: DateTime
              }
            }
          }
        },
    ?   icon?: String | null,
    ?   bgColor?: String | null,
    ?   createdAt?: DateTime,
    ?   updatedAt?: DateTime
      }
    }
    
    Unknown arg `sub` in data.subCategories.createMany.data.0.sub for type SubcategoryCreateManyCategoryInput. Did you mean `subId`?
    Argument name for data.subCategories.createMany.data.0.name is missing.
    Argument name for data.name is missing.
    
    Note: Lines with + are required, lines with ? are optional.
    Schema:
    Copy code
    model Category {
          id            Int           @id @default(autoincrement())
          name          String        @db.VarChar(255)
          url           String?       @db.VarChar(255)
          icon          String?       @db.VarChar(255)
          description   String?       @db.VarChar(255)
          bgColor       String?       @db.VarChar(255)
          subCategories Subcategory[]
          createdAt     DateTime      @default(now())
          updatedAt     DateTime      @updatedAt
    }
    
    model Subcategory {
          id          Int       @id @default(autoincrement())
          name        String    @db.VarChar(255)
          description String?
          image       String?
          url         String?
          category    Category  @relation(fields: [categoryId], references: [id])
          sub         Sub[]
          categoryId  Int
          subId       Int?
          createdAt   DateTime  @default(now())
          updatedAt   DateTime  @updatedAt
          Program     Program[]
    }
    
    model Sub {
          id            Int          @id @default(autoincrement())
          name          String       @db.VarChar(255)
          description   String?
          image         String?
          url           String?
          createdAt     DateTime     @default(now())
          updatedAt     DateTime     @updatedAt
          categoryId    Int
          category      Subcategory? @relation(fields: [subcategoryId], references: [id])
          subcategoryId Int?
    }
    create file:
    Copy code
    import { PrismaClient } from '@prisma/client';
    import { data } from '../../../categoryData';
    
    const ArtData = async (req, res) => {
      const prisma = new PrismaClient({ log: ['query'] });
    
      try {
        const categoryData = req.body;
    
        await categoryData.map(async (category) => {
          const { name, description, url, subCategories } = category;
          const {
            subName = name,
            subDescription = description,
            subUrl = url,
            image,
            sub,
          } = subCategories;
    
          const categories = await prisma.category.create({
            data: {
              name,
              description,
              url,
              subCategories: {
                createMany: {
                  data: [
                    {
                      name: subName,
                      description: subDescription,
                      url: subUrl,
                      sub: {
                        createMany: {
                          data: [
                            {
                              //  name: innerName,
                            },
                          ],
                        },
                      },
                      image,
                    },
                  ],
                },
              },
            },
          });
        });
    
        res.status(201).json({ 'category: ': categoryData });
      } catch (error) {
        console.error(error);
        res.status(500);
        res.json({ error: 'something went wrong', error });
      } finally {
        await prisma.$disconnect();
      }
    };
    
    export default ArtData;
    n
    • 2
    • 2
  • l

    louis-sanna-eki

    03/29/2022, 6:25 AM
    I have a very strange bug: when I'm installing prisma
    Copy code
    npm install prisma --save-dev
    then generating from the prisma schema,
    Copy code
    npx prisma generate
    it breaks the typing of the pre-existing mongoose schema. If I look at the .lock I see no change that could explain it. Any guesses?
    n
    • 2
    • 3
  • l

    louis-sanna-eki

    03/29/2022, 6:26 AM
    n
    • 2
    • 2
  • j

    Jonathan

    03/29/2022, 8:07 AM
    Hi folks, more of a general question, how do you benchmark your Application in terms of database performance? Our team has a GraphQL application, and is undergoing severe performance issues. We want to have better observability in this, such as logging number of queries, finding inefficient queries, and the like. Any best practices or suggestion?
    👀 1
    👆 1
    t
    n
    • 3
    • 6
  • o

    Okan Yıldırım

    03/29/2022, 11:30 AM
    Hello friends, how can I generate types with prefix?
    👍 1
  • o

    Okan Yıldırım

    03/29/2022, 11:30 AM
    For example, instead of User, I want it to generate like IUser
    n
    • 2
    • 1
  • j

    Jason

    03/29/2022, 2:00 PM
    Hey all, I have a basic question to ask. What's the best way to loop through all rows in a table? Let's say the table has ~3m rows. I need to perform some action for every row. Do I need to sort the table when performing findMany or will prisma use some implicit ordering by default?
    a
    n
    • 3
    • 3
  • m

    Mischa

    03/29/2022, 2:13 PM
    Has anyone been able to instrument prisma queries with AWS X-ray? Wondering if there's a place to hook in to queries to add timing (and ideally query being executed metadata) to x-ray segments Here's someone doing it for TypeORM as an example
    n
    • 2
    • 5
  • s

    shahrukh ahmed

    03/29/2022, 2:20 PM
    When having a one to one field, is there a way I can ensure that both models have the same primary key or id.
    n
    • 2
    • 3
  • t

    Topi Pihko

    03/29/2022, 2:49 PM
    I'm trying to add Middleware to Prisma for multitenancy / row level security, which sets auth.principle in a transaction before actual query is ran. Auth.principle is used in DB-level in RLS-policy. Concept works if I create own method to prisma.service, but usability would be nicer if this could be done in a middleware with $use-notation or something similar. Any suggestions? Working solution with bad usability:
    Copy code
    Prisma.service:
      async auth(func: any): Promise<any> {
    
        [ignore, result] = await this.$transaction([
          this.$executeRaw`SET local "auth.principal" = "1234567890"`,
          func,
        ]);
        return result;
      }
    
    
    Usage:
    async getUsers(): Promise<User[]>{
        return this.prisma.auth(this.prisma.user.findMany());
    }
    Tryout with $use, but queries are not run inside the same transaction -> auth.principal is not set when actual query is ran resulting empty array.
    Copy code
    Prisma.service:
        this.$use(async (params, next) => {
          // Set auth variable in a transaction
          const setTransActionResult = await next({
            args: {
              query: 'SET local "auth.principal" = "1234567890"',
              parameters: {
                values: '[]',
                __prismaRawParamaters__: true,
              },
            },
            dataPath: [],
            runInTransaction: true,
            action: 'executeRaw',
            model: undefined,
          });
    
          params.runInTransaction = true;
          // Run original query here
          return await next(params);
        });
    
    Usage: 
    
    async getUsers(): Promise<User[]>{
        return this.prisma.user.findMany();
    }
    👀 1
    n
    • 2
    • 5
  • t

    Tobias Lins

    03/29/2022, 2:57 PM
    Is there a way to type objects that are from type
    Json
    I really want to have a typescript type but it should be stored in the database column as json. I can't find any issue for that - should I create one or is there a solution for that?
    r
    a
    • 3
    • 3
  • y

    Yaakov

    03/29/2022, 3:25 PM
    Is there a way to use
    skipDuplicates
    with SQL Server?
    n
    • 2
    • 14
  • r

    Richard

    03/29/2022, 3:49 PM
    alphabet yellow question Is it possible in Prisma to handle
    connectOrCreate
    and
    disconnect
    in a single query when updating many:many relations?
    n
    • 2
    • 7
  • y

    Yaakov

    03/29/2022, 4:11 PM
    Is it possible to
    upsertMany
    ?
    a
    n
    • 3
    • 3
  • j

    Johny Velho

    03/29/2022, 5:08 PM
    Hey folks! I am using prisma with mongodb and I am facing a problem I am not sure if I am missing something or it's really a bug. could you help me? When using composite types, I can't update the embedded type by filtering it as mentioned in the documentation: Composite types | Prisma Docs. I only have access to set & push properties, not updateMany. Am I missing something or it's really a bug? prisma version: 3.11.0
    ✅ 1
    n
    • 2
    • 4
  • d

    Daan Helsloot

    03/30/2022, 3:39 AM
    Hi guys quick question, how much more performant is a
    findUnique
    call compared to a
    findFirst
    call? Is there any difference and if so, how big is it?
    c
    n
    j
    • 4
    • 7
  • u

    user

    03/30/2022, 9:30 AM
    Fullstack App With TypeScript, PostgreSQL, Next.js, Prisma &amp; GraphQL: Image upload This article is the fourth part of the course where you build a fullstack app with Next.js, GraphQL, TypeScript, Prisma and PostgreSQL. In this article, you will learn how to add image upload using AWS S3.
    🎉 1
    🙌 2
    💯 1
    prisma rainbow 2
  • j

    Javed Iqbal

    03/30/2022, 9:48 AM
    👋 Hello, team!
    👋 2
  • o

    Orcioly Andrade Alves

    03/30/2022, 12:52 PM
    Good morning guys.. blz? What do you think of this procedure? Using select was a way I found to omit the password in the client-side return. In Prisma Studio when I click on the Product within the Model OrderClient it shows the product, but when I click on the field in name Client it shows in the field name the Model User because the Model Client is related to the User. Is correct? Remembering that in Insomnia it shows right. I had a look at the prism connect option, but I managed to solve it this way. What do you think? Apparently it's working as expected, but I'd like opinions! Thank you very much in advance. schema.prisma:
    Copy code
    generator client {
      provider = "prisma-client-js"
    }
    
    datasource db {
      provider = "postgresql"
      url      = env("DATABASE_URL")
    }
    
    model User {
      id         String   @id @default(uuid())
      name       String
      email      String   @unique
      password   String
      isAdmin    Boolean  @default(false)
      created_at DateTime @default(now())
      updated_at DateTime @updatedAt
    
      Client Client[]
      @@map("users")
    }
    
    model Client {
      id              String   @id @default(uuid())
      user_id         String
      name            User     @relation(fields: [user_id], references: [id])
      address         String
      city            String
      district        String
      state           String
      zipcode         String
      cnpj            String   @unique
      stateregistered String
      telephone       String
      mobile          String
      active          Boolean
      created_at      DateTime @default(now())
      updated_at      DateTime @updatedAt
    
      Order OrderClient[]
      @@map("clients")
    }
    
    model Product {
      id           String   @id @default(uuid())
      followUp     String
      fabric       String?
      name         String
      size         String
      color        String
      status       String
      code_karsten String
      price        Decimal  @default(0.00)
      isActive     Boolean
      created_at   DateTime @default(now())
      updated_at   DateTime @updatedAt
    
      Order OrderClient[]
      @@map("products")
    }
    
    model OrderClient {
      id           String   @id @default(uuid())
      name         Client   @relation(fields: [client_id], references: [id])
      client_id    String
      product      Product  @relation(fields: [product_id], references: [id])
      product_id   String
      quantity     Int
      size         String
      color        String
      status       String
      code_karsten String
      price        Decimal  @default(0.00)
      liquid       Decimal  @default(0.00)
      priceTotal   Decimal  @default(0.00)
      created_at   DateTime @default(now())
      updated_at   DateTime @updatedAt
    
      @@map("orders_clients")
    }
    CreateOrderClientService.ts:
    Copy code
    import { AppError } from '../shared/errors/AppError';
    import prismaClient from '../prisma';
    import { CreateOrderClientDTO } from '../dtos/order_client/CreateOrderClientDto';
    
    class CreateOrderClientService {
      async execute({
        client_id,
        product_id,
        quantity,
        size,
        color,
        status,
        code_karsten,
        price,
        liquid,
        priceTotal,
      }: CreateOrderClientDTO) {
        const order = await prismaClient.orderClient.create({
          data: {
            client_id,
            product_id,
            quantity,
            size,
            color,
            status,
            code_karsten,
            price,
            liquid,
            priceTotal,
          },
          include: {
            name: {
              select: {
                name: {
                  select: {
                    id: true,
                    name: true,
                    email: true,
                    isAdmin: true,
                    created_at: true,
                    updated_at: true,
                  },
                },
              },
            },
            product: true,
          },
        });
    
        return order;
      }
    }
    
    export { CreateOrderClientService };
    v
    n
    • 3
    • 6
  • a

    Alex Service

    03/30/2022, 2:28 PM
    Hey folks! I’m exploring the Json type as well and was wondering what’s an appropriate way to access nested objects; all of the examples I see in the documentation are about accessing arrays and my queries in the playground are all very slow (4 seconds versus 60ms in postgres) e.g. let’s say we have a record like this:
    Copy code
    {
      "data": {
        "field_one": {
          "field_two": "hello"
        }
      }
    }
    In postgres, I could quickly find records matching on field_two’s value like so:
    Copy code
    SELECT doc_col FROM "MyTable" WHERE doc_col @> '{"data": {"field_one": {"field_two": "hello"}}}'
    I have my table created in
    schema.prisma
    with doc_col set as Json and enabled prisma’s “filterJson” previewFeature. I wrote the following graphql query, which takes 4 seconds:
    Copy code
    query { myTables(where: {doc_col: {path: ["data", "field_one", "field_two"], equals: "0004"}}) }
    n
    • 2
    • 3
1...558559560...637Latest