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

    Robert Witchell

    04/30/2021, 6:15 AM
    anyone have any examples on seeding prisma (other than the prisma docs). Any additional libraries out there that can help with the data creation?
  • d

    Danil Tikhii

    04/30/2021, 7:06 AM
    Hi. I need help, my work just stuck. I'm trying to solve the race condition problem, but don't understand how to handle it with Prisma API. My API server has route "/shop/buyItem", where people can buy something by providing itemId. Code logic something like this: 1) get user and his balance 2) get additional info about item from DB 3) check if user has enough money to buy item 4) compute which items need to be added additionally 5) add items to user inventory 6) update user balance The actual problem happens when the user sends me multiple requests. There is a BIG chance that he could buy an item multiple times without having enough money for it. The code can easily run in parallel (express and GCP instance scaling). So, I need somehow prevent this. I found a pretty good solution, Postgres row level locks. Just add "FOR UPDATE" lock for the current user row (1st stage) and all subsequent requests with this user will just wait for the ending of the first transaction. The real question is.. how to make this "long-running transaction" (which really not, I guess), which Prisma does not support? The update / upsert / etc API doesn't help me, cuz there are too many dependent requests and actions. I just wanna use straightforward transactions, as I do with pg library. Something like this:
    Copy code
    const conn = await pool.connect();
    
    await conn.query("BEGIN");
    const userRes = await conn.query("SELECT coins, ... , ... FROM "User" WHERE "id" = 'someId'" FOR UPDATE);
    
    ...
    
    await conn.query("COMMIT");
    Is there any way to do this? Don't wanna add pg library in project just for this functionality o.o
    👀 1
  • l

    Lars Ivar Igesund

    04/30/2021, 7:17 AM
    @Danil Tikhii I haven't done this in prisma, but generally this is the type of problem that is handled by a distributed lock (assuming you want to scale this webshop and the additional requests may end up on a different instance). In this case though, a simple solution may be to lock the user by having a transaction column?
    d
    • 2
    • 3
  • r

    Robin

    04/30/2021, 2:07 PM
    What is the recommended way to use a DateTime in nextjs with getServerSideProps and prisma? I'm getting
    Copy code
    Error: Error serializing `.urls[0].createdAt` returned from `getServerSideProps` in "/urls".
    Reason: `object` ("[object Date]") cannot be serialized as JSON. Please only return JSON serializable data types.
    r
    • 2
    • 1
  • j

    Joey

    04/30/2021, 5:28 PM
    Anyone get this warning
    warn(prisma-client) Already 10 Prisma Clients are actively running.
    and how do you ensure you only have one instance? I am already doing;
    Copy code
    //lib/prisma-client.ts
    import { PrismaClient } from "@prisma/client"
    
    const prisma = new PrismaClient()
    export default prisma
    Then importing that instance and using it. Or do I have to explicitly have to
    disconnect
    ?
    j
    • 2
    • 4
  • s

    Sebastian

    05/01/2021, 5:54 AM
    Good morning. I'm here to ask for a little of help, I recently started learning the Prisma and run into this issue:
    Copy code
    // Console log
    
    node[21175]: ../src/node_http_parser.cc:567:static void node::{anonymous}::Parser::Initialize(const v8::FunctionCallbackInfo<v8::Value>&): Assertion `args[3]->IsInt32()' failed.
     1: 0x562789d0ab61 node::Abort() [node]
     2: 0x562789d0abf7  [node]
     3: 0x562789d26945  [node]
     4: 0x562789f4ca37 v8::internal::FunctionCallbackArguments::Call(v8::internal::CallHandlerInfo) [node]
     5: 0x562789f4d869  [node]
     6: 0x562789f4de3f  [node]
     7: 0x562789f4e0e6 v8::internal::Builtin_HandleApiCall(int, unsigned long*, v8::internal::Isolate*) [node]
     8: 0x56278a79d539  [node]
    zsh: abort (core dumped)  npm run dev
    The code is sample from the website, for nextjs.
    import {  PrismaClient } from "@prisma/client";
    import { NextApiHandler, NextApiRequest, NextApiResponse } from "next";
    
    // The code:
    
    const prisma = new PrismaClient()
               
    async function main(){
      
        const user = await prisma.user.create({
            data:{
                name: "test",
                email: "<mailto:test@gmail.com|test@gmail.com>"
            }
        })
        console.log(user)
      
        prisma.$disconnect()
    }
    
    
    export default async (req: NextApiRequest, res: NextApiResponse, next: NextApiHandler)=>{
        
       
        switch (req.method){
            case 'POST':{
    
                
                try{
                    await main().catch(err=>console.log(err)).finally(async()=>{
                        res.send("ok")
                      
                      })
                }   
                catch(err){
                   
                }
             
              
            
              
            }
            case 'GET':{
    
            }
        }
    }
    What went wrong?
    r
    • 2
    • 7
  • s

    Sebastian

    05/01/2021, 6:27 AM
    Same thing happens with prisma studio when trying to launch
    Copy code
    Prisma Studio is up on <http://localhost:5555>
    node[6740]: ../src/node_http_parser.cc:567:static void node::{anonymous}::Parser::Initialize(const v8::FunctionCallbackInfo<v8::Value>&): Assertion `args[3]->IsInt32()' failed.
    c
    l
    • 3
    • 3
  • d

    Dog

    05/01/2021, 9:14 AM
    Is this still not fixed? https://github.com/prisma/prisma/discussions/1971
    m
    j
    • 3
    • 2
  • d

    Dog

    05/01/2021, 9:14 AM
    I find myself in a situation where I need to filter a post by the user id and the id of the post
  • c

    Carlos

    05/01/2021, 12:44 PM
    _Is possible do something like this on Prisma?
    prisma.posts.findUnique_({......}).then().catch()
    l
    • 2
    • 1
  • j

    Joakim Repomaa

    05/02/2021, 11:47 AM
    hi there!
  • j

    Joakim Repomaa

    05/02/2021, 11:50 AM
    I'm writing an api using prisma and almost all my models are scoped to the user, that's currently logged in. Now, if i write CRUD endpoints I would expect to have some way of scoping the uniquewhere queries to the currently logged in user. I haven't found a way to do this. The only way allowing scoped write operations seems to be by updating the user and using nested updates to get to the actual record you want to update. That's quite cumbersome though, because getting back the updated nested model involves more code.
  • j

    Joakim Repomaa

    05/02/2021, 11:51 AM
    am i missing something?
  • j

    Joakim Repomaa

    05/02/2021, 11:52 AM
    e.g. for
    PATCH /post
    i'd expect to be able to do something like
    prisma.post.update({ where: { id: params.id, user: { id: context.currentUser.id } }, ... })
  • s

    stephan levi

    05/02/2021, 4:05 PM
    i’m creating a car entity setting the owner field to a non existing user prisma creates the car but throws an error that the user does not exist is there a way to tell prisma to fail the whole process before creating the car entity ?
    r
    r
    • 3
    • 5
  • a

    Alexis

    05/03/2021, 3:35 AM
    Copy code
    Role.findOne({
    	raw: true,
    	where: {
    		guild: this.guild.id,
    		channel: message.channel.id,
    		message: message.id,
    		pairs: {
    			[Op.contains]: [{ emoji }],
    		},
    	},
    });
    // Is this a thing in Prisma? "pairs" in an array of objects which has an emoji prop (along with other props)
  • p

    Paul

    05/03/2021, 9:29 AM
    hey all. I have a model:
    Copy code
    model DamFiles {
      id                Bytes     @id @db.Binary(26)
      ...
      createdAt         DateTime  @default(now())
      updatedAt         DateTime? @updatedAt
      deletedAt         DateTime?
    
      // relations
      type   DamFileTypes     @relation(fields: [typeId], references: [id])
      typeId Bytes            @db.Binary(26)
      mime   DamFileMimeTypes @relation(fields: [mimeId], references: [id])
      mimeId Bytes            @db.Binary(26)
      user   User             @relation(fields: [userId], references: [id])
      userId Bytes            @db.Binary(26)
    
      DamImages      DamImages[]
      DamFileTags    DamFileTags[]
      DamImageColors DamImageColors[]
    }
    When I do a query, I get the type, mime, user relations by using include. When I include the DamImages, DamFileTags and DamImageColors. I don't see them appearing in the result object. My query:
    Copy code
    const query = await db.damFiles.findMany({
          where: {
            parentId: queryParams.parentId,
            deletedAt: null,
          },
          include: {
            user: {
            },
            mime: {
            },
            type: {
            },
            DamFileTags: {
            },
            DamImageColors: {
            },
            DamImages: {          
            },
          },
        })
    Am I right in saying. The Dam tables aren't getting anything due to having a where clause on them internally using parentId ? Thanks Note: I have pulled out the select statements for brevity.
    r
    j
    • 3
    • 19
  • d

    Danil Tikhii

    05/03/2021, 3:48 PM
    Hi. I need help, my work just stuck. I'm trying to solve the race condition problem, but don't understand how to handle it with Prisma API. My API server has route "/shop/buyItem", where people can buy something by providing itemId. Code logic something like this: 1) get user and his balance 2) get additional info about item from DB 3) check if user has enough money to buy item 4) compute which items need to be added additionally 5) add items to user inventory 6) update user balance The actual problem happens when the user sends me multiple requests. There is a BIG chance that he could buy an item multiple times without having enough money for it. The code can easily run in parallel (express and GCP instance scaling). So, I need somehow prevent this. I found a pretty good solution, Postgres row level locks. Just add "FOR UPDATE" lock for the current user row (1st stage) and all subsequent requests with this user will just wait for the ending of the first transaction. The real question is.. how to make this "long-running transaction" (which really not, I guess), which Prisma does not support? The update / upsert / etc API doesn't help me, cuz there are too many dependent requests and actions. I just wanna use straightforward transactions, as I do with pg library. Something like this:
    Copy code
    const conn = await pool.connect();
    
    await conn.query("BEGIN");
    const userRes = await conn.query("SELECT coins, ... , ... FROM "User" WHERE "id" = 'someId'" FOR UPDATE);
    
    ...
    
    await conn.query("COMMIT");
    Is there any way to do this? Don't wanna add pg library in project just for this functionality o.o
    👀 1
    🙏 1
    c
    r
    • 3
    • 5
  • s

    Stasi Vladimirov

    05/03/2021, 11:44 PM
    Hello, I didn’t see a help channel and hope that this is the right place to ask. Is there a way to reuse the same Prisma Client/Connection and query multiple schemas on the same MySQL database. Example:
    Copy code
    Query 1: SELECT * FROM `Schema1`.`Requests`
    and
    Copy code
    Query 2: SELECT * FROM `Schema2`.`Accounts`
    c
    r
    • 3
    • 5
  • m

    Mitchell Amihod

    05/04/2021, 2:15 AM
    Hi. Looking at https://github.com/prisma/prisma/issues/2917#issuecomment-708340112 , I don’t quite understand this line:
    Copy code
    While we're still killing the child processes, after the beforeExit hook has been executed, we're not killing the current process anymore, if there are other listeners on the signals, like SIGINT.
    For context, i came across this when looking into graceful shutdowns with nestjs + prisma, with prisma swallowing up the sigterm
    🙌 2
    👍 1
  • m

    Mitchell Amihod

    05/04/2021, 2:18 AM
    Ideally, i would rather deal with the connect/disconnect myself at the app (nest js) layer. Is it possible to opt out of this behaviour? (still looking through the docs, but thought it might be worth asking here)
    👍 2
    🙌 1
    • 1
    • 1
  • m

    Mitchell Amihod

    05/04/2021, 2:57 PM
    Anyone know what the env var PRISMA_FORCE_NAPI is about? it seems like a way I could use to disable the hooks, but not sure what its implications are?
    👍 1
    🙌 1
    j
    • 2
    • 5
  • u

    Ulysse Tallepied

    05/04/2021, 4:37 PM
    Hello thanks for this amazing tool! I was wondering why you choose to create a Go client first although some internals of Prisma are written in Rust?
  • s

    Stasi Vladimirov

    05/05/2021, 1:42 AM
    Is there a way to do something like that in prisma middleware:
    Copy code
    prisma.$use(async (params, next) => {
      if (
        whereActions.includes(params.action) &&
        params.model &&
        prisma[params.model].prototype.hasOwnProperty('tenantId')
      ) {
        params.args.where.tenantId = requestTenantId
      }
      const result = await next(params)
      return result
    })
    the main question is how to do this part:
    Copy code
    prisma[params.model].prototype.hasOwnProperty('tenantId')
    or in other words: How to check, if an abstract model (table) contains a specific property (column)?
    j
    • 2
    • 14
  • n

    Natalia

    05/05/2021, 12:11 PM
    Prisma Meetup is on tomorrow, 6PM CEST! 🤗 You will also have a chance to win the Designing Data-Intensive Applications book by Martin Kleppmann in our raffle. Our superstar speakers: • Guy Royse - "Dungeons, Dragons, and Graph Databases: D&D-themed introduction to graph databases" • Julieta Curdi - "Prisma's Developer Experience" • *Andy Woods and Adam Storm *from Cockroach Labs - "The Future is Multi-region: Building a World-class Multi-region Application in 4 Easy Steps” You can 

    set a YouTube reminder▾

     or RSVP on Meetup. Hoping to see you all there! prisma rainbow
    fast parrot 3
    prisma cool 3
    🇹🇭 1
  • h

    Hector

    05/05/2021, 5:09 PM
    Hi, is there an option or convention for Read methods (findMany, findUnique...) so that the result includes all relations without explicitly specifying the fields in the
    include
    option?
    a
    j
    • 3
    • 5
  • n

    Nitzan

    05/05/2021, 6:02 PM
    Hello! new to prisma and getting started with it. In terms of structuring the schema and using models, we have one "monolithic" db but are trying to decouple the data layer from the business logic/domain layer into somewhat of a microservice approach. In this case, is there best practice for prisma on where the prisma schema should live? can there be multiple prisma schemas for the same DB? (probably an antipattern i assume)
    🇮🇱 1
  • w

    Wilson

    05/05/2021, 6:03 PM
    Hello, I'm trying to apply migrations to local instance buy I'm getting the error
    *Error:* Failure during a migration command: Generic error. (error: The field .... on model .... already exists in this Datamodel. It is not possible to create it once more.)
    but my coworker is able to migrate correctly, what am i missing?
    o
    • 2
    • 1
  • r

    Ron Mizrahi

    05/05/2021, 8:04 PM
    Does prisma has a solution for left join with a table that isn't defined as relation? Thanks
    j
    • 2
    • 4
  • j

    Jonathan Romano

    05/06/2021, 1:16 AM
    I have a function that looks like the following on my users service in a Nest project:
    Copy code
    const selectPublicFields = {...}
    
    async findOne(
        { id, email }: { id?: number; email?: string },
        selectPrivateFields: { email?: boolean } = {}
      ) {
        return this.prisma.user.findUnique({
          select: {
            ...selectPrivateFields,
            ...selectPublicUserFields
          },
          where: { id, email },
        });
      }
    The return type winds up only including id, createdAt, and name, regardless of what I pass to includePrivateFields. Is there a way to type this function so that the caller of findOne will get the correct return type based on the additional fields passed in includePrivateFields?
    • 1
    • 3
1...430431432...637Latest