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

    Chris D.

    09/24/2021, 7:43 AM
    Hi there, I just started with Prisma and was looking for Schema-Samples. I found https://www.prisma.io/docs/guides/schema-query-examples using the docs-search - but unfortunately there's no sample. I was using the "unhappy" button - hoping I could provide feedback - but then again that ended in failure - resulting in a blocked request because of "CORS Missing Allow Origin" (request: {"pageUrl":"/docs/guides/schema-query-examples","sentiment":"Unhappy"}).
    r
    • 2
    • 2
  • j

    Josef Henryson

    09/24/2021, 7:46 AM
    Hi, I’m still struggling with trying to migrate from Prisma 1.34 to Prisma 2/3. My current task is to change my scalar arrays to regular tables / prisma types so that it will work in MySQL which we use as DB. Does anyone here have any experience with this and could you then please share some tips on how you managed this? Or do you have some other idea on how to break out from the scalar array dependency?
  • v

    Vladi Stevanovic

    09/24/2021, 10:33 AM
    Hello team 👋! Next Tuesday, Sept 28th, we're hosting our #8 Prisma Meetup and we have an amazing speaker line up: 🎙️ "Prisma, TypeScript, AzureSQL, Serverless, FullStack…oh my!" by Davide Mauri - Program Manager at Microsoft 🎙️ "_Full-Stack Jamstack Fun_" by @Mike Cavaliere - Senior Engineering Strategist at Echobind 🎙️ "_Boosting development with Prisma & GraphQL_" by @Victor Iris - #PrismaAmbassador & Sr. FullStack engineer at DigitalOnUs by Tech Mahindra 👉  Join the meetup: https://www.meetup.com/Berlin-Prisma-Meetup/events/280919370/ 👉  Show your support by retweeting: https://twitter.com/prisma/status/1441347745306931201
  • n

    NikolaBjelo

    09/24/2021, 1:28 PM
    hello everyone, what is the difference between
    node_modules/.prisma/client
    and
    node_modules/@prisma/client
    ? (didn't know about node_modules/.prisma until vscode autoimported from there today for the first time)
    t
    r
    • 3
    • 2
  • c

    Chip Clark

    09/24/2021, 2:59 PM
    [ExceptionsHandler]
    $queryRaw
    is a tag function, please use it like the following: breaking with Prisma 3.1.1 - was working with prisma 2.x
    Copy code
    public RelatedClient = 'SELECT client.RelatedClientNumber [RelatedClientNumber], client.RelatedClientName [RelatedClientName], ' + 
        'splitbill.TimekeeperNumber [TimekeeperNumber], person.LastName [SplitBill_LastName], ' +
        'person.FirstName [SplitBill_FirstName] ';
    
    public RelatedClientJoin = 'FROM ERP_ODS_Test.dbo.Client AS client ' +
        'INNER JOIN ERP_ODS_Test.dbo.SplitBillingAttorney AS splitbill ' +
        'ON client.ClientNumber = splitbill.ClientNumber  ' +
        'INNER JOIN dbo.Person AS person ' +
        'ON splitbill.TimekeeperNumber = person.TimekeeperNumber ';
    
    public activeClient = "WHERE client.ClientActive = 1 AND splitbill.EmployeeActive = 1 ";
    
    public Count = 'SELECT COUNT(*) ';
      
    accessPrismaRaw(raw1: TemplateStringsArray, rawCount: TemplateStringsArray) {
        let Memory = [];
        const data = Promise.all([
          this.prisma.$queryRaw(raw1),
          this.prisma.$queryRaw(rawCount),
          Memory = this.appService.getMemory()
        ]).then(([records, total]) => {
          return {
            records,
            metadata: {
              count: total,
              memory: Memory
            },
          };
        });
        return data;
      }
    
      
    async relatedclients(params: { searchString?: string; } = {}) {
        const { searchString } = params;
        let viewString = this.RelatedClient + this.RelatedClientJoin;
        let rawView;
        let rawCount;
        let searchFilter = this.activeClient + " AND client.RelatedClientName LIKE '%" + searchString + "%'";
        if (searchString) {
          rawView = this.RelatedClient + this.RelatedClientJoin + searchFilter;
          rawCount = this.Count + this.RelatedClientJoin + searchFilter;
        } else {
          rawView = this.RelatedClient + this.RelatedClientJoin + this.activeClient;
          rawCount = this.Count + this.RelatedClientJoin + this.activeClient;
        }
        return this.accessPrismaRaw(rawView, rawCount);
      }
    The final script (rawView) = SELECT client.RelatedClientNumber [RelatedClientNumber], client.RelatedClientName [RelatedClientName], splitbill.TimekeeperNumber [TimekeeperNumber], person.LastName [SplitBill_LastName], person.FirstName [SplitBill_FirstName] FROM ERP_ODS_Test.dbo.Client AS client INNER JOIN ERP_ODS_Test.dbo.SplitBillingAttorney AS splitbill ON client.ClientNumber = splitbill.ClientNumber  INNER JOIN dbo.Person AS person ON splitbill.TimekeeperNumber = person.TimekeeperNumber WHERE client.ClientActive = 1 AND splitbill.EmployeeActive = 1  AND client.RelatedClientName LIKE '%google%' Works when run on the sql server. Change $queryRaw to $executeRawUnsafe - and the sql script executes.
    Copy code
    accessPrismaRaw(raw1: string, rawCount: string) {
        let Memory = [];
        const data = Promise.all([
          this.prisma.$executeRawUnsafe(raw1),
          this.prisma.$executeRawUnsafe(rawCount),
          Memory = this.appService.getMemory()
        ]).then(([records, total]) => {
          return {
            records,
            metadata: {
              count: total,
              memory: Memory
            },
          };
        });
        return data;
      }
    Again, $queryRaw used to work in 2.x, but no longer in 3.1.1
    r
    • 2
    • 1
  • k

    Kent C. Dodds

    09/24/2021, 3:13 PM
    Heya friends, does anyone have a good way of generating an assertion function based on a dynamic type like those we get from prisma queries? For example:
    Copy code
    const users = await prismaRead.user.findMany({
      select: {
        firstName: true,
        email: true,
        id: true,
        team: true,
      },
      orderBy: {
        createdAt: 'asc',
      },
    })
    const data: LoaderData = {users}
    return data // this gets sent over the network as json
    
    // then later, on the other side of a network request, in a React component for example:
    
    const data = useLoaderData()
    assert(data, LoaderData)
    data.users[0].firstName // <-- autocompletes
    a
    r
    • 3
    • 7
  • b

    Brian de la Motte

    09/24/2021, 3:44 PM
    Hello, we are using Nextauth with Prisma. I had it working and then it randomly broke. I rolled back to when I first got it working and still getting this error. I was wondering if anyone else has ran into this message before.
    Copy code
    "message": "ReferenceError: prisma is not defined\n    at Object.2132 (/var/task/.next/server/chunks/7133.js:15:10)\n    at __webpack_require__ (/var/task/.next/server/webpack-runtime.js:25:42)\n    at Object.7133 (/var/task/.next/server/chunks/7133.js:30:69)\n    at __webpack_require__ (/var/task/.next/server/webpack-runtime.js:25:42)\n    at Object.8316 (/var/task/.next/server/pages/api/auth/[...nextauth].js:28:13)\n    at __webpack_require__ (/var/task/.next/server/webpack-runtime.js:25:42)\n    at __webpack_exec__ (/var/task/.next/server/pages/api/auth/[...nextauth].js:137:52)\n    at /var/task/.next/server/pages/api/auth/[...nextauth].js:138:80\n    at Function.__webpack_require__.X (/var/task/.next/server/webpack-runtime.js:108:21)\n    at /var/task/.next/server/pages/api/auth/[...nextauth].js:138:47",
  • c

    Chip Clark

    09/24/2021, 3:49 PM
    The following prisma.queryRaw - doesn't work SELECT contcomp.ContactCompanyID [ContactCompanyID], contcomp.CompanyName [CompanyName], contcomp.CompanyWebSite FROM dbo.ContactCompany AS contcomp WHERE ContactCompanyID = 7247 error: Raw query failed. Code:
    102
    . Message:
    Incorrect syntax near '='.
    If I change last line to WHERE contcomp.ContactCompanyID = 7247 error: Raw query failed. Code:
    102
    . Message:
    Incorrect syntax near '.'.
    This suggests the query is not able to process the field name ContactCompanyID for WHERE.
    • 1
    • 5
  • c

    Chris V

    09/24/2021, 4:39 PM
    Hello all 👋 I'm planning to use Prisma deployed as a lambda with an Aurora Serverless database, but I've seen that Prisma doesn't support the Aurora Serverless Data API: https://github.com/prisma/prisma/issues/1964 Can anyone advise on whether Aurora Serverless is still a good option with Prisma even without the Data API? I've got things working without the Data API (just connecting to Aurora Serverless from my lambda like I would to any RDS instance) but I'm not sure if this is just making things more difficult for myself without getting the real benefits Aurora Serverless
    f
    t
    • 3
    • 10
  • c

    Carlos Gomez

    09/24/2021, 8:58 PM
    Hi, I'm using Postgres and have a JSON column with this shape:
    Copy code
    { 
      "id": "uuid", 
      "members": [ { "id": 1 } ],
    }
    If I have a specific
    member
    ID, how would I find rows that have a
    members
    array containing a
    member
    object with that ID? I'm using the new JSON filtering API.
    r
    • 2
    • 1
  • s

    Sai Krishna

    09/25/2021, 7:31 AM
    Can someone tell me what's the rate limit for Prisma data proxy? Thank you
    r
    j
    • 3
    • 7
  • j

    Jon Insley

    09/25/2021, 8:55 AM
    Does anyone know if it's possible in Prisma Studio to bulk change the same column value for multple rows? I have a column for event category and need to change about 200 rows to the same value. Changing one at a time takes so long 😓
    r
    • 2
    • 2
  • n

    Nditah Samweld

    09/25/2021, 9:48 AM
    Who has a quick-starter Prisma + Typescript + MongoDb 🙏
  • i

    Ivan

    09/25/2021, 10:04 AM
    Hi all! I have a production database and i would like to modify a schema addinf another field to it. I've read the documentation, i've found it a little confusing, i'm still a newbie into backend. What would be the best approach, in order to modify a schema in a production database?
    r
    • 2
    • 4
  • t

    Temm

    09/25/2021, 10:43 AM
    does a prisma.$transaction with 2 updates protect from any queries being ran between the 2 updates and getting back a state where only one of the 2 updates is applied?
    r
    • 2
    • 1
  • n

    Nditah Samweld

    09/25/2021, 1:40 PM
    How to use Enum in Prisma? data.type is MediaType
    Copy code
    export enum MediaType {
      IMAGE = 'IMAGE',
      VIDEO = 'VIDEO',
    }
    registerEnumType(MediaType, {
      name: 'MediaType',
      description: 'Media type',
    });
    
    ======
    
        return this.prisma.media.create({
          data: {
            type: data.type,
            fileItem: data.fileItem && { connect: { id: data.fileItem } },
          },
        });
    r
    • 2
    • 1
  • p

    Phil Bookst

    09/25/2021, 8:01 PM
    hey guys my prisma api calls sometimes timeout after 30s - i guess it's because of my connection pooler being overloaded and the waiting queue ist too long causing the timeout. i'm using supabase with pgbouncer hosted on vercel do you have any idea how to solve this?
    r
    j
    • 3
    • 7
  • h

    Hristijan

    09/25/2021, 10:37 PM
    Hi all! To cut straight to the chase - I’m interested in the scenario of using Prisma for a shared database across multiple GraphQL microservices. I understand the scenario of having a database for each microservice, that’s pretty straightforward. However, having only one database for all my microservices seems a bit tricky and challenging. Regarding the answer to a similar question on GitHub, having a Prisma schema definition as an npm package is in my opinion, impractical - you’d want to regularly update your package across all your applications. Is this considered an anti-pattern in the case of Prisma? Is having a separate database for each microservice (therefore a separate Prisma schema) a far better approach, especially with a gateway graph like apollo federation? Has anyone here had any experience on this topic (or an opinion, for that matter)? Thank you very much! 😊
  • a

    Andrew Ross

    09/26/2021, 3:07 AM
    anyone trying out the new beta release of next-auth with prisma? where the prisma model itself is altered a bit? I am using it with GitHub at the moment I was having success initially but now am getting this error
    Copy code
    [next-auth][error][OAUTH_CALLBACK_HANDLER_ERROR] 
    <https://next-auth.js.org/errors#oauth_callback_handler_error> getUserByAccount is not a function {
      message: 'getUserByAccount is not a function',
      stack: 'TypeError: getUserByAccount is not a function\n' +
        '    at Object.callback (/home/dopaminedriven/prisma-nexus-next-ts/cortina-crm/cortina-tracking/.next/server/pages/api/auth/[...nextauth].js:2583:39)\n' +
        '    at runMicrotasks (<anonymous>)\n' +
        '    at processTicksAndRejections (node:internal/process/task_queues:96:5)\n' +
        '    at async NextAuthHandler (/home/dopaminedriven/prisma-nexus-next-ts/cortina-crm/cortina-tracking/.next/server/pages/api/auth/[...nextauth].js:832:18)\n' +
        '    at async Object.apiResolver (/home/dopaminedriven/prisma-nexus-next-ts/cortina-crm/cortina-tracking/node_modules/next/dist/server/api-utils.js:101:9)\n' +
        '    at async DevServer.handleApiRequest (/home/dopaminedriven/prisma-nexus-next-ts/cortina-crm/cortina-tracking/node_modules/next/dist/server/next-server.js:770:9)\n' +
        '    at async Object.fn (/home/dopaminedriven/prisma-nexus-next-ts/cortina-crm/cortina-tracking/node_modules/next/dist/server/next-server.js:661:37)\n' +
        '    at async Router.execute (/home/dopaminedriven/prisma-nexus-next-ts/cortina-crm/cortina-tracking/node_modules/next/dist/server/router.js:205:32)\n' +
        '    at async DevServer.run (/home/dopaminedriven/prisma-nexus-next-ts/cortina-crm/cortina-tracking/node_modules/next/dist/server/next-server.js:841:29)\n' +
        '    at async DevServer.run (/home/dopaminedriven/prisma-nexus-next-ts/cortina-crm/cortina-tracking/node_modules/next/dist/server/dev/next-dev-server.js:355:20)',
      name: 'TypeError'
    }
    that's after the oauth callback logs all of my github info to the console in json format correctly...
  • p

    Phil Bookst

    09/26/2021, 10:04 AM
    Hey guys, i'm having trouble using nested queries - my db and server are hosted in the same city so it's not because of latency My schema looks like this:
    Copy code
    model Profile {
      id              String?     @unique
      username        String      @id
      is_private      Boolean?
      is_verified     Boolean?
      full_name       String?
      biography       String?
      profile_pic_url String?
      post_amount     Int?
      follower        Int?
      following       Int?
      imageTags       ImageTags[]
    
      nodes           Image[] // this is the slow relation
    
      SearchProfiles SearchProfiles[]
      @@map("profile")
    }
    
    model Image {
      id              String           @id
      thumbnail       String
      shortcode       String           @unique
      liked           Int
      comment_count   Int
      engagement_rate Float?
      day             Int?
      hour            Int?
      date            String
      caption         String?
    
      profile         Profile?         @relation(fields: [profileUsername], references: [username])
      profileUsername String?
    
      hashtag         Hashtag?         @relation(fields: [hashtagName], references: [name])
      hashtagName     String?
      location        Location?        @relation(fields: [locationId], references: [id])
      locationId      String?
      imageHashtags   ImageHashtags[]
      imageTags       ImageTags[]
      imageLocations  ImageLocations[]
    
      @@map("image")
    }
    if i run this query, it takes about 4-5 seconds to give me the results
    Copy code
    const user = await prisma.profile.findUnique({
        where: {
          username,
        },
        include: {
          nodes: true,
        },
      });
    if i run it without the include it takes around 200ms
    Copy code
    const user = await prisma.profile.findUnique({
         where: {
          username,
        },
      });
    the profile table has around 370k entries and and image table around 620k
  • p

    Peter Boomsma

    09/26/2021, 10:30 AM
    i have a
    User
    table, each
    User
    can have multiple
    FollowedBy
    records (a many to many relation to other Users). I want to push a record (a notification) to each of the
    FollowedBy
    users of the current user if a certain action has been done.
    Copy code
    model User {
      id                Int     @id @default(autoincrement())
      email             String  @unique
      name              String
      user_name         String  @unique
      password          String
      movies            Movie[]
      notifications     Notification[]
      followedBy        User[]  @relation("UserFollows", references: [id])
      following         User[]  @relation("UserFollows", references: [id])
    }
    
    model Notification {
      id                Int     @id @default(autoincrement())
      link              String?
      movie_id          Int?
      message           String
      icon              String?
      thumbnail         String?
      user              User    @relation(fields: [userId], references: [id])
      userId            Int
      watched           Boolean
    }
    So I need a create function on the notification:
    Copy code
    createNotification: async (_, args, {req, res}) => {
        const notification = await prisma.notification.create({
          
        });
    
        return notification;
      },
    What would be the best way to go through the list of
    FollowedBy
    users for the current user? (current user id is available on the req
    req.userId
    r
    • 2
    • 1
  • t

    Thomas Morice

    09/26/2021, 7:12 PM
    Hello Prisma team! I have a question related to the generated model, it’s very convenient to be able to use auto generated model from the prisma schema, but I can see that I have a one to many relationship, and this is not part of the model. Is there a reason why? Can we somehow do so it generates the model with the relation fields ? Thnaks in advance
    c
    • 2
    • 2
  • u

    user

    09/26/2021, 11:00 PM
    Fullstack App With TypeScript, PostgreSQL, Next.js, Prisma &amp; GraphQL: GraphQL API This article is the second part of a course where you build a fullstack app with Next.js, GraphQL, TypeScript, Prisma, and PostgreSQL. In this article, you will create the GraphQL API and interact with it on the frontend.
  • c

    Charles Dimino

    09/27/2021, 5:08 AM
    is there a way to tell prisma to “include everything”?
    r
    • 2
    • 4
  • a

    Andrew Ross

    09/27/2021, 5:55 AM
    this would be a type safe way to create nested input using the validator, ja? Asking because the example indicates that it isn't possible for it to be type safe unless using a third party tool or package here
    Copy code
    const userCreate = ({
      email,
      name,
      dob,
      role,
      type,
      provider,
      accessToken,
      providerAccountId,
      isAdmin
    }: {
      isAdmin: boolean;
      email: string;
      name: string;
      dob: string;
      role: Role;
      type: string;
      provider: string;
      accessToken: string;
      providerAccountId: string;
    }) => {
      return Prisma.validator<
        Prisma.UserCreateInput extends Prisma.AccountCreateInput
          ? Prisma.UserCreateInput & Partial<Prisma.AccountCreateInput>
          : Prisma.UserCreateInput
      >()({
        email,
        isAdmin: role === "USER" ? !isAdmin : !!isAdmin,
        name,
        accounts:
          {
            create: {
              type,
              provider,
              accessToken,
              providerAccountId,
              dob,
              role
            }
          } ?? {}
      });
    };
    r
    • 2
    • 1
  • m

    Manthan Mallikarjun

    09/27/2021, 6:35 AM
    Hello! I've started to have some weird behavior after upgrading to 3.1.1 from 2.30.2. I'm doing the following:
    Copy code
    export const prisma = new PrismaClient({
      datasources: { db: { url: generateDatabaseURL(schemaId) } },
    });
    and I know it works because doing console.log shows:
    Copy code
    datasourceOverrides: [Object: null prototype] {
              db: '<postgresql://example:example@localhost:54321/example?schema=test-9d1a4b74-2304-4edf-8663-92ec3bb55a7a>'
            },
    in the mess. However when I query the data, its actually coming from the default schema and not the schema listed above (I used a postgres viewer to go check the data in the tables of each of those schemas). Any idea why this would be happening?
  • h

    Harun

    09/27/2021, 6:49 AM
    Hi guys, is it possible to make 1-1 relationship with prisma?
    l
    r
    • 3
    • 11
  • h

    Harsha MV

    09/27/2021, 8:01 AM
    Copy code
    PrismaClientValidationError: Unknown arg `youtube` in data.youtube for type ProjectCreateInput. Did you mean `about`?
    I added this as a new migrate and its reflecting in the database as well. but am getting the following error when I try to create the record
    r
    d
    • 3
    • 11
  • c

    Charity Darko

    09/27/2021, 9:10 AM
    Hello! I added a relation to the schema and it looks like
    Copy code
    model Company {
      id        Int   @id
      name     String
      users User[]
    }
    
    model User {
      userId        Int       @default(autoincrement()) @id
      companyId     Int?
      worksAt   Company? @relation(fields: [companyId], references: [id])
      email         String?   @unique
      name          String
      password      String
      @@map(name: "users")
    When I run $ prisma db push I get this error. Any assistance will be appreciated
    r
    • 2
    • 4
  • h

    Harsha MV

    09/27/2021, 9:29 AM
    Copy code
    PrismaClientUnknownRequestError: Error occurred during query execution:
    ConnectorError(ConnectorError { user_facing_error: None, kind: QueryError(Error { kind: ToSql(0), cause: Some(Error(Parser(InvalidLength { expected: Any([36, 32]), found: 0 }))) }) })
        at cb (/var/task/node_modules/@prisma/client/runtime/index.js:36956:17)
        at async handler (/var/task/.next/server/pages/api/projects.js:261:29)
        at async Object.apiResolver (/var/task/node_modules/next/dist/server/api-utils.js:101:9)
        at async Server.handleApiRequest (/var/task/node_modules/next/dist/server/next-server.js:760:9)
        at async Object.fn (/var/task/node_modules/next/dist/server/next-server.js:651:37)
        at async Router.execute (/var/task/node_modules/next/dist/server/router.js:205:32)
        at async Server.run (/var/task/node_modules/next/dist/server/next-server.js:825:29)
        at async Server.handleRequest (/var/task/node_modules/next/dist/server/next-server.js:292:20)
        at async Server.<anonymous> (/var/task/___next_launcher.js:32:9) {
      clientVersion: '3.1.1'
    }
    Any idea why this error happens?
    r
    • 2
    • 16
1...487488489...637Latest