https://www.prisma.io/ logo
Join SlackCommunities
Powered by
# prisma-client
  • p

    Philipp Klein

    08/08/2022, 1:45 PM
    Hello all! I wonder if its possible with prisma to make a IN query where i can define pairs of values matching in two columns at the same time. Pseudocode:
    ... where: {in: [{columnA: 1, columbB:2}, {columnA: 15, columbB:17}]} ...
    ✅ 1
    n
    • 2
    • 2
  • r

    Robert Woods

    08/09/2022, 4:36 PM
    Hi there, when I generate my prisma client, it doesn't seem to add the relation models. For example:
    Copy code
    export type LessonsCompleted = {
      id: number
      watchedVideo: boolean
      readText: boolean
      completionDate: Date | null
      userId: string
      lessonId: number
    }
    has a relation to
    Lesson
    , however the generate command doesn't add that to the client. I can manually add
    lesson: Lesson
    to my
    LessonsCompleted
    model and I'm able to select the lesson as needed, however when I regenerate my client, that is undone and the field is no longer on the model. Is there anyway to get around this? Am I misunderstanding something?
    ✅ 1
    n
    • 2
    • 2
  • r

    Rich Starkie

    08/11/2022, 11:36 AM
    Hey folks, I'm trying to specify columns from related tables to be shown, rather than every column I've got this working but its showing everything from all the tables mentioned
    Copy code
    const shelfContents = await prisma.libraryShelves.findUnique({
        where: {
            shelfId: id
        },
        include: {
            shelfRelease: {
                include: {
                    releaseArtists: true,
                    releaseRecordLabel: true,
                    releaseFormats: true,
                    releaseStyle: true,
                    releaseGenres: true,
                    releaseCurrentLocation: true,
                    }
                },
            },
    });
    every time I add a
    select: {}
    statement to any of the included tables, or even to
    libraryShelves
    under the
    where@{}
    the whole statement falls apart and just returns the clientversion information can anyone please advise?
    👀 1
    a
    v
    • 3
    • 2
  • r

    Rich Starkie

    08/11/2022, 12:42 PM
    also having problems with 2
    where
    conditions ... eg:
    Copy code
    where:{
    shelfId: id,
    shelfPublished: true
    }
    shelfPublished is a Boolean (probably obvious but thought worth mentioning)
    👀 1
    a
    v
    • 3
    • 9
  • r

    Rich Starkie

    08/11/2022, 6:55 PM
    @Austin lets start with the probably easier one ...
  • r

    Rich Starkie

    08/11/2022, 6:57 PM
    Code Fragment:
    Copy code
    where:{
    shelfId: id,
    shelfPublished: true
    }
    Expected Behaviour ... To Filter by BOTH
    where
    statements Actual Behaviour ... returns the following
    Copy code
    "client-version" : "4.1.xxxx"
  • p

    Philipp Klein

    08/12/2022, 11:56 AM
    Hello, I have a question related to "JSON: Filtering by null Values" https://www.prisma.io/docs/concepts/components/prisma-client/working-with-fields/working-with-json-fields#filtering-by-null-values I follow a similar schema. When i try to do the
    Copy code
    prisma.foo.findMany({
      where: {
        data: {
          meta: Prisma.AnyNull,
        },
      },
    })
    I get Object literal may only specify known properties, and 'data' does not exist in type 'FooWhereInput' if i try to do:
    Copy code
    prisma.foo.findMany({
      where: {
         meta: Prisma.AnyNull,
      },
    })
    I get:
    Copy code
    [tsserver 2322] [E] Type 'AnyNull' is not assignable to type 'JsonNullableFilter'.
    What am I missing?
    ✅ 1
    n
    • 2
    • 4
  • l

    Luan Rodrigues

    08/12/2022, 3:05 PM
    Hello everyone, I am using prisma with multiple tenants, is there any way to filter the tenant ID on every query?
    👀 1
    n
    v
    • 3
    • 2
  • j

    Jeremy Hinegardner

    08/12/2022, 4:43 PM
    Just confirming here - the variable expansion that is done in prisma-client as documented here - https://www.prisma.io/docs/guides/development-environment/environment-variables#expanding-variables - it does not appear to do default value substitution although the documentation points to dotenv-expand which does.
    ✅ 1
    n
    • 2
    • 5
  • r

    Rich Starkie

    08/13/2022, 8:01 AM
    Hey Folks, hopefully someone can offer some advice / assistance on a problem I'm having .... Stack: Node / TS / Express / Prisma I'm trying to do a
    createMany
    with many relationships, which I know according to the prisma docs you can't do. I have been following the docs on the prisma site, it does the first (main)
    CreateMany
    then for any of the others in the same bit of script, I get an Error
    [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
    can anyone please advise how I should do the bulk import? I can post code snippet if it becomes necessary, and I'm happy to do a
    Live Share in VSC
    or a
    Code With Me in WebStorm
    if it is easier At this stage of the project, I can, just about get away with refactoring the data, but that would be a total pain in the ass and would need refactoring of other parts of the project that are completed ... possible, but impractical
    👀 1
    t
    n
    • 3
    • 2
  • i

    Ignacio Velasco

    08/16/2022, 2:48 PM
    Hi all, I have the following question, Im using a stored procedure using
    $queryRaw
    , my stored procedure returns two results, but I am only getting the last one. Is there any way to get both values?
    ✅ 1
    n
    v
    • 3
    • 9
  • g

    Guillermo David

    08/17/2022, 3:14 PM
    Hey folks, I'm using prism search, for the search in 2 columns of my table, firstName and lastName, but it gives me an error when I search for the same string in both fields.
  • g

    Guillermo David

    08/17/2022, 3:15 PM
    Copy code
    where: {
            firstName: { search: 'word' },
            lastName: { search: 'word' },
          } // this is an error
    n
    • 2
    • 1
  • g

    Guillermo David

    08/17/2022, 3:16 PM
    but when I try to use differents string in the firstName and lastname is correct the function
    ✅ 1
    n
    • 2
    • 6
  • d

    Dávid Korečko

    08/18/2022, 10:16 AM
    Hey guys, I've been struggling for a few days now. I am deploying a function to an AWS lambda, which uses the Prisma Client. I have been using the version 2 for quite some time and am trying to update to version 4, but even after updating all packages and generating DB, I'm always getting the @prisma/client did not initialize yet error. Any idea why this could be?
    ✅ 1
    r
    • 2
    • 18
  • d

    Dávid Korečko

    08/18/2022, 10:18 AM
    It's important to note that everything runs just fine locally
  • d

    Dávid Korečko

    08/18/2022, 10:18 AM
    And I'm storing the .prisma and @prisma folders in an AWS layer
  • g

    Gustavo

    08/19/2022, 3:58 AM
    Hi guys, I've got a hopefully not unique situation here (multi-tenant architecture), I'd appreciate any inputs/suggestions 🙂 I have developed an API running on nodejs. that is split into different packages, where each package has its own
    schema.prisma
    e.g.
    Copy code
    - project_folder
    -- migrate.js
    -- src
    ---- index.ts
    ---- packages
    ------- package_1
    ---------- index.ts
    ---------- prisma
    ------------- client
    ------------- migrations
    ------------- schema.prisma
    ------- package_2
    ---------- index.ts
    ---------- prisma
    ------------- client
    ------------- migrations
    ------------- schema.prisma
    package_1 > prisma > schema.prisma
    looks like:
    Copy code
    generator client {
        provider        = "prisma-client-js"
        previewFeatures = ["interactiveTransactions"]
        output          = "./client"
    }
    
    datasource db {
        provider = "mysql"
        url      = env("ORGANISATION_CONTEXT_DATABASE_URL")
    }
    ORGANISATION_CONTEXT_DATABASE_URL
    is always the same for a given env (dev, prod, etc...)
    package_2 > prisma > schema.prisma
    looks like:
    Copy code
    generator client {
        provider        = "prisma-client-js"
        previewFeatures = ["interactiveTransactions"]
        output          = "./client"
    }
    
    datasource db {
        provider = "mysql"
        url      = env("DATABASE_URL")
    }
    DATABASE_URL
    changes depending the user making a request. Everything locally works just fine. The issue I have is at the moment of applying migrations when deploying through github actions. At the moment I'm testing the following. Whenever everything has been deployed run the command:
    ci.yml
    Copy code
    - name: "Run migrations"
         run: yarn migrate
    package.json
    Copy code
    {
      "scripts": {
        "migrate": "node migrate.js"
      }
    }
    migrate.js
    Copy code
    process.env.ORGANISATION_CONTEXT_DATABASE_URL = 'postgressql://....'
    
    const organisationContextSchema='./src/packages/package_1/prisma/prisma.schema'
    const cmd1 = spawnSync('npx', ['prisma', 'generate', `--schema=${organisationContextSchema}`]);
    
    const cmd2 = spawnSync('npx', ['prisma', 'migrate', 'deploy', `--schema=${organisationContextSchema}`]);
    
    // HERE IS WHERE PROBLEMS HAPPEN!!!! :(
    const orgContDbClient = new PrismaClient({
        datasources: { db: { url: process.env.ORGANISATION_CONTEXT_DATABASE_URL } },
    });
    
    console.log('connected! Fetching orgs...');
    const dbOrgs = await orgContDbClient.organisation.findMany();
    
    console.log('dbOrgs: ', dbOrgs);
    Error:
    Error: @prisma/client did not initialize yet. Please run "prisma generate" and try to import it again.
    😞
    ✅ 1
    • 1
    • 1
  • p

    Pascal Sthamer

    08/19/2022, 3:49 PM
    After upgrading mysql to 8.0.30, prisma is no longer able to connect:
    Error querying the database: Server error: `ERROR 08S01 (1043): Bad handshake'
    I am unable to write a bug report right now, so just dropping a quick warning here, before you upgrade your mysql server.
    ✅ 1
    n
    • 2
    • 2
  • j

    Jacob Coker-Dukowitz

    08/19/2022, 11:14 PM
    TL;DR: If all calls to the prisma client are synchronous, are queries sent to a single instance of the Prisma client guaranteed to be in the same connection/session when using postgres? Background: I’d like to set a transactional advisory lock where i need some processing between queries. • I can’t use the Sequential Operations feature because i need processing between queries. • I can’t use the Interactive transactions feature because this is for production. • I’d prefer to use a transactional and not a general advisory lock on the db, because then we need to worry about cleaning up orphaned advisory locks in the unlikely but real scenario of a node dying without ‘unlocking’. Why can’t I just use this? Are queries sent to a single instance of the Prisma client not guaranteed to be in the same connection? Running in my repl, it appears to be the same connection.
    Copy code
    prisma.$queryRaw`BEGIN`
    prisma.$queryRaw`pg_advisory_xact_lock(5)`
    // code, processing
    prisma.$queryRaw`pg_advisory_xact_unlock(5)`
    prisma.$queryRaw`COMMIT`
    ✅ 1
    n
    • 2
    • 4
  • y

    Yann Buydens

    08/23/2022, 6:44 AM
    Hi everyone. I’m stuck with a slow query I’d like to speed up. TLDR; this query is super slow. What should I do to speed this query up? Can I do it by adding an index?
    Copy code
    prisma.concept.findMany({
        where: {
          dictionaryId: Number(dictId),
          name: {contains: foo}
        },
        include: {
          _count: {
            select: {
              declarations: true, // including this in the query makes it super slow
            },
          },
        }
      })
    I have a concept table and a declaration table. Concept and declaration have a many to many relationship. The declaration table has more than 500k rows, same goes for concept table. longer explanation: https://www.loom.com/share/ff8d3034898e4ad08b8d19f044d500fe
    j
    • 2
    • 9
  • f

    Florian Thelliez

    08/24/2022, 11:36 AM
    Hi I’m currently trying to upgrade to Prisma 4 and I’m having a little casting issues in some
    $queryRaw()
    Example query:
    Copy code
    const rows = await this.prismaClient.$queryRaw<
      { id: string; location: string }[]
    >(Prisma.sql`
      SELECT id, ST_AsGeoJSON(location) as location,
      FROM something
      WHERE id IN (${Prisma.join(ids)})
    `);
    I get some type errors I didn’t have in previous versions:
    Copy code
    ERROR: operator does not exist: uuid = text
    I’ve tried various way to cast my list of
    ids
    to uuids, but to no avail so far.
    Copy code
    IN (${Prisma.join(ids)}::uuid[]) IN (${Prisma.join(ids)})::uuid[]
    I wouldn’t mind some help there since I might be missing something simple 😅
    👀 1
    n
    • 2
    • 8
  • t

    Trey Holterman

    08/26/2022, 2:54 PM
    Hey! I’m struggling with a strange error creating a new item in a collection that I can’t seem to find anything on. Best explained with my schema files, the failing create call, and the errors that ensue. Here’s my schema for the idea of a ‘report’, which has to belong to a ‘team’.
    Copy code
    model Report {
      id            String        @id @default(auto()) @map("_id") @db.ObjectId
      ...
      team          Team          @relation(fields: [teamId], references: [id])
      teamId        String 
      ...
    }
    Here’s the Team:
    Copy code
    model Team {
      id                   String             @id @map("_id")
      ...
      reports              Report[]
      ...
    }
    I’ve tried creating a number of different ways. I thought the right way was as such:
    Copy code
    const report = await prisma.report.create({
            data: {
                id : newId.toString(),
                teamId:        teamId,
                ...
            },
        });
    Which gives error:
    Copy code
    "Parse errors: [Query parsing/validation error at Mutation.createOneReport.data.ReportCreateInput.team: A value is required but not set"
    Which I interpret to mean it’s missing the ‘team’ object. So I tried:
    Copy code
    const report = await prisma.report.create({
            data: {
                id : newId.toString(),
                ...
                teamId:        teamId,
                team: {
                    connect: {
                        id: teamId,
                    },
                },
                ...
            },
        });
    Which errors out telling me I shouldn’t be including team Id. (will include error in thread). But if I don’t invlude teamId it errors out telling me I should be using teamId. Very confusing since I used to be able to just add teamId in these types of situations
    ✅ 1
    • 1
    • 3
  • m

    Martin Janeček

    08/29/2022, 3:52 PM
    Hello 👋 Has anyone managed to build some kind of query builder or query composer? I've found this discussion in Prisma's repo, but it doesn't really have any answer: https://github.com/prisma/prisma/discussions/12047#discussioncomment-3501408 I've tried to describe my use-case in the comment there. Basically I'd like several small repository/service methods that take care of a single responsibility, and can be combined together into a single strongly-typed query/result. I'd be grateful for really any resource on how to design a DRY, reusable repositories/services with Prisma. Thanks!
    ✅ 1
    a
    • 2
    • 2
  • a

    Austin

    08/29/2022, 6:09 PM
    Hey Gautam! What versions of Prisma and TypeScript are you using?
    g
    • 2
    • 2
  • r

    Rich Starkie

    08/30/2022, 2:08 PM
    hey folks, I'm trying something new ... MongoDB i've managed to convert my schema into a mongo "happy" format, but when I try to write data, I'm getting some errors when I'm linking to documents in other collections
    Copy code
    //schema
    
    model activityLog {
      activityLogId      String                @id @map("_id") @default(uuid())
      activityLogType    activityLogType       @relation(fields: [activityLogTypeId], references: [activityLogType])
      activityLogTypeId  String                @db.ObjectId()
      activityLogMessage String                @db.String
      activityCompleted  Boolean               @default(false)
      createdAt          DateTime              @default(now()) @db.Timestamp
      updatedAt          DateTime              @default(now()) @db.Timestamp
    }
    
    model activityLogType {
      activityLogType     String                @id @map("_id")  @db.String
      createdAt           DateTime              @default(now()) @db.Timestamp
      updatedAt           DateTime              @default(now()) @db.Timestamp
      activityLog         activityLog[]
    }
    when I try to do
    Copy code
    await prisma.activityLog.create({
        data: {
          activityLogType: {
            activityLogType: "Start"
          },
          activityLogMessage: "Start Seeding",
          activityCompleted: true
        }
      })
    The
    Start
    document already exists in the
    activityLogTypes
    collection it complains that the
    activityLogType
    does not exist schema I'm probably doing something wrong, and its likely a n00b error for Mongo, but any help would be suggested.
    👀 1
    a
    • 2
    • 2
  • j

    James Fox

    08/30/2022, 5:31 PM
    Hi there - I noticed the release today with preview support for field reference support on query filters. Curious if this is a precursor or helps in any way to address this issue (sorting by foreign key fields): https://github.com/prisma/prisma/issues/5837
    ✅ 1
    n
    • 2
    • 1
  • c

    Casey Chow

    09/01/2022, 7:11 PM
    Looks like it’s working as intended. The only way to make this work is to select the value on both, otherwise there’s only one case where birthdate is a value so Typescript can’t safely let you use the property.
  • k

    Kay Khan

    09/05/2022, 2:10 PM
    Hi friends, i wanted to ask about naming convention of models and how it relates to reusing code and pulling/introspection. Let me explain the scenario. Folder structure
    Copy code
    /core/prisma/schema.prisma
    /lambda/prisma/schema.prisma
    Core - This folder contains some core logic and is often "shared" code used by folder
    lambda
    . Lambda folder is a serverless function more on that later.
    core/prisma/schema.prisma
    Copy code
    model Collection {
        id                String    @id @default(auto()) @map("_id") @db.ObjectId
        network           String
        contract_address  String    @unique
        @@map("collections")
    }
    The convention for declaring a model here is familiar to the docs. https://www.prisma.io/docs/concepts/components/prisma-schema - Singular with a capital first letter.
    core/models/collections.ts
    Inside of this file im doing some common functionality like finding, inserting etc. Note: the model name that is being used "collection". Generated by the prisma library based on schema.prisma.
    Copy code
    export const FindCollections = async () => {
        try {
            const contracts = await PrismaService.collection.findMany();
    
            return [contracts, null] as const;
        } catch (err) {
            Logger.error({ kind: "FindCollections", error: err.name, stack_trace: err.stack });
            return [null, err] as const;
        }
    };
    Up until now, there are no problems. Now lets introduce my lambda. I have this lambda folder which has my serverless function im going to deploy and i want to use "FindCollections" function within the core folder which has already been created. However in my lambda folder, i need to introspect the database and package the engine. but when i introspect the database the model name becomes a problem.
    lambda/prisma/prisma.schema
    Copy code
    model collections {
      id                String   @id @default(auto()) @map("_id") @db.ObjectId
      contract_address  String
      ...
    }
    You can now see its all lowercase with plural. Now with this introspected schema, my existing "FindCollections" function no longer works, because the model name is different.
    InsertCollections","stack_trace":"Error: Could not find mapping for model Collection\n
    What is the suggestion for this usecase? There are 2 solutions i can think of but im wondering what you guys think.
    ✅ 1
    h
    • 2
    • 1
  • n

    Niv Oppenhaim

    09/07/2022, 9:16 AM
    Hi! Is there anyway to use the prisma CLI to check if the remote schema matches the local one?
    h
    • 2
    • 3
1...1920212223Latest