Kuba
Kuba
Explore posts from servers
DTDrizzle Team
Created by Kuba on 9/25/2024 in #help
referencedTable error when querying
Hello! I'm trying to define one to many relations between the tables. While it works for most of the tables, I cannot think of why it fails for SRSCards. I created a very minimal and complete drizzle.run: https://drizzle.run/y2ztrp5ylzvj18klf8kxf932 The error in the playground is different, as locally I get:
Cannot read properties of undefined (reading 'referencedTable') TypeError: Cannot read properties of undefined (reading 'referencedTable')
Cannot read properties of undefined (reading 'referencedTable') TypeError: Cannot read properties of undefined (reading 'referencedTable')
But nevertheless query fails. The goals: - single question can be referenced by multiple SRSCards, - each user can have their own SRSCards, - single SRSCards belongs to only one user and only one question. I feel this is something simple, yet I fail to notice it. Thanks for help in advance.
3 replies
DTDrizzle Team
Created by Kuba on 8/31/2024 in #help
Relations and inheritance mapping
Hello! I have a schema where a question can be polymorphic - that is there's a generalized (base) Question that can be specialized: TrueFalseQuestion, MultipleChoiceQuestion etc. Specialized types have their own attributes, that are unique to them (such as is_correct for true/false). I would like to know if there's a way to use Drizzle Query and don't nest the associated tables, but instead return the attributes within the object itself:
// Instead of this
{
"id": "1b22a63f-d935-44c2-ae52-38b899788e64",
"type": "true_false",
"question": "Does drizzle support polymorphic associations?",
"answers": [],
// nested relation, queried through findMany's `with`
"trueFalseQuestion": {
"isCorrect": true
}
}

// Return this
{
"id": "1b22a63f-d935-44c2-ae52-38b899788e64",
"type": "true_false",
"question": "Does drizzle support polymorphic associations?",
"answers": [],
"isCorrect": true
}
// Instead of this
{
"id": "1b22a63f-d935-44c2-ae52-38b899788e64",
"type": "true_false",
"question": "Does drizzle support polymorphic associations?",
"answers": [],
// nested relation, queried through findMany's `with`
"trueFalseQuestion": {
"isCorrect": true
}
}

// Return this
{
"id": "1b22a63f-d935-44c2-ae52-38b899788e64",
"type": "true_false",
"question": "Does drizzle support polymorphic associations?",
"answers": [],
"isCorrect": true
}
Mapping it manually ofc isn't a problem. I'm just curious whethe it's possible to do it through drizzle directly? Currently I query the data as follows:
database.query.questions.findMany({
with: {
answers: true,
trueFalseQuestion: {
columns: {
isCorrect: true,
},
},
},
where: (questions, { eq }) => eq(questions.quizId, quizId),
});
database.query.questions.findMany({
with: {
answers: true,
trueFalseQuestion: {
columns: {
isCorrect: true,
},
},
},
where: (questions, { eq }) => eq(questions.quizId, quizId),
});
2 replies
DTDrizzle Team
Created by Kuba on 8/13/2024 in #help
snapshot.json is not of the latest version
Hi! I just updated drizzle ORM in my project to:
"drizzle-orm": "0.33.0", // from "0.30.9"
"drizzle-kit": "0.24.0", // from "0.20.17"
"drizzle-orm": "0.33.0", // from "0.30.9"
"drizzle-kit": "0.24.0", // from "0.20.17"
I also migrated to new config after the update:
export default defineConfig({
schema: "./src/core/database/schema.ts",
out: "./database/migrations",
dialect: "postgresql",
dbCredentials: {
url: process.env.DATABASE_URL ?? "",
},
verbose: true,
strict: true,
});
export default defineConfig({
schema: "./src/core/database/schema.ts",
out: "./database/migrations",
dialect: "postgresql",
dbCredentials: {
url: process.env.DATABASE_URL ?? "",
},
verbose: true,
strict: true,
});
However when I try to generate migration after modifying the schema, I get an error:
> pnpm drizzle-kit generate
No config path provided, using default 'drizzle.config.ts'
Reading config file 'F:\Projects\app\backend\drizzle.config.ts'
database\migrations\meta\0000_snapshot.json/snapshot.json is not of the latest version
database\migrations\meta\0001_snapshot.json/snapshot.json is not of the latest version
database\migrations\meta\0002_snapshot.json/snapshot.json is not of the latest version
database\migrations\meta\0003_snapshot.json/snapshot.json is not of the latest version
database\migrations\meta\0004_snapshot.json/snapshot.json is not of the latest version
database\migrations\meta\0005_snapshot.json/snapshot.json is not of the latest version
Run drizzle-kit up
> pnpm drizzle-kit generate
No config path provided, using default 'drizzle.config.ts'
Reading config file 'F:\Projects\app\backend\drizzle.config.ts'
database\migrations\meta\0000_snapshot.json/snapshot.json is not of the latest version
database\migrations\meta\0001_snapshot.json/snapshot.json is not of the latest version
database\migrations\meta\0002_snapshot.json/snapshot.json is not of the latest version
database\migrations\meta\0003_snapshot.json/snapshot.json is not of the latest version
database\migrations\meta\0004_snapshot.json/snapshot.json is not of the latest version
database\migrations\meta\0005_snapshot.json/snapshot.json is not of the latest version
Run drizzle-kit up
Is there something I'm missing here? When I roll back the packages generate:pg work fine.
2 replies
DTDrizzle Team
Created by Kuba on 3/14/2024 in #help
Access table field dynamically by an index - help with types
Hello! I'm further extending the DAO from https://discord.com/channels/1043890932593987624/1147439990683488268 , and currently I'm trying to implement custom ordering. I've already written the code which works, and the only thing I'm missing is type-compliance - accessing table column directly by an index gives me this TS error:
TS2536: Type 'string | number | (keyof TTable["_"]["columns"] & string)' cannot be used to index type 'TTable'.
TS2536: Type 'string | number | (keyof TTable["_"]["columns"] & string)' cannot be used to index type 'TTable'.
The code which errors:
interface FieldOrder<TTableFields extends string | number> {
field: TTableFields;
order: "asc" | "desc";
}

// This is a method in the class
findAllPaginated(
page: number,
pageSize: number,
orderBy?: FieldOrder<keyof InferSelectModel<TTable>>[],
): Promise<InferSelectModel<TTable>[]> {
const customOrderBy = orderBy?.map(({ field, order }) => {
// this part right here
const sqlField = this.table[field];

return order === "desc" ? desc(sqlField) : asc(sqlField);
});
const defaultOrderBy = [desc(this.sqlCreatedAt)];

return this.database
.select()
.from(this.table)
.where(this.isNotDeleted)
.orderBy(...(customOrderBy ?? defaultOrderBy))
.limit(pageSize)
.offset(pageSize * (page - 1)) as Promise<InferSelectModel<TTable>[]>;
}
interface FieldOrder<TTableFields extends string | number> {
field: TTableFields;
order: "asc" | "desc";
}

// This is a method in the class
findAllPaginated(
page: number,
pageSize: number,
orderBy?: FieldOrder<keyof InferSelectModel<TTable>>[],
): Promise<InferSelectModel<TTable>[]> {
const customOrderBy = orderBy?.map(({ field, order }) => {
// this part right here
const sqlField = this.table[field];

return order === "desc" ? desc(sqlField) : asc(sqlField);
});
const defaultOrderBy = [desc(this.sqlCreatedAt)];

return this.database
.select()
.from(this.table)
.where(this.isNotDeleted)
.orderBy(...(customOrderBy ?? defaultOrderBy))
.limit(pageSize)
.offset(pageSize * (page - 1)) as Promise<InferSelectModel<TTable>[]>;
}
The question is - how can I tell typescript, that this is valid? I'm fine with any type casting solutions, I just don't know how can I take this further.
6 replies
TTCTheo's Typesafe Cult
Created by Kuba on 7/25/2023 in #questions
Stop react query from retry on 404
TLDR: I cannot get correct typing for the error, as the react query uses unknown type for the error in retry function. They also reccomend to perform a runtime check for the error. I'm kinda stuck as I don't lnow how to retrieve the error code from the error in retry function. --- Currently I'm trying to stop react query client (that's used by the tRPC internally) from retrying on 404 and 401 HTTP errors. I found this issue https://github.com/TanStack/query/discussions/372#discussioncomment-6023276 and adapted the answer to my needs:
const MAX_QUERY_RETRIES = 4;
const SKIPPED_HTTP_CODES = [401, 402, 403, 404];

export const reactQueryRetry = (failureCount: number, error: unknown) => {
if (failureCount > MAX_QUERY_RETRIES) {
return false;
}

if (
error instanceof TRPCError &&
SKIPPED_HTTP_CODES.includes(getHTTPStatusCodeFromError(trpcError))
) {
return false;
}

return true;
};
const MAX_QUERY_RETRIES = 4;
const SKIPPED_HTTP_CODES = [401, 402, 403, 404];

export const reactQueryRetry = (failureCount: number, error: unknown) => {
if (failureCount > MAX_QUERY_RETRIES) {
return false;
}

if (
error instanceof TRPCError &&
SKIPPED_HTTP_CODES.includes(getHTTPStatusCodeFromError(trpcError))
) {
return false;
}

return true;
};
However, after inspecting this further the error isn't an isntance of TRPCError, as its shape differs from the TRPC's error structure:
// https://trpc.io/docs/server/error-handling
const error: TRPCError = {
name: 'TRPCError',
code: 'BAD_REQUEST',
message: '"password" must be at least 4 characters',
};
// https://trpc.io/docs/server/error-handling
const error: TRPCError = {
name: 'TRPCError',
code: 'BAD_REQUEST',
message: '"password" must be at least 4 characters',
};
Error's shape:
{
"meta":{
"response":{}
},
"shape":{
"message":"Quiz not found",
"code":-32004,
"data":{
"code":"NOT_FOUND",
"httpStatus":404,
"stack":"removed",
"path":"quiz.byId",
"zodError":null
}
},
"data":{
"code":"NOT_FOUND",
"httpStatus":404,
"stack":"removed",
"path":"quiz.byId",
"zodError":null
},
"name":"TRPCClientError"
}
{
"meta":{
"response":{}
},
"shape":{
"message":"Quiz not found",
"code":-32004,
"data":{
"code":"NOT_FOUND",
"httpStatus":404,
"stack":"removed",
"path":"quiz.byId",
"zodError":null
}
},
"data":{
"code":"NOT_FOUND",
"httpStatus":404,
"stack":"removed",
"path":"quiz.byId",
"zodError":null
},
"name":"TRPCClientError"
}
So I tried tRPC helpers const trpcError = getTRPCErrorFromUnknown(error) and then getHTTPStatusCodeFromError(trpcError) but the HTTP code returned by helper is 500 instead of 404 visible in JSON.
2 replies
KPCKevin Powell - Community
Created by Kuba on 7/22/2023 in #front-end
react-hook-form input radio not having a default value supplied
Hey! I'm having an issue with RHF (react-hook-form) and controlled radio input. The default value supplied by useForm does not results in radio button being checked by default. I figured a workaround by supplying defaultChecked with a comparison with a default value, but that feels hacky. If I try with uncontrolled inputs (vanilla html inputs), then the default value is supplied correctly. https://codesandbox.io/p/sandbox/modern-hooks-wd874l
1 replies