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

    Jordansz

    10/15/2022, 8:47 PM
    hello everyone, anyone could help me as prisma newbie with an issue im unable to understand correctly?
  • j

    Jordansz

    10/15/2022, 8:48 PM
    im trying to understand why a User and Password model is like this:
    Copy code
    model User {
      id    String @id @default(cuid())
      email String @unique
    
      createdAt DateTime @default(now())
      updatedAt DateTime @updatedAt
    
      password Password?
      notes    Note[]
    }
    
    model Password {
      hash String
    
      user   User   @relation(fields: [userId], references: [id], onDelete: Cascade, onUpdate: Cascade)
      userId String @unique
    }
  • j

    Jordansz

    10/15/2022, 8:48 PM
    So the Password table is a relation to the User. but why is this modelled in a seperate table?
    πŸ‘€ 1
    n
    v
    • 3
    • 2
  • d

    Dave Edelhart

    10/15/2022, 9:27 PM
    Trying to create a string field in a schema / migrate; basic field, want a default of empty string. Prisma doesn’t seem to like
    phone       String                @default("");
    why not?
    πŸ‘€ 1
    n
    v
    • 3
    • 2
  • t

    TomΓ‘Ε‘

    10/16/2022, 12:17 PM
    Copy code
    const sql = Prisma.sql`INSERT INTO "vendor" (id, name, description, "userId", alias, emails, phones, address, links, location) VALUES (${id}, ${
        data.name
      }, ${data.description}, ${
        userId ?? "A0605996-E265-47DF-B152-179C298BB2BC"
      }, ${slugify(`${data.name}_${id.slice(0, 4)}`, "_")}, ${data.emails}, ${
        data.phones
      }, ${data.address}, ${data.links}, ${null});`;
    βœ… 1
    n
    • 2
    • 3
  • b

    Bart Westenenk

    10/16/2022, 1:14 PM
    Hi, I am planning on using Prisma with next.js. In the examples they show that you should close the connection with prisma. Do I also have to do that with the API routes (see picture from prisma.io/nextjs)
    πŸ‘€ 1
    t
    n
    • 3
    • 7
  • b

    Bart Westenenk

    10/16/2022, 1:14 PM
  • b

    Bart Westenenk

    10/16/2022, 3:13 PM
    Different question: Does Prisma handle SQL injection for me or do I have to do that myself?
    βœ… 1
    t
    • 2
    • 2
  • m

    mazhar iqbal

    10/16/2022, 4:32 PM
    How to get records with conditions from multiple tables. Schema: model User { id Int @id @default(autoincrement()) email String @unique name String? posts Post[] } model Post { id Int @id @default(autoincrement()) title String published Boolean @default(false) author User @relation(fields: [authorId], references: [id]) authorId Int } Query: To get users post where user name will be "john" OR post title will be "First Post"?
    βœ… 1
    n
    • 2
    • 2
  • n

    Neil Girardi

    10/17/2022, 1:02 AM
    Hi. I'm new here. I'm building a Next.js app and using NextAuth. I keep getting the following error:
    Copy code
    [next-auth][error][adapter_error_getSessionAndUser] 
    <https://next-auth.js.org/errors#adapter_error_getsessionanduser> 
    Invalid `p.session.findUnique()` invocation in
    /Users/neilgirardi/Projects/Personal/getitapp/node_modules/@next-auth/prisma-adapter/dist/index.js:22:52
    
      19 linkAccount: (data) => p.account.create({ data }),
      20 unlinkAccount: (provider_providerAccountId) => p.account.delete({ where: { provider_providerAccountId } }),
      21 async getSessionAndUser(sessionToken) {
    β†’ 22     const userAndSession = await p.session.findUnique(
    Error occurred during query execution:
    ConnectorError(ConnectorError { user_facing_error: None, kind: QueryError(Error { kind: Db, cause: Some(DbError { severity: "ERROR", parsed_severity: Some(Error), code: SqlState(E26000), message: "prepared statement \"s56\" does not exist", detail: None, hint: None, position: None, where_: None, schema: None, table: None, column: None, datatype: None, constraint: None, file: Some("prepare.c"), line: Some(485), routine: Some("FetchPreparedStatement") }) }) }) {
      message: '\n' +
        'Invalid `p.session.findUnique()` invocation in\n' +
        '/Users/neilgirardi/Projects/Personal/getitapp/node_modules/@next-auth/prisma-adapter/dist/index.js:22:52\n' +
        '\n' +
        '  19 linkAccount: (data) => p.account.create({ data }),\n' +
        '  20 unlinkAccount: (provider_providerAccountId) => p.account.delete({ where: { provider_providerAccountId } }),\n' +
        '  21 async getSessionAndUser(sessionToken) {\n' +
        'β†’ 22     const userAndSession = await p.session.findUnique(\n' +
        'Error occurred during query execution:\n' +
        'ConnectorError(ConnectorError { user_facing_error: None, kind: QueryError(Error { kind: Db, cause: Some(DbError { severity: "ERROR", parsed_severity: Some(Error), code: SqlState(E26000), message: "prepared statement \\"s56\\" does not exist", detail: None, hint: None, position: None, where_: None, schema: None, table: None, column: None, datatype: None, constraint: None, file: Some("prepare.c"), line: Some(485), routine: Some("FetchPreparedStatement") }) }) })',
      stack: 'Error: \n' +
        'Invalid `p.session.findUnique()` invocation in\n' +
        '/Users/neilgirardi/Projects/Personal/getitapp/node_modules/@next-auth/prisma-adapter/dist/index.js:22:52\n' +
        '\n' +
        '  19 linkAccount: (data) => p.account.create({ data }),\n' +
        '  20 unlinkAccount: (provider_providerAccountId) => p.account.delete({ where: { provider_providerAccountId } }),\n' +
        '  21 async getSessionAndUser(sessionToken) {\n' +
        'β†’ 22     const userAndSession = await p.session.findUnique(\n' +
        'Error occurred during query execution:\n' +
        'ConnectorError(ConnectorError { user_facing_error: None, kind: QueryError(Error { kind: Db, cause: Some(DbError { severity: "ERROR", parsed_severity: Some(Error), code: SqlState(E26000), message: "prepared statement \\"s56\\" does not exist", detail: None, hint: None, position: None, where_: None, schema: None, table: None, column: None, datatype: None, constraint: None, file: Some("prepare.c"), line: Some(485), routine: Some("FetchPreparedStatement") }) }) })\n' +
        '    at RequestHandler.handleRequestError (/Users/neilgirardi/Projects/Personal/getitapp/node_modules/@prisma/client/runtime/index.js:30855:13)\n' +
        '    at RequestHandler.request (/Users/neilgirardi/Projects/Personal/getitapp/node_modules/@prisma/client/runtime/index.js:30834:12)\n' +
        '    at async PrismaClient._request (/Users/neilgirardi/Projects/Personal/getitapp/node_modules/@prisma/client/runtime/index.js:31812:16)\n' +
        '    at async getSessionAndUser (/Users/neilgirardi/Projects/Personal/getitapp/node_modules/@next-auth/prisma-adapter/dist/index.js:22:36)',
      name: 'Error'
    }
    [next-auth][error][SESSION_ERROR] 
    <https://next-auth.js.org/errors#session_error> 
    Invalid `p.session.findUnique()` invocation in
    /Users/neilgirardi/Projects/Personal/getitapp/node_modules/@next-auth/prisma-adapter/dist/index.js:22:52
    
      19 linkAccount: (data) => p.account.create({ data }),
      20 unlinkAccount: (provider_providerAccountId) => p.account.delete({ where: { provider_providerAccountId } }),
      21 async getSessionAndUser(sessionToken) {
    β†’ 22     const userAndSession = await p.session.findUnique(
    Error occurred during query execution:
    ConnectorError(ConnectorError { user_facing_error: None, kind: QueryError(Error { kind: Db, cause: Some(DbError { severity: "ERROR", parsed_severity: Some(Error), code: SqlState(E26000), message: "prepared statement \"s56\" does not exist", detail: None, hint: None, position: None, where_: None, schema: None, table: None, column: None, datatype: None, constraint: None, file: Some("prepare.c"), line: Some(485), routine: Some("FetchPreparedStatement") }) }) }) Error: 
    Invalid `p.session.findUnique()` invocation in
    /Users/neilgirardi/Projects/Personal/getitapp/node_modules/@next-auth/prisma-adapter/dist/index.js:22:52
    
      19 linkAccount: (data) => p.account.create({ data }),
      20 unlinkAccount: (provider_providerAccountId) => p.account.delete({ where: { provider_providerAccountId } }),
      21 async getSessionAndUser(sessionToken) {
    β†’ 22     const userAndSession = await p.session.findUnique(
    Error occurred during query execution:
    ConnectorError(ConnectorError { user_facing_error: None, kind: QueryError(Error { kind: Db, cause: Some(DbError { severity: "ERROR", parsed_severity: Some(Error), code: SqlState(E26000), message: "prepared statement \"s56\" does not exist", detail: None, hint: None, position: None, where_: None, schema: None, table: None, column: None, datatype: None, constraint: None, file: Some("prepare.c"), line: Some(485), routine: Some("FetchPreparedStatement") }) }) })
        at RequestHandler.handleRequestError (/Users/neilgirardi/Projects/Personal/getitapp/node_modules/@prisma/client/runtime/index.js:30855:13)
        at RequestHandler.request (/Users/neilgirardi/Projects/Personal/getitapp/node_modules/@prisma/client/runtime/index.js:30834:12)
        at async PrismaClient._request (/Users/neilgirardi/Projects/Personal/getitapp/node_modules/@prisma/client/runtime/index.js:31812:16)
        at async getSessionAndUser (/Users/neilgirardi/Projects/Personal/getitapp/node_modules/@next-auth/prisma-adapter/dist/index.js:22:36) {
      name: 'GetSessionAndUserError',
      code: undefined
    }
    The app is running on Supabase. Restarting the app server makes it go away. Any ideas on how to troubleshoot / fix this? Thanks in advance!
    πŸ‘€ 1
    βœ… 1
    v
    n
    • 3
    • 6
  • o

    Ofek Gabay

    10/17/2022, 4:07 AM
    Hi everyone, I'm Ofek, a developer in Amplication, we use Prisma in our generated code for the users, and I want to get to the gats of the Prisma schema. Do you have any AST package that parses the schema and mutates it?
    βœ… 1
    n
    • 2
    • 3
  • j

    javier g

    10/17/2022, 9:12 AM
    Hi everyone, I have this error I can't resolve with using mongodb Error: P1013 The provided database string is invalid. An invalid argument was provided: Database must be defined in the connection string in database URL.
    βœ… 1
    n
    • 2
    • 4
  • h

    Harris Rothaermel

    10/17/2022, 4:54 PM
    What would be the best way to implement a searchbar where I want users to be able to search by any field in all objects that are associated with them in a db?
    πŸ‘€ 2
    βœ… 1
    r
    v
    • 3
    • 16
  • d

    David Ressler

    10/17/2022, 6:02 PM
    Hello! I am trying to leverage Prisma within a Cloud Run container and through connecting to a Cloud SQL PostgreSQL instance. Within my Cloud Run container, I am able to connect to my Cloud SQL database without Prisma by doing something like this (using
    knex
    as an example):
    Copy code
    knex({
      client: 'pg',
      connection: {
        user: '...',
        password: '...',
        database: '...',
        host: `/cloudsql/${INSTANCE_NAME}`
      }
    })
    I have so far been unable to connect to Prisma using the
    /cloudsql
    reference to my Cloud SQL instance, though. I am able to connect if I run the Cloud SQL Auth proxy locally and do something like this:
    Copy code
    datasource db {
      provider = "postgresql"
      url      = "postgresql://...:...@localhost/...?host=127.0.0.1"
    }
    But I would ideally love to be able to connect to Prisma using the
    /cloudsql
    host name. Does anyone know if this is possible?
    πŸ‘€ 1
    r
    v
    • 3
    • 6
  • l

    Lucas Pelegrino

    10/17/2022, 6:07 PM
    Hi there, people! Currently building a POC using Prisma to present it to my team as an alternative to TypeORM. Our stack includes NestJS and we have a user module with authentication. We also use entities with class-transformer. The Prisma generated types works great and it’s really helpful, but in this case I have been using @Exclude() on my entities to remove the password. But it’s not working properly, not excluding the password. My files currently look like this:
    Copy code
    import { ApiProperty } from '@nestjs/swagger';
    import { User } from '@prisma/client';
    import { Exclude } from 'class-transformer';
    
    export class UserEntity implements User {
      ...
    
      @Exclude()
      password: string;
    
      ...
    
      // If I add this constructor and call `return new UserEntity(user) at the end of my services it works, when using TypeORM that wasn't necessary.
      constructor(partial: Partial<UserEntity>) {
        Object.assign(this, partial);
      }
    }
    A simple service I wrote just to validade password exclusion
    Copy code
    @Injectable()
    export class GetUserService {
      constructor(private prisma: PrismaService) {}
    
      async get(id: string): Promise<UserEntity> {
        const user = await this.prisma.user.findUnique({ where: { id } });
    
        // Again, in order for the @Exclude option to work, I have to do this.
        return new UserEntity(user);
      }
    }
    NOTE: I have Nest global serialization enabled on the app. My goal is to have password removed from the response without having to add the constructor in the entity, I did check Prisma Docs and read about excluding fields, but the options there are to open to errors just as this one I’m using. Manually removing password using the select option also gives room to error, as I have to add all other fields every time, excluding only password. So, anyone have other suggestions on how I can solve this, am I missing something? Appreciate feedback.
    βœ… 1
    s
    n
    • 3
    • 4
  • s

    Stanislav Pugach

    10/17/2022, 10:26 PM
    Hi everyone. We are using Blitz to build a multitenant application. One of our options (for reasons) is doing multitenancy manually, by having something like
    Copy code
    model Tenant {
      id      Int      @id @default(autoincrement())
      name    String
    
      widgets  Widget[]
    }
    
    model Widget {
      tenant    Tenant @relation(fields: [tenantId], references: [id])
      tenantId  Int
      id        Int     @default(autoincrement())
      @@id([tenantId, id])
      //...
    }
    The syntax seems to require the
    widgets  Widget[]
    field in the
    Tenant
    model, and the question is: what would happen if the number of total records in the
    Widget
    table is large? Is the array a proactively loaded construct, i.e. would it load the entirety of the DB at all times? Or is the array just syntactic sugar over something that is smarter than that? Also, is there a way to not require that array field? The schema is likely to be rather large, and the
    Tenant
    model is going to be just lines and lines of those array fields... Disclaimer: I know there are multitenancy plugins, I'm just comparing the alternatives.
    βœ… 1
    d
    • 2
    • 6
  • d

    Dave Edelhart

    10/17/2022, 10:59 PM
    question: do you have to change any fields in upsert? can you do, eg.,
    prisma.account.upsert({where: {email: email}, update: {}, create: {email: email}})
    and not modify but return the acocunt unchanged if it exists?
    βœ… 1
    n
    • 2
    • 2
  • h

    Harry Lee

    10/18/2022, 5:01 AM
    Hi everyone! I have one question. Is there any ways to implement Declarative Transaction Management (like
    @transactional
    in spring)? I’m using Interactive Transaction feature from prisma but it is quit bothersome when especially repository layer is separated
    Copy code
    await prisma.$transaction(async (prisma) => {
        // ...
        await createUser(prisma, ...)
        await createReservation(prisma, ...)
        await updateLocation(prisma, ...) 
    })
    βœ… 1
    n
    • 2
    • 2
  • a

    abdoaligomaa107

    10/18/2022, 6:12 AM
    my database is deleted but i have the migration files , and i create a new database , what should i do now ? prisma migration dev or prisma migration deploy
    πŸ‘€ 1
    n
    v
    d
    • 4
    • 6
  • o

    Odysseas Pap

    10/18/2022, 1:55 PM
    I have this schema
    Copy code
    model Column {
        id        String  @id @default(cuid())
        title     String
    
        projectId String
        project   Project @relation(fields: [projectId], references: [id], onDelete: Cascade)
        cards     Card[]
    }
    
    model Card {
        id          String @id @default(cuid())
        title       String
        description String?
    
        columnId    String
        column      Column @relation(fields: [columnId], references: [id], onDelete: Cascade)
    }
    I'm basically making a trello clone. I'm using react-beautiful-dnd to rearrange the cards on a column, I thought the easiest way to update the database would be something like this
    Copy code
    const result = await ctx.prisma.column.update({
            where: {
              id: input.colId,
            },
            data: {
              cards: {
                set: input.cards
              },
            },
            include: {
              cards: true
            }
          });
    input.cards
    has a type of Card[]
    Copy code
    export type Card = {
      id: string
      title: string
      description: string | null
      columnId: string
    }
    But it doesn't work saying it got a wrong value... How do I set the cards field with new array of card objects?
    πŸ‘€ 1
    n
    v
    • 3
    • 6
  • j

    Jose

    10/18/2022, 4:22 PM
    I'm trying to create a different database name per branch to make sure we can test different branches in isolation. Is it possible to extend/compose the environment variable for
    DATABASE_URL
    ?
    Copy code
    datasource db {
      provider = "postgresql"
      url      = env(`postgresql://${POSTGRES_USER}:${POSTGRES_PASSWORD}@${POSTGRES_HOST}:${POSTGRES_PORT}/${BRANCH_NAME}?schema=public`)
    }
    According to the docs, we either set the full string, or a single environment variable (but in this case we want to read the branch name for each environment)
    πŸ‘€ 1
    n
    v
    • 3
    • 7
  • j

    Jose

    10/18/2022, 4:26 PM
    ^ And a follow-up question related to this case: Is it possible to set up a script that only seeds the database when a new one is created? It's not obvious to detect when a new database is created from scratch vs. a migration is applied to an existing one
    βœ… 1
    n
    • 2
    • 3
  • m

    Matthew Knight

    10/18/2022, 4:54 PM
    Is there a way to introspect programatically? I see some references in slack to a future SDK, but I can't find anything that would allow me to introspect without the CLI.
    βœ… 1
    n
    v
    • 3
    • 4
  • s

    Steven Kuck

    10/18/2022, 5:41 PM
    I've been bitten multiple times by customers in our production environment now by this issue I opened up last week. https://github.com/prisma/prisma/issues/15745 It's really painful that the client is case sensitive and causing Prisma Query Engine to panic.
    βœ… 1
    n
    • 2
    • 1
  • j

    Jacob Martin

    10/18/2022, 6:55 PM
    We migrated several of our huge existing platforms from TypeORM to Prisma in production.
    l
    n
    • 3
    • 15
  • a

    AJ Holloway

    10/18/2022, 6:49 PM
    This hurts.
    Copy code
    Filtering on object key values within an array is only supported by the MySQL database connector.
    πŸ˜… 1
    n
    • 2
    • 1
  • z

    Zakaria Mofaddel

    10/18/2022, 7:23 PM
    Is anybody using Prisma v4 with GraphQL Nexus?
    πŸ’¬ 1
  • s

    Sebastian Gug

    10/18/2022, 8:17 PM
    Copy code
    // returning the search result
            return await this.client.user.findUnique({where: {email}});
    what's the right way of doing this? currently throws
    'email' does not exist in type 'UserWhereUniqueInput'.
    -- what's the expected way?
    βœ… 1
    k
    n
    • 3
    • 7
  • s

    Sebastian Gug

    10/18/2022, 8:17 PM
    Copy code
    model User {
      id                   String    @id @default(uuid())
      email                String    @unique
    my user is defining email as a unique thing
    βœ… 1
  • k

    Kevin Lanthier

    10/18/2022, 8:29 PM
    Hello guys - I'm looking at anything that could help with Idle connection management I'm running off Digital Ocean managed PGSQL db and whenever I use
    $transaction
    it leaves an idle connection afterwards. Code looks like that:
    Copy code
    const [items, count] = await this.prisma.$transaction([
          this.prisma.user.findMany({ ...args, include: userIncludes }),
          this.prisma.user.count({ where: computedWhere }),
        ]);
    πŸ‘€ 1
    n
    v
    • 3
    • 4
1...633634635636637Latest