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

    Theo Browne

    05/30/2022, 8:36 PM
    Is there any guidance around using variables within
    select
    and
    include
    ? Seems like it breaks type inference pretty hard. Cut an issue about it here: https://github.com/prisma/prisma/issues/13571
    👀 1
    n
    • 2
    • 1
  • u

    Ulises Viña

    05/30/2022, 9:05 PM
    Hello, I'm trying to create a following/followers system by using a many-to-many relation, everything is fine with the schema side, but on the client I'm getting an error when connecting a new ID to the following value of a user. The error is the following:
    Copy code
    Unknown arg `id` in data.following.connect.id for type FollowsWhereUniqueInput. Available args:
    
    type FollowsWhereUniqueInput {
      followerId_followingId?: FollowsFollowerIdFollowingIdCompoundUniqueInput
    }
    EDIT: I did try to use the followerId_followingId argument in the connect object, but when using it, a different error appears saying it expected type FollowsFollowerIdFollowingIdCompoundUniqueInput but received String.
    👀 1
    n
    s
    • 3
    • 4
  • h

    hoe

    05/31/2022, 1:44 AM
    hi, everyone, I want to use vitest to test mock prisma api. Prisma’s official test case uses jest. How can I use vitest to implement this test? this is prisma unit test page: https://www.prisma.io/docs/guides/testing/unit-testing test uses vitest-mock-extended here my test code, mock not work and no error! import { PrismaClient } from ‘@prisma/client’; import { mockDeep, mockReset } from ‘vitest-mock-extended’; import { type DeepMockProxy } from ‘vitest-mock-extended/lib/Mock’; import prisma from ‘./client’; vi.mock(‘./client’, () => ({ __esModule: true, default: mockDeep(), })); // beforeEach(() => { // mockReset(prismaMock); // }); export const prismaMock = prisma as unknown as DeepMockProxy; it(‘test prisma’, async () => { const user = { id: 1, user_id: 1, created_time: new Date(), updated_time: new Date(), }; prismaMock.payingUser.create.mockResolvedValue(user); const res = prismaMock.payingUser.findMany(); console.log(res); });
    👏 1
    👀 1
    n
    d
    • 3
    • 2
  • p

    PHANTOM KNIGHT

    05/31/2022, 9:05 AM
    Hi People, I need a help This is my schema
    Copy code
    generator client {
      provider = "prisma-client-js"
    }
    
    datasource db {
      provider = "postgresql"
      url      = env("DATABASE_URL")
    }
    model Organisation {
      id             Int           @id @default(autoincrement())
      name           String        @unique
      slogan         String
      logoUrl        String?
      organisationId String        @unique
      juniorAdmins   JuniorAdmin[]
    }
    
    model JuniorAdmin {
      id           Int           @id @default(autoincrement())
      name         String
      number       BigInt
      photoUrl     String?
      password     String
      email        String
      Organisation Organisation? @relation(fields: [id], references: [id])
    }
    This is working fine when I add the first entry but when I add more of them I get this error
    👀 1
    n
    • 2
    • 1
  • p

    PHANTOM KNIGHT

    05/31/2022, 9:07 AM
  • b

    Brothak

    05/31/2022, 9:08 AM
    Why is there such a huge difference between duration of a query logged by prisma and results of explain analyze of them same query. Plan:
    Copy code
    Planning Time: 2.072 ms
    Execution Time: 186.830 ms
    ✅ 1
    n
    • 2
    • 6
  • b

    Brothak

    05/31/2022, 9:08 AM
    but the query in prisma took took 32441 ms
  • b

    Brothak

    05/31/2022, 9:08 AM
    it can’t be network latency, because although the server and client / app are on different places they are not that far away
  • t

    Teerapat

    05/31/2022, 10:08 AM
    Hey Guys! Need help about how to connect GCP Cloud SQL with the unix socket. Here is my
    DATABASE_URL
    Copy code
    DATABASE_URL="<mysql://MY_USER:MY_PASSWORD@localhost/MY_DB?socket=/cloudsql/inbound-BLAH-BLAH-BLAH>"
    But I got error as picture below. Any suggestion?
    ✅ 1
    n
    • 2
    • 2
  • b

    Berian Chaiwa

    05/31/2022, 11:46 AM
    Hello here. How do you all solve over-fetching with prisma/graphql. I have a graphql
    province
    query that might include
    districts
    or not, depending on whether we requested for it. But my
    Prisma
    query for the resolver always includes it in the result, regardless of whether the user wants it or not. Isn't this overfetching?:
    Query.ts
    Copy code
    function province(_: any, args: any, context: any) {
      return context.prisma.province.findUnique({
        include: {districts: true},
        where: {
          id: args.id,
        },
      });
    }
    graphql.schema
    Copy code
    type Query {
      province(id: ID!): Province!
    }
    type Province {
      id: ID!
      code: String!
      name: String!
      country_id: String
      country: Country
      districts: [District!]!
      created_at: String!
      created_by: String!
      last_modified_at: String!
      last_modified_by: String!
    }
    
    type District {
      id: ID!
      name: String!
      code: String!
      province_id: String!
      province: Province!
      created_at: String!
      created_by: String!
      last_modified_at: String!
      last_modified_by: String!
    }
    GraphQL Query that needs districts
    Copy code
    query Query($provinceId: ID!){
      province(id: $provinceId) {
        code
        name
        districts {
          code
          name
        }
      }
    }
    GraphQL Query that does not need districts but still hits the same resolver
    (Prisma loads districts that are not needed by the client) How can I solve this?
    Copy code
    query Query($provinceId: ID!){
      province(id: $provinceId) {
        code
        name
      }
    }
    ✅ 1
    n
    o
    • 3
    • 9
  • m

    Michael Roberts

    05/31/2022, 1:46 PM
    Hey all, does anyone have any good guides as to how we can test prisma endpoints?
    👀 1
    n
    • 2
    • 2
  • g

    Ge Yang

    05/31/2022, 1:57 PM
    HI All, I am looking for a way to extend a MongoDB list with a few items. Currently the prisma-client does not allow this, does anyone know how to do this with the
    $runCommand
    escape hatch? In Mongo I can write a query that looks like the following:
    Copy code
    db.students.update(
       { name: "joe" },
       { $push: { scores: { $each: [ 90, 92, 85 ] } } }
    )
    and this will give me the following object:
    Copy code
    students: {
       name: "joe",
       scores: [100, 99,  90, 92, 85 ]
    }
    What I Have Tried First of all, iterating through the list items item-by-item is infeasible for our application. The example here is simple, but the list items in our application is larger. So I tried to use
    $runCommandRaw
    Copy code
    let rawQuery = {
              insert: "Student",
              bypassDocumentValidation: false,
              documents: [
                text
                  ? {text, deltas}
                  : {scores: {$push: {$each: deltas}}}
              ]
            }
    
          }
      newText = await context.prisma.$runCommandRaw(rawQuery)
    How do I do this with Prisma-js? @Nurul @janpio
    ✅ 1
    j
    n
    • 3
    • 9
  • h

    Harsh Singh

    05/31/2022, 11:21 PM
    Hey -- I was building an integration for Prisma which allowed people to compile multiple Prisma files into a single Prisma file. Is there an integration for this which exists already?
    ✅ 1
    a
    n
    n
    • 4
    • 3
  • s

    Siddharth Sharma

    06/01/2022, 12:56 AM
    Hey everyone, does anyone have an example of adding a property on a type which is an array of objects? Been stuck on this for a while, i essentially have a computed field which is a nested property.. My code looks like the following.
    Copy code
    const posts = await db.post.findMany({
            ...paginateArgs,
            where: {
              galleryId: galleryId,
            },
            include: { images: true },
            orderBy,
          })
    posts array has many posts (obviously) and the post essentially has a child array called
    images
    . I’d like to add a computed field called
    url
    to this
    images array
    , and retain type safety on this. I debated adding URL to the DB as a dummy field but that doesnt really sound correct to me. I’m sure im over complicating things, so im curious what the best route to do this is.
    ✅ 1
    • 1
    • 1
  • c

    Chris Tsongas

    06/01/2022, 1:06 AM
    I decided to not use computed fields until they are supported by Prisma, for this exact reason...it's a type safety nightmare. I'd recommend adding the
    url
    field but computing the value beforehand using JS whenever you do an insert or update. You could write a helper function to do that so it's sure to be consistent.
    👍 1
    s
    n
    • 3
    • 3
  • j

    Jonas

    06/01/2022, 9:21 AM
    I have a model with an optional field and want to call
    findMany()
    and return only results where that field has a value. What do I need to do for that?
    👀 1
    t
    n
    • 3
    • 11
  • m

    Manish

    06/01/2022, 11:00 AM
    Hi, In my model I have a field:
    Copy code
    trial_ends_on   DateTime?
    I want to set the default value of this to be 14 days from today. If I was setting it to now, I would add it as follows:
    Copy code
    trial_ends_on   DateTime?   @default(now())
    However, instead of now, I actually want to add a date which is 14 days from now. How can I do this with default value?
    ✅ 1
    n
    • 2
    • 2
  • b

    Berian Chaiwa

    06/01/2022, 12:14 PM
    Hello here. I am trying to figure out if I can use
    findUnique
    with multiple args and only enable
    case insensitive
    on some of them. I have tried the below but I am getting the error as :
    Copy code
    "Argument code: Got invalid value ",
                "{",
                "  equals: 'ZM',",
                "  mode: 'insensitive'",
                "}",
                "on prisma.findUniqueCountry. Provided Json, expected String.",
    And my query looks like:
    Copy code
    country: (_parent: unknown, args, context) => {
          return context.prisma.country.findUnique({
            where: {
              id: args.id || undefined,
              code:
                args.code ? {
                  equals: args.code,
                  mode: "insensitive",
                } : undefined,
              name:
                args.name ? {
                  equals: args.name,
                  mode: "insensitive",
                } : undefined,
            },
          });
        },
    r
    • 2
    • 3
  • f

    foreverjunior

    06/01/2022, 2:16 PM
    whats a better way to typesafe nested prisma models? e.g
    Copy code
    interface ModelC {
      ...
    }
    
    Interface ModelB extends ModelC {
      ...
    }
    
    Interface ModelA extends ModelB {
      ...
    }
    ✅ 1
    r
    a
    • 3
    • 8
  • m

    Michael Roberts

    06/01/2022, 3:39 PM
    Is there a way where we can run Prisma in an atomic transaction state … such that we can either decide to commit or rollback once we have run some code?
    ✅ 1
    a
    • 2
    • 1
  • b

    Berian Chaiwa

    06/01/2022, 10:01 PM
    Hello everyone. I am struggling to make auto-completion work in the resolvers for the
    context
    . I am using
    Apollo-Server
    with
    Prisma
    and
    code-generator
    for resolver types. The args are type-safe and I can auto-complete in resolvers but I can't do so with
    context
    . In the resolver if I set the
    context: GraphQLContext
    I am getting the below errors but it works without the context type. Here is the error:
    Copy code
    Type '(_root: {}, { id, code, name }: Partial<QueryCountryArgs>, context: GraphQLContext) => Prisma__CountryClient<Country | null>' is not assignable to type 'Resolver<Maybe<ResolverTypeWrapper<Country>>, {}, any, Partial<QueryCountryArgs>> | undefined'.
    And here is how I am setting up the server and declaring /instantiating the context:
    Copy code
    import fs from "fs";
    import path from "path";
    import { ApolloServer } from "apollo-server-express";
    import { ApolloServerPluginDrainHttpServer } from "apollo-server-core";
    import { makeExecutableSchema } from "@graphql-tools/schema";
    import { WebSocketServer } from "ws";
    import { useServer } from "graphql-ws/lib/use/ws";
    import { PrismaClient } from "@prisma/client";
    import express, { Request } from "express";
    import http from "http";
    import {
      typeDefs as scalarTypeDefs,
      resolvers as scalarResolvers,
    } from "graphql-scalars";
    import { GraphQLSchema } from "graphql";
    import { resolvers } from "./api/resolvers/resolvers";
    
    const prisma = new PrismaClient();
    
    export type GraphQLContext = {
      req: Request;
      prisma: PrismaClient;
    };
    
    export async function createContext(
      req: Request,
      prismaClient: PrismaClient
    ): Promise<GraphQLContext> {
      return {
        req,
        prisma: prismaClient,
      };
    }
    
    const typeDefs = fs.readFileSync(
      path.join(path.resolve(), "src/api/schema.graphql"),
      "utf-8"
    );
    
    const schema = makeExecutableSchema({
      typeDefs: [typeDefs, ...scalarTypeDefs],
      resolvers: { ...resolvers, ...scalarResolvers },
    });
    
    async function startApolloServer(
      gqlSchema: GraphQLSchema,
      prismaClient: PrismaClient
    ) {
      const app = express();
    
      // 1. Http Server
      const httpServer = http.createServer(app);
    
      // 2. Websocket Server
      const wsServer = new WebSocketServer({
        server: httpServer,
        path: "/",
      });
    
      const wsServerCleanup = useServer({ schema: gqlSchema }, wsServer);
    
      // 3. Apollo Server
      const server = new ApolloServer({
        schema,
        context: ({ req }) => {
          return createContext(req, prismaClient);
        },
        csrfPrevention: true,
        plugins: [
          // Proper shutdown for the HTTP server.
          ApolloServerPluginDrainHttpServer({ httpServer }),
    
          // Proper shutdown for the websocket server
          {
            async serverWillStart() {
              return {
                async drainServer() {
                  await wsServerCleanup.dispose();
                },
              };
            },
          },
        ],
      });
    
      await server.start();
      server.applyMiddleware({
        app,
      });
    
      //   Modified server startup
      await new Promise<any>((resolve: any) =>
        httpServer.listen({ port: 4000 }, resolve)
      );
      console.log(`🚀 Server ready at <http://localhost:4000>${server.graphqlPath}`);
    }
    
    startApolloServer(schema, prisma);
    And my resolvers fail when I do this:
    Copy code
    country: (_root, { id, code, name }, context: GraphQLContext) => { // fails when this type is applied here
        return context.prisma.country.findUnique({
          where: {
            id: id || undefined,
            code: code || undefined,
            name: name || undefined,
          },
        });
      },
    ✅ 1
    • 1
    • 3
  • y

    YeonHoPark

    06/02/2022, 1:19 AM
    I am using graphql-iso-date for date custom scalar. why is the type of Date custom scalar specified as any type ? can’t i explicitly specify the type ?
    👀 1
    n
    v
    n
    • 4
    • 6
  • j

    Josue Quinteros

    06/02/2022, 4:58 AM
    hey, how you doing? I've been using TypeORM for a while, I cannot continue using it haha. What's the first resource besides official docs, you would recommend me to get a deep understanding of Prisma? Thx in advanced go gopher dance
    ✅ 1
    n
    n
    • 3
    • 6
  • j

    Jeremy Monson

    06/02/2022, 5:23 AM
    Hi Everyone. Currently running a
    prisma migrate deploy
    on my production database. The command has been running for over 15 minutes, and all it is doing is dropping a unique index. Is this normal? What do i do? It's stuck in the "Applying Migration" state
    ✅ 1
    n
    • 2
    • 3
  • t

    Thangavel P

    06/02/2022, 6:05 AM
    Hi, Anyone help me out to select a Enum column using findUnique? When I give like below select: { status: true } I am getting ReferenceError: status is not defined Schema referrence status JobStatus @default(WAITING)
    👀 1
    ✅ 1
    n
    • 2
    • 4
  • a

    Adam Boulila

    06/02/2022, 3:08 PM
    Copy code
    return this.prismaService.employeeOrderItem.update(
      The column `(not available)` does not exist in the current database.
    why is prisma unable to tell me the column name
    ✅ 1
    n
    j
    • 3
    • 10
  • n

    Natalia

    06/02/2022, 3:53 PM
    Hey, <!channel> - only two weeks left until Prisma Day! ⏳ The final schedule of talks and workshops is ready to view on our site and it is the bomb! 💥 Check out the schedule and get your ticket here. You can join Prisma Day online on the day, or choose to celebrate with us in James June Sommergarten in Berlin. We hope to see you there! 👋
    😍 11
    prisma rainbow 18
    🇷🇴 2
    catjam 13
    pakistan parrot 6
    fast parrot 27
    a
    • 2
    • 3
  • e

    Eric Kreis

    06/02/2022, 4:07 PM
    👋 Hello, team!
    👋 5
    n
    • 2
    • 1
  • z

    Zakaria Mofaddel

    06/02/2022, 6:19 PM
    I have been using Prisma with NodeJs for so long, I was so happy when I saw the Prisma client module for Golang and then the deprecation notice hit me so hard😭 Hope you guys will go back to maintaining it, you rule when it comes to ORMs in my very humble opinion
    n
    • 2
    • 2
  • j

    John Smeeth

    06/03/2022, 1:10 AM
    hi all
    👋 1
1...581582583...637Latest