Nimish Gupta
06/30/2021, 1:48 PMmodel 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
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?Gonzalo Moreno
06/30/2021, 2:58 PMAman Tiwari
06/30/2021, 4:52 PMLars Ivar Igesund
06/30/2021, 6:32 PMYrobot
07/01/2021, 2:24 AMYrobot
07/01/2021, 2:28 AMconsole.log('Hello World!');
Arun Kumar
07/01/2021, 5:43 AMcreate
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.dhatGuy
07/01/2021, 6:02 AMjasci
07/01/2021, 8:54 AMUser
type.
Should I requery user or can return it right away ?
...
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.Slackbot
07/01/2021, 12:03 PMJemin Kothari
07/01/2021, 1:07 PMprisma.manageCustomFieldCategories.findMany({})
Response :-
"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
sven
07/01/2021, 2:17 PMqueryRaw
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?Alhassan Raad
07/01/2021, 4:57 PMMike Lumos
07/01/2021, 7:33 PMprisma.post.create()
invocation: Unknown arg tags
in data.tags for type PostUncheckedCreateInput`.
Here are my prisma models:
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:
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:
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?El
07/01/2021, 7:53 PM[*] Altered column `notes` (default changed from `Some(DbGenerated("''::text"))` to `Some(Value(String("")))`)
El
07/01/2021, 7:53 PMHalvor
07/01/2021, 9:04 PMHalvor
07/01/2021, 9:08 PMPeter Kellner
07/01/2021, 10:25 PMconst 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-queriesAdam
07/02/2021, 12:00 AMdescribe
) 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.J Giri
07/02/2021, 12:58 AM@@map
in schema.prisma
like this
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?J Giri
07/02/2021, 2:15 AM"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?Gelo
07/02/2021, 3:41 AMGelo
07/02/2021, 3:41 AMJ Giri
07/02/2021, 7:23 AMtypegraphql-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).
@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.
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?J Giri
07/02/2021, 10:19 AMtypegraphql-prisma
. I followed the doc of typegraphql-prisma
.
What I installed as per doc of typegraphql-prisma is
npm i -D typegraphql-prisma @types/graphql-fields
npm i graphql-scalars graphql-fields
I also configured the default output folder
generator typegraphql {
provider = "typegraphql-prisma"
output = "../prisma/generated/type-graphql"
}
my tsconfig.json is
{
"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
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)
khareta
07/02/2021, 1:48 PMError in connector: Error creating a database connection. (Timed out fetching a connection from the pool (connection limit: 50, in use: 17))
on aws elastic beanstalkAriel Flesler
07/02/2021, 4:53 PMmodel Group {
id String @id @default(cuid())
members User[] @relation(fields: [memberIds], references: [id])
memberIds String[]
}
Andy
07/02/2021, 5:59 PMError: 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