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

    Nimish Gupta

    06/30/2021, 1:48 PM
    Hello prisma team, Second question for the day 😅 . Question is again related to raw queries. So I have the below model
    Copy code
    model Test {
      id        String   @id @default(uuid())
      name      String   @unique
      values    String[]
      // common fields
      createdAt DateTime @default(now()) @map("created_at")
      updatedAt DateTime @default(now()) @updatedAt @map("updated_at")
    
      @@map("test")
    }
    and I am using below code snippet in node.js
    Copy code
    async function main() {
    	await prisma.$connect();
    
    	await prisma.test.deleteMany();
    
    	await prisma.test.create({ data: { name: 'current_value' } });
    	const values = ['first', 'second'];
    
    	const allUpdateQuery = await prisma.$queryRaw(
    		`UPDATE test set values = $1`,
    		values
    	);
    	console.log(`Successfully runs allUpdateQuery`);
    
    	try {
    		const names = ['current_value'];
    		const partialUpdateQuery = await prisma.$queryRaw(
    			`UPDATE test set values = $1 where name IN $2`,
    			values,
    			names
    		);
    		console.log(`Successfully runs partialUpdateQuery`);
    	} catch (error) {
    		console.log(error);
    		/**
    		 *  Raw query failed. Code: `42601`. Message: `db error: ERROR: syntax error at or near "$2"`
    			{
    				code: 'P2010',
    				clientVersion: '2.26.0',
    				meta: {
    					code: '42601',
    					message: 'db error: ERROR: syntax error at or near "$2"'
    				}
    		 */
    	}
    	process.exit();
    }
    So while adding an array filter while updating the model is throwing an error. Like parameterized array is working correct while setting data in update query but throwing syntax error while filtering the update query. Do I have to convert the js array into postgres syntax array (
    {current_value,new_value}
    ) and then pass as parameter or something else I am missing here?
    r
    • 2
    • 3
  • g

    Gonzalo Moreno

    06/30/2021, 2:58 PM
    Hello everyone 👋, has anyone managed to deploy a Next.js+Prisma app to Google App Engine Standard?? Cannot get prisma client started there.
  • a

    Aman Tiwari

    06/30/2021, 4:52 PM
    prisma 2 + typegraphql + express-graphql what do you think? is it good enough? [10:21 PM] what is the different between express-graphql and apollo-server [10:21 PM] i think express-graphql is better what do you think?
    т
    • 2
    • 1
  • l

    Lars Ivar Igesund

    06/30/2021, 6:32 PM
    @Aman Tiwari I use apollo with express and it works just fine
  • y

    Yrobot

    07/01/2021, 2:24 AM
    Hello guys!
    👋🏽 1
    👋 1
  • y

    Yrobot

    07/01/2021, 2:28 AM
    Copy code
    console.log('Hello World!');
  • a

    Arun Kumar

    07/01/2021, 5:43 AM
    Is it possible to make primsa accept only the object fields it requires. I don't want to individually feed the
    create
    method. From the front end I get an object and want to pass it to
    create
    . Prisma should be smart enough to accept only the fields it requires.
    r
    • 2
    • 1
  • d

    dhatGuy

    07/01/2021, 6:02 AM
    Is there a way to use different database for testing?
    r
    • 2
    • 1
  • j

    jasci

    07/01/2021, 8:54 AM
    Hello everybody, wanted to ask: I’ve got a resolver for a particular query that should return the
    User
    type. Should I requery user or can return it right away ?
    Copy code
    ...
    const user = await prisma.user.findUnique({ where });
    ...
    <some actions that require info from the user record>
    ...
    <some other actions, maybe updating that user record>
    
    // from the resolver should I requery User or return the queried one?
    
    return user;
    // OR
    return prisma.user.findUnique({ where })
    Thank you.
    r
    • 2
    • 5
  • s

    Slackbot

    07/01/2021, 12:03 PM
    This message was deleted.
    n
    • 2
    • 2
  • j

    Jemin Kothari

    07/01/2021, 1:07 PM
    Hello For the below query I am getting below response.
    Copy code
    prisma.manageCustomFieldCategories.findMany({})
    Response :-
    Copy code
    "manageCustomFieldCategories": [
          {
            "id": 1126,
            "name": "test",
            "Fields": [
              {
                "id": 0,
                "field_label": "test",
                "is_required": 0,
                "is_active": false
              },
              {
                "id": 1,
                "field_label": "test1",
                "is_required": 0,
                "is_active": true,
              }
            ]
          }
        ]
    But I want only those records which has
    is_active
    : true inside the
    Fields
    .
    manageCustomFieldCategories
    has one to many relationship with
    Fields
    r
    a
    • 3
    • 63
  • r

    ryan

    07/01/2021, 1:37 PM
    Hi all 👋 @Daniel Norman and I will be going live in just under an hour and half from now for What’s New in Prisma 🎉 Come hang out with us to check out what’s new at v2.26

    https://youtu.be/i8TqB5ofVaM▾

    japan parrot 4
    prisma rainbow 10
    fast parrot 9
    🎉 8
    👍 1
  • s

    sven

    07/01/2021, 2:17 PM
    I am running several select queries with
    queryRaw
    against my postgres. I am getting the following error object: ``{"code": String("42P01"), "message": String("relation \"Book\" does not exist")}), error_code: "P2010" }``. The error does not occur every time I run those queries, only every few minutes it occurs. Some specific info about my case: • prisma version: 2.25.0 • I am using a schema (added to the connection string) • I am using pg_bouncer set to transactional mode (this is important, because on staging and local I dont have pg_bouncer and there no error occures) Things I have tried: • Running the queries in one transaction => Still broken • Running $queryRaw(
    SET search_path TO ${config.DATABASE_SCHEMA};)
    ) before the other queries => This solved the issue, but created other issues in other environments It seems like prisma doesnt know about the schema in some of the
    queryRaw
    queries, due to the connection pooling. Is this a bug?
    r
    • 2
    • 8
  • a

    Alhassan Raad

    07/01/2021, 4:57 PM
    Hey guys, I was wondering if there were any plans to create a caching system for frequent queries.
  • m

    Mike Lumos

    07/01/2021, 7:33 PM
    Hey guys! I want to create a post with a list of tags attached to it. The models are connected many-to-many (one post can have several tags, and one tag can have several posts in it). But I'm getting an error `Invalid
    prisma.post.create()
    invocation: Unknown arg
    tags
    in data.tags for type PostUncheckedCreateInput`. Here are my prisma models:
    Copy code
    model Post {
          id String @id @default(cuid())
          slug String @unique
          title String
          body String
          tags Tag[]
        }
    
        model Tag {
          id String @id @default(cuid())
          posts Post[]
          name String
          slug String @unique
        }
    And here's a mutation where I'm trying to create a post, and attach tags to it:
    Copy code
    t.field('createPost', {
          type: 'Post',
          args: {
            title: nonNull(stringArg()),
            body: stringArg(),
            tags: list(arg({ type: 'TagInput' }))
          },
          resolve: async (_, args, context: Context) => {
            // Create tags if they don't exist
            const tags = await Promise.all(
              args.tags.map((tag) =>
                context.prisma.tag.upsert({
                  create: omit(tag, "id"),
                  update: tag,
                  where: { id: tag.id || "" },
                })
              )
            )
            return context.prisma.post.create({
              data: {
                title: args.title,
                body: args.body,
                slug: `${slugify(args.title)}-${cuid()}`,
                tags: {
                  set: [{id:"ckql6n0i40000of9yzi6d8bv5"}]
                },
                authorId: getUserId(context),
                published: true, // make it false once Edit post works.
              },
            })
          },
        })
    This doesn't seem to be working. I'm getting an error:
    Copy code
    Invalid `prisma.post.create()` invocation:
        {
          data: {
            title: 'Post with tags',
            body: 'Post with tags body',
            slug: 'Post-with-tags-ckql7jy850003uz9y8xri51zf',
            tags: {
              connect: [
                {
                  id: 'ckql6n0i40000of9yzi6d8bv5'
                }
              ]
            },
          }
        }
        Unknown arg `tags` in data.tags for type PostUncheckedCreateInput. Available args:
        type PostUncheckedCreateInput {
          id?: String
          title: String
          body: String
          slug: String
        }
    It seems like the
    tags
    field on the post is missing? But I did run
    prisma generate
    and
    prisma migrate
    . Also I can successfully query tags on a post if I add them manually using Prisma Studio. What could be causing this issue?
    r
    • 2
    • 1
  • e

    El

    07/01/2021, 7:53 PM
    Copy code
    [*] Altered column `notes` (default changed from `Some(DbGenerated("''::text"))` to `Some(Value(String("")))`)
    r
    • 2
    • 1
  • e

    El

    07/01/2021, 7:53 PM
    how could I fix this
  • h

    Halvor

    07/01/2021, 9:04 PM
    How can i check if a prisma query did return any rows?
  • h

    Halvor

    07/01/2021, 9:08 PM
    also how can i somehow make prisma not return a json object with null values if no rows are returned?
    r
    • 2
    • 1
  • p

    Peter Kellner

    07/01/2021, 10:25 PM
    How can I insert two records with the second using the result of the first. Like adding an invoice with line items. Need to have the invoice number before inserting the line items. I tried the below, but it’s a hot mess I know. EDIT: figured it out. Below works:
    Copy code
    const addedDate = new Date().toISOString();
    const noteAdded = prisma.note.create({
      data: {
        description: description,
        title: title,
        active: 1,
        createDate: addedDate,
        noteChangeLogs: {
          create: [
            {
              changeDate: addedDate,
              operation: 'Created',
              details: '',
            },
          ],
        },
      },
      include: {
        noteChangeLogs: true, // Include all posts in the returned object
      },
    });
    This was helpful: https://www.prisma.io/docs/concepts/components/prisma-client/relation-queries
    👍 1
    r
    • 2
    • 1
  • a

    Adam

    07/02/2021, 12:00 AM
    Has anyone solved/created a best practice on how to run integration tests in an idempotent and isolated way? I've seen a few articles on simply running integration tests, but these don't scale. In past projects I've worked on (that didn't use prisma) each test suite (in jest this would be under the
    describe
    ) would start up its own isolated database/schema and its own base data to perform the tests, then destroy it after being completed. With the nature of
    Prisma
    requiring the DB_URL outside of the application context, I haven't found a good way of implementing this model. Is there a different way beyond running test in a synchronous fashion? One of my thoughts (for postgres) was to create databases with a UUID so the connection string would be like
    <postgresql://localapp:password@localhost:5432/${UUID}>
    which with postgres these can reside all in the same DB server. Then drop them on completion/failure of the test. But I don't see a way of doing that.
    p
    r
    • 3
    • 5
  • j

    J Giri

    07/02/2021, 12:58 AM
    Is it safe to use
    @@map
    in
    schema.prisma
    like this
    Copy code
    model User {
      id        String @id @default(cuid())
      firstName String
      lastName  String
      email     String @unique
      password  String
    
      @@map("user")
    }
    Will there be any issue when introspecting later? I want my database table names to be in lowercase but the model names in schema to be in uppercase. Is it safe to use
    @@map
    like this? Or is there any better and safer way?
    p
    r
    • 3
    • 8
  • j

    J Giri

    07/02/2021, 2:15 AM
    Can i just use types from
    "node_modules/.prisma/client"
    instead of using
    typegraphql-prisma
    and generating types which emits the generated typegraphql classes to
    "node_modules/@generated/typegraphql-prisma"
    ? PS: i found that
    "node_module/.prisma/client"
    contains the types. Using
    typegraphql-prisma
    seems redundant. Isn't it? Basically can i do
    import { User } from ".prisma/client"
    , INSTEAD OF ``import { User } from "@generated/type-graphql/models/User"``. Is there any danger zone while doing so?
    r
    • 2
    • 5
  • g

    Gelo

    07/02/2021, 3:41 AM
    How to handle error globally using nestjs?
  • g

    Gelo

    07/02/2021, 3:41 AM
    In prisma
  • j

    J Giri

    07/02/2021, 7:23 AM
    Caught in a issue with
    typegraphql-prisma
    . I have my types generated using
    typegraphql-prisma
    . In one of the resolver I made, in it I used
    User
    type (created by typegraphql-prisma).
    Copy code
    @Mutation(() => User)
      async register(
        @Arg("firstName") firstName: string,
        @Arg("lastName") lastName: string,
        @Arg("email") email: string,
        @Arg("password") password: string
      ): Promise<User> {
        const hashedPassword = await bcrypt.hash(password, 12);
        const user = await prisma.user.create({
          data: {
            firstName,
            lastName,
            email,
            password: hashedPassword,
          },
        });
    The problem is there is also a field for password (as expected return property) in User type definiation (created by typegraphql-prisma) like below.
    Copy code
    export class User {
      @TypeGraphQL.Field(_type => String, {
        nullable: false
      })
      id!: string;
    
      @TypeGraphQL.Field(_type => String, {
        nullable: false
      })
      firstName!: string;
    
      @TypeGraphQL.Field(_type => String, {
        nullable: false
      })
      lastName!: string;
    
      @TypeGraphQL.Field(_type => String, {
        nullable: false
      })
      email!: string;
    
      @TypeGraphQL.Field(_type => String, {
        nullable: false
      })
      password!: string;
    }
    I dont want the
    password
    field as the property in the returned User type. Even if i omit the
    password
    field manually,
    npx generate
    regenerate the types and again
    password
    field is there. How to work around this?
    r
    • 2
    • 6
  • j

    J Giri

    07/02/2021, 10:19 AM
    Run time issue with
    typegraphql-prisma
    . I followed the doc of
    typegraphql-prisma
    . What I installed as per doc of typegraphql-prisma is
    Copy code
    npm i -D typegraphql-prisma @types/graphql-fields
    npm i graphql-scalars graphql-fields
    I also configured the default output folder
    Copy code
    generator typegraphql {
      provider = "typegraphql-prisma"
      output   = "../prisma/generated/type-graphql"
    }
    my tsconfig.json is
    Copy code
    {
      "compilerOptions": {
        "target": "es6",
        "module": "commonjs",
        "lib": ["dom", "es6", "es2017", "esnext.asynciterable"],
        "sourceMap": true,
        "outDir": "./dist",
        "moduleResolution": "node",
        "declaration": false,
        // "esModuleInterop": true,
    
        "composite": false,
        "removeComments": true,
        "noImplicitAny": true,
        "strictNullChecks": true,
        "strictFunctionTypes": true,
        "noImplicitThis": true,
        "noUnusedLocals": true,
        "noUnusedParameters": true,
        "noImplicitReturns": true,
        "noFallthroughCasesInSwitch": true,
        // "allowSyntheticDefaultImports": false,
        "emitDecoratorMetadata": true,
        "experimentalDecorators": true,
        "skipLibCheck": true,
        "baseUrl": "."
        // "rootDir": "src"
      },
      "exclude": ["node_modules"],
      "include": ["./src/**/*.tsx", "./src/**/*.ts"]
    }
    But now When i try to start my server with
    npm start
    (ts-node src/index.ts). i get the following error
    Copy code
    D:\Work\coding\testing\rough\ben_Typegraphql\node_modules\ts-node\src\index.ts:587
        return new TSError(diagnosticText, diagnosticCodes);
               ^
    TSError: ⨯ Unable to compile TypeScript:
    prisma/generated/type-graphql/models/User.ts:2:1 - error TS6133: 'GraphQLScalars' is declared but its value is never read.
    
    2 import * as GraphQLScalars from "graphql-scalars";
      ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    prisma/generated/type-graphql/models/User.ts:3:1 - error TS6133: 'Prisma' is declared but its value is never read.
    
    3 import { Prisma } from "@prisma/client";
      ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    prisma/generated/type-graphql/models/User.ts:4:1 - error TS6133: 'DecimalJSScalar' is declared but its value is never read.
    
    4 import { DecimalJSScalar } from "../scalars";
      ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    
        at createTSError (D:\Work\coding\testing\rough\ben_Typegraphql\node_modules\ts-node\src\index.ts:587:12)
        at reportTSError (D:\Work\coding\testing\rough\ben_Typegraphql\node_modules\ts-node\src\index.ts:591:19)
        at getOutput (D:\Work\coding\testing\rough\ben_Typegraphql\node_modules\ts-node\src\index.ts:921:36)
        at Object.compile (D:\Work\coding\testing\rough\ben_Typegraphql\node_modules\ts-node\src\index.ts:1189:32)
        at Module.m._compile (D:\Work\coding\testing\rough\ben_Typegraphql\node_modules\ts-node\src\index.ts:1295:42)
        at Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
        at Object.require.extensions.<computed> [as .ts] (D:\Work\coding\testing\rough\ben_Typegraphql\node_modules\ts-node\src\index.ts:1298:12)
        at Module.load (internal/modules/cjs/loader.js:928:32)
        at Function.Module._load (internal/modules/cjs/loader.js:769:14)
        at Module.require (internal/modules/cjs/loader.js:952:19)
    r
    • 2
    • 6
  • k

    khareta

    07/02/2021, 1:48 PM
    Anybody ever faced this error before?
    Copy code
    Error in connector: Error creating a database connection. (Timed out fetching a connection from the pool (connection limit: 50, in use: 17))
    on aws elastic beanstalk
    r
    j
    • 3
    • 15
  • a

    Ariel Flesler

    07/02/2021, 4:53 PM
    Hi all, is something like this possible and recommended when it makes sense?
    Copy code
    model Group {
      id         String        @id @default(cuid())
      members    User[] @relation(fields: [memberIds], references: [id])
      memberIds   String[]
    }
    c
    r
    • 3
    • 4
  • a

    Andy

    07/02/2021, 5:59 PM
    hi all was wondering if anyone has seen such an error before:
    Copy code
    Error: Database error
    Error querying the database: db error: ERROR: invalid string in message
       0: sql_migration_connector::flavour::postgres::sql_schema_from_migration_history
                 at migration-engine/connectors/sql-migration-connector/src/flavour/postgres.rs:367
       1: migration_core::api::DevDiagnostic
                 at migration-engine/core/src/api.rs:89
    when trying to connect to a PostgresDB
    r
    • 2
    • 1
1...452453454...637Latest