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

    Atticus Curtis

    03/21/2022, 6:56 PM
    i've been stuck for a while and found this discussion without any answers, it matches my problem
    n
    • 2
    • 3
  • o

    Orcioly Andrade Alves

    03/22/2022, 2:05 AM
    Boa noite pessoal, Estou precisando verificar se já tem algum usuário com o mesmo email cadastro. Estou tendo o seguinte erro: [ERROR] 225009 UnhandledPromiseRejection: This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). The promise rejected with the reason "#<AppError>". Código CreateUserService.ts import { User } from '@prisma/client'; import { AppError } from '../shared/errors/AppError'; import prismaClient from '../prisma'; import { hash } from 'bcryptjs'; import { CreateUserDTO } from '../dtos/user/CreateUserDto'; class CreateUserService { async execute({ name, email, password, admin, }: CreateUserDTO): Promise<User> { const passwodHash = await hash(password, 8); const userAlreadyExists = await prismaClient.user.findUnique({ where: { email, }, }); if (userAlreadyExists) { throw new AppError('User already exists!'); } const user = await prismaClient.user.create({ data: { name, email, password: passwodHash, admin, }, }); return user; } } export { CreateUserService }; CÓDIGO AppError.ts: class AppError { public readonly message: string; public readonly statusCode: number; constructor(message: string, statusCode = 400) { this.message = message; this.statusCode = statusCode; } } export { AppError }; Se alguém puder me ajudar, agradeço!
    n
    • 2
    • 2
  • a

    alechko

    03/22/2022, 6:52 AM
    hi everyone! I’m trying prisma as a candidate for orm in a project that’s being converted from php to node, and while the other, more traditional orm’s look like they are more “featured”, I really like prisma schema definition and the auto generated client. however, I’m not sure about couple of things that might be a huge showstoppers: 1. I couldn’t find anything related to data migrations in the docs, for example, how would one launch a process based on completed schema migration? the
    prisma migrate
    command generates raw sql file and there’s no
    up
    method that could be used to launch a custom script or whatever to initiate a data migration process related to the schema process. is there a best practices how to do that with maybe
    prisma seed
    or some other method, or do I need to figure out on my own how to do that? 2. are
    UNION
    queries available from the client api or only by raw sql? 3. is there a way to specify db master/replicas and set the query to use a
    replica
    for reads and
    master
    for writes? (like Mikro-ORM) Thanks!
    n
    j
    • 3
    • 3
  • s

    s1w

    03/22/2022, 7:16 AM
    Hey folks, anyone able to help me properly model:
    Copy code
    model Item {
      id String @unique
    }
    
    model Set {
      additions Item[]
      removals Item[]
    }
    I can’t get the right combination of references and stuff between the two
    n
    o
    • 3
    • 7
  • d

    dhatGuy

    03/22/2022, 9:58 AM
    @default(crypt(genSaltSync(10), ""))
    GitHub copilot suggested that when defining a model and I want to know if it is possible. I have searched and I can't find an answer.
    n
    • 2
    • 2
  • o

    Orcioly Andrade Alves

    03/22/2022, 1:15 PM
    Bom dia @Nurul, fiz assim agora, fiz o teste pelo Insomnia e funcionou, porém ele apenas não retorna a mensagem caso o Usuário já exista. Você poderia me enviar um exemplo? Te agradeço muito!!!
    Copy code
    import { User } from '@prisma/client';
    import { AppError } from '../shared/errors/AppError';
    import prismaClient from '../prisma';
    import { hash } from 'bcryptjs';
    import { CreateUserDTO } from '../dtos/user/CreateUserDto';
    
    class CreateUserService {
      async execute({
        _name_,
        _email_,
        _password_,
        _admin_,
      }: _CreateUserDTO_): _Promise_<_User_ | _undefined_> {
        const passwodHash = await hash(_password_, 8);
    
        const userAlreadyExists = await prismaClient.user.findUnique({
          where: {
            email,
          },
        });
    
        if (!userAlreadyExists) {
          try {
            const user = await prismaClient.user.create({
              data: {
                name,
                email,
                password: passwodHash,
                admin,
              },
            });
            return user;
          } catch (error) {
            throw *new* AppError('User already exists!');
          }
        }
      }
    }
    
    export { CreateUserService };
    n
    • 2
    • 6
  • j

    Julius

    03/22/2022, 1:25 PM
    Hey, can someone help me with my Issue on GitHub? Somehow npx prisma generate doesnt work at all. 😞 https://github.com/prisma/prisma/discussions/12475
    n
    • 2
    • 1
  • u

    user

    03/22/2022, 2:12 PM
    👉 What's new in Prisma (v3.12.0) --

    https://www.youtube.com/watch?v=TGMF8ykS29M▾

    -- Niko and Alex from the Prisma team discuss the latest 3.10.0 release of Prisma and other news from the Prisma ecosystem. Tune in to learn about new releases, how to upgrade, planned features, and other interesting bits from the Prisma world.
  • u

    user

    03/22/2022, 2:14 PM
    👉 What's new in Prisma (v3.13.0) --

    https://www.youtube.com/watch?v=mzWBmhWluKk▾

    -- Niko and Alex from the Prisma team discuss the latest 3.13.0 release of Prisma and other news from the Prisma ecosystem. Tune in to learn about new releases, how to upgrade, planned features, and other interesting bits from the Prisma world.
  • d

    Daniel Mahon

    03/22/2022, 6:56 PM
    Whats a good way to debug
    Killed
    prisma exceptions?…. Im qeurying a large data set 3mil+ (indexed) but even locally prisma seems to crash when trying to return anything larger than a few thousand records. I cant seem to find any other error message. When enabled prisma logging the only thing different is it doesnt print out the “query” to console, like it does with the previous ones. Thoughts? EDIT: Nevermind, I think it has something to do with my local docker setup, not specifically prisma.
    👍 1
  • a

    Adam

    03/22/2022, 7:09 PM
    I’m upgrading from
    v2.27.0
    to the latest
    v3.11.0
    in typescript/node, and I’m having issues with
    Prisma
    Keeping the previous connection string when starting a new Integration Test. Is there something else I should do to force-reset the connection string that prisma is using? I know the example docs show to call
    delete
    on everything, but that seemed excessive and painstaking. So I simply generate a new schema (
    postgres
    ) for each test suite, keeps it nice and clean. I override the
    Jest
    NodeEnvironment
    to create a new random connection string. This was working fine in v2.27. Now the below code will fail tests because
    prisma
    will try to be querying a schema from a previous test and it doesn’t exist. I am also using
    --runInBand
    with jest to run tests sequentially
    Copy code
    class PrismaTestEnvironment extends NodeEnvironment {
      connectionString?: string;
    
      schema?: string;
    
      app?: ExpressType;
    
      constructor(config: Config.ProjectConfig) {
        //@ts-ignore
        super(config);
    
        // Generate a unique schema identifier for this test context
        this.schema = stringGenerator();
        //pseudo-code, set random schema on DB_URL ENV
          this.global.process.env.DB_URL = `{myConnectionString}/${this.schema}`
          process.env.DB_URL = `{myConnectionString}/${this.schema}`
    
      }
    
      public async setup(): Promise<void> {
        process.env.DB_URL = this.connectionString;
        this.global.process.env.DB_URL = this.connectionString;
        forceResetPrisma();
    
        // Run the migrations to ensure our schema has the required structure
        try {
          const out = await promisifiedExec(
            `${prismaBinary} db push --force-reset`
          );
    
          <http://this.app|this.app> = await initExpress();
          <http://this.global.APP|this.global.APP> = <http://this.app|this.app>;
          
        } catch (e) {
          console.error(e);
          throw e;
        }
    
        return super.setup();
      }
    
      public async teardown(): Promise<void> {
        const prismaClient = getPrisma();
        await prismaClient.$executeRawUnsafe(
          `drop schema if exists "${this.schema}" cascade`
        );
        await prismaClient.$disconnect();
        await super.teardown();
      }
    }
    
    export default PrismaTestEnvironment;
    //Prisma Generator File
    Copy code
    import { PrismaClient, Prisma } from '@prisma/client';
    
    let db: PrismaClient;
    const DefaultLogLevels: Prisma.LogLevel[] = ['info', 'warn', 'error'];
    
    export const getPrisma = (log: Array<Prisma.LogLevel> = DefaultLogLevels) => {
      if (!db) {
        forceResetPrisma(log);
      }
      return db;
    };
    
    export const hasPrisma = () => !!db;
    
    /**
     * Force reset the DB instance using the current @param DB_URL environment var
     * @param log
     * @returns
     */
    export const forceResetPrisma = (
      log: Array<Prisma.LogLevel> = DefaultLogLevels
    ) => {
      console.log(`[PRISMA] Generating Client with log levels ${log.join(',')} `);
      try {
        db = new PrismaClient({
          log,
        });
      } catch (e) {
        console.error(e);
        throw e;
      }
      return db;
    };
    j
    • 2
    • 1
  • b

    ben aldrich

    03/22/2022, 8:26 PM
    Hi All, new to using Prisma and loving it so far! I wondered if its possible to limit the number of rows returned from a search and also the same if you are to use an 'include' to bring in another table of data?
    👍 1
  • b

    ben aldrich

    03/22/2022, 8:28 PM
    Copy code
    const allUsers = await prisma.user.findMany({
        include: { 
          posts: true,
          limit: 10 // <--- Something like this
        },
      })
    n
    • 2
    • 1
  • p

    Philipp Minder

    03/22/2022, 10:32 PM
    Hi guys . IM Just wondering if im getting any benefits to use connect instead directly set the relation id?
    👀 1
    n
    • 2
    • 2
  • k

    Kenneth Gitere

    03/23/2022, 5:06 AM
    Hi guys. Is there like a wiki for using Prisma with projects that use vite as a bundler? I recently had an issue building a SvelteKit app because I was importing an enum from
    @prisma/client
    . Idk how often other people faced such an issue so I was thinking I could add to any existing wiki on it as a potential fix.
    👍 1
    n
    • 2
    • 2
  • k

    Kenneth Gitere

    03/23/2022, 5:06 AM
    Also now that prisma is in v3, maybe the group's discussion could be updated 😉
  • k

    Kay Khan

    03/23/2022, 8:48 AM
    I have a long running script where for each i need to fetch some data from the database. However after a while i get this
    GenericFailure
    and i'm not really too sure what is happening here..
    Copy code
    export const GetReachForServiceIds = async (serviceIds: string[], startDate: Date, endDate: Date) => {
        try {
            const result = await PrismaService.reach_growth.findMany({
                where: { service_id: { in: serviceIds }, date: { gte: startDate, lte: endDate } },
            });
    
            return [result, null] as const;
        } catch (err) {
            Logger.error({ kind: "leaderboard_reach", method: "GetReachForServiceIds", error: err, stack_trace: err.stack });
            return [null, err] as const;
        }
    };
    Copy code
    Invalid `PrismaService.reach_growth.findMany()` invocation in
    /home/kay/checkpoint/leaderboards/src/reach/reach.service.ts:19:57
    
      16 
      17 export const GetReachForServiceIds = async (serviceIds: string[], startDate: Date, endDate: Date) => {
      18     try {
    → 19         const result = await PrismaService.reach_growth.findMany(
      
        at Object.request (/home/kay/checkpoint/leaderboards/node_modules/@prisma/client/runtime/index.js:39818:15)
        at async PrismaClient._request (/home/kay/checkpoint/leaderboards/node_modules/@prisma/client/runtime/index.js:40646:18)
        at async GetReachForServiceIds (/home/kay/checkpoint/leaderboards/src/reach/reach.service.ts:19:24)
        at async LeaderboardReach (/home/kay/checkpoint/leaderboards/src/reach/leaderboard-reach.ts:23:37)
        at async Main (/home/kay/checkpoint/leaderboards/src/reach/main.ts:9:9) {
      code: 'GenericFailure',
      clientVersion: '3.11.0',
      meta: undefined
    j
    • 2
    • 1
  • n

    nikolasburk

    03/23/2022, 9:12 AM
    set the channel topic: General Discussions about Prisma [Looking for Prisma 1? Join the #prisma1 channel!]
  • d

    Dhananjay Takalkar

    03/23/2022, 10:55 AM
    Can we use case when in prisma query ?
    n
    • 2
    • 2
  • j

    Jonas Rothmann

    03/23/2022, 1:02 PM
    Why can i suddenly no longer use PrismaClient as a type?
    n
    • 2
    • 2
  • a

    Austin Zentz

    03/23/2022, 2:03 PM
    Anyone have experience with Prisma and memory (RAM) usage creeping up? I'm on Heroku and see memory usage creep up especially as I use Prisma to query for many records. It doesn't seem to have a performance impact, from the testing I've been able to do.
    p
    j
    • 3
    • 7
  • a

    Adam Kaczmarek

    03/23/2022, 3:02 PM
    hey all! I'm looking to do some more advanced filtering on JSON objects than what is currently provided by prisma (https://www.prisma.io/docs/reference/api-reference/prisma-client-reference#string_contains). Does anyone have an example of implementing a custom filter etc?
    n
    • 2
    • 2
  • m

    motiondev

    03/23/2022, 3:47 PM
    Hey Prisma community, just wondering if there is a better solution for casting a id to BigInt in a Prisma operation.
    return ctx.prisma.dataProvider.update({
    data: {
    name: args.data?.name,
    description: args.data?.description,
    },
    where: {
    id: BigInt(args.data.id), // <===== I have to do this to every Prisma operation where I work with IDS
    },
    });
    Is there something like a way to extend models to accept id as string and cast it at model level with BigInt(id)? Thanks in advance!
    prisma cool 1
    💭 1
    a
    • 2
    • 2
  • j

    Julian

    03/23/2022, 4:16 PM
    Hey guys what's the best way to generate statistics data in Prisma, for example order counts or total revenue per month? From an
    order
    table for example
    a
    • 2
    • 1
  • s

    Seraphina Orsini

    03/23/2022, 7:07 PM
    Hey folks! The lack of support for the
    MultiSubnetFailover
    for sqlserver is blocking my team and I would love to help contribute a fix if possible. It appears like it may be a simple fix here, but would love to chat with someone on if that is the right approach before jumping in (or if there are any other expected blockers). GH Issue here.
    n
    • 2
    • 3
  • g

    Glaucia Lemos

    03/23/2022, 9:17 PM
    Folks, a question: Prisma has support the ability to specify which index type should be used? cause it seems Prisma doesn't allow to define which type of Primary Key one can use, and it default to a CLUSTERED index to support the primary key, which is best when data is ordered, but the UUID generate data with random order. Question: in this case an INT with an autoincrement() attribute would be better? cc: @Alex Ruheni @nikolasburk
    j
    • 2
    • 4
  • b

    Bret emm

    03/23/2022, 10:40 PM
    How do i show all my data “users” that have been added to a table?
    n
    • 2
    • 1
  • e

    ezeikel

    03/23/2022, 11:37 PM
    Hey all 👋🏿 has anyone used
    findRaw
    with mongodb? The raw query returns an empty array but the other query returns all users as expected. Am I doing something wrong?
    Copy code
    const rawUsers = await prisma.user.findRaw(); // empty array
      const users = await prisma.user.findMany(); // all users as expected
    n
    • 2
    • 2
  • h

    Hamin Lee

    03/24/2022, 5:14 AM
    Has anyone used prisma and appwrite.io together? I've seen a lot of people using supbase and prisma together. Appwrite is also a firebase installation project like supbase, which has a simple structure without having to create a sql query directly. If might be using both appwrite and prisma, it's easier to use ORM through appwrite and query through prisma, so I suddenly think it'll be much more comfortable. I wonder what everyone thinks.
    n
    • 2
    • 2
  • a

    A. Sauder

    03/24/2022, 6:30 AM
    Hello together I don't know if I just didn't understand something basic, or if prisma just doesn't offer it that way. Namely, I have for example a user who can have multiple cars via a 1:n. If I now read the user and set the connection to the cars to true via includes, I get the user which has all cars in the field "cars". If I now add another auto in this field in the GUI, and send the user object back to the backend, I currently take apart the user object to store the pure user, and then the cars. Is there no way to tell prisma directly "hey, here I have the user's cars, see which ones need to be deleted, which ones get an update, and which ones need to be recreated"? Currently I get the autos that exist now, and make different filters on them. This results in the cars to be deleted, the ones that are new and the ones that get an update. Here I would be very happy for tips.
    n
    • 2
    • 3
1...556557558...637Latest