Suji
Suji
DTDrizzle Team
Created by Suji on 2/23/2024 in #help
Undo Migration
Is there a way to undo a generated migration, not dropping the migration from the migration table but undo the schema changes applied from a migration like in sequalize ?
1 replies
DTDrizzle Team
Created by Suji on 1/27/2024 in #help
Help with types relational query function
I've created a function that i use to paginate data with relations, removed all the paginating stuff for the post
// Types from https://github.com/drizzle-team/drizzle-orm/issues/695
type Schema = typeof primarySchemas;
type TSchema = ExtractTablesWithRelations<Schema>;

export type IncludeRelation<TableName extends keyof TSchema> = DBQueryConfig<
'one' | 'many',
boolean,
TSchema,
TSchema[TableName]
>['with'];

export type InferResultType<
TableName extends keyof TSchema,
With extends IncludeRelation<TableName> | undefined = undefined,
> = BuildQueryResult<
TSchema,
TSchema[TableName],
{
with: With;
}
>;

async paginatedQuery<
U extends keyof drizzleOrm.ExtractTablesWithRelations<typeof schema>,
TableRelations extends IncludeRelation<U>,
>(
table: BaseTable,
{
with: queryWith,
}: {
with: TableRelations;
},
) {

const tableName = this.getTableName(table);
const data: Array<InferResultType<U, typeof queryWith>> =
await this.db.query[tableName].findMany({
with: queryWith
});

return { data, meta };
}
// Types from https://github.com/drizzle-team/drizzle-orm/issues/695
type Schema = typeof primarySchemas;
type TSchema = ExtractTablesWithRelations<Schema>;

export type IncludeRelation<TableName extends keyof TSchema> = DBQueryConfig<
'one' | 'many',
boolean,
TSchema,
TSchema[TableName]
>['with'];

export type InferResultType<
TableName extends keyof TSchema,
With extends IncludeRelation<TableName> | undefined = undefined,
> = BuildQueryResult<
TSchema,
TSchema[TableName],
{
with: With;
}
>;

async paginatedQuery<
U extends keyof drizzleOrm.ExtractTablesWithRelations<typeof schema>,
TableRelations extends IncludeRelation<U>,
>(
table: BaseTable,
{
with: queryWith,
}: {
with: TableRelations;
},
) {

const tableName = this.getTableName(table);
const data: Array<InferResultType<U, typeof queryWith>> =
await this.db.query[tableName].findMany({
with: queryWith
});

return { data, meta };
}
right now this works, but the problem is i have to define the relations twice, once as a param for the generic type and again for the with parameter This is what ive done, im not sure why this doesn't yield the same results
async paginatedQuery<
U extends keyof drizzleOrm.ExtractTablesWithRelations<typeof schema>,
TableRelations extends IncludeRelation<U>, <-- Delete this and directly assign the type to with
>(
table: BaseTable,
{
with: queryWith,
}: {
with: IncludeRelation<U>,
},
) {
async paginatedQuery<
U extends keyof drizzleOrm.ExtractTablesWithRelations<typeof schema>,
TableRelations extends IncludeRelation<U>, <-- Delete this and directly assign the type to with
>(
table: BaseTable,
{
with: queryWith,
}: {
with: IncludeRelation<U>,
},
) {
Above change causes to miss the relational types in the return type 😦 Any TS aficionados willing to help 🙂
28 replies
DTDrizzle Team
Created by Suji on 9/9/2023 in #help
Get raw query from toSQL
I trying to figure out if drizzle has a function or helper built in that builds the raw query returned from toSQL right now toSQL returns params and sql as an object, i would like to get the raw sql query this is what im doing now to achieve this, any alternatives or is there a something drizzle provides i missed thanks
buildQuery(query: string, params: unknown[]) {
let index = 1;

return query.replace(/\$\d+/g, () => {
const value = params[index - 1];
index++;

return `'${value}'`;
});
}
buildQuery(query: string, params: unknown[]) {
let index = 1;

return query.replace(/\$\d+/g, () => {
const value = params[index - 1];
index++;

return `'${value}'`;
});
}
8 replies
DTDrizzle Team
Created by Suji on 6/1/2023 in #help
Infer return type for relational query with pagination
I have created a function that can paginate data for relational queries, problem is i cant figure out how to make to include the relations that are passed into the inferred return type
async paginatedQuery<
ReturnType extends drizzleOrm.InferModel<Table>,
Table extends AnyPgTable,
>(
table: Table,
{
limit,
page,
where,
takeAll,
with: queryWith,
}: {
limit: number;
page: number;
where?: drizzleOrm.SQL;
takeAll?: boolean;
// eslint-disable-next-line @typescript-eslint/ban-types
with?: object;
},
) {
const tableNameSymbol = Object.getOwnPropertySymbols(table).find(
(value) => value.description === 'Name',
);

const tableName = table[tableNameSymbol!].toString().toLowerCase();

const count = await (where?.queryChunks.length === 0
? this.db
.select({ count: sql<number>`count(*)`.mapWith(Number) })
.from(table)
: this.db
.select({ count: sql<number>`count(*)`.mapWith(Number) })
.from(table)
.where(where));

const offset = (page - 1) * limit;

const data: ReturnType[] = await this.db.query[tableName].findMany({
...(queryWith && { with: queryWith }),
...(where?.queryChunks.length !== 0 && { where }),
...(!takeAll && { limit, offset: offset <= 0 ? 0 : offset }),
});

const meta: IPageMeta = {
currentPage: page,
isLastPage: page * limit >= count[0].count,
isFirstPage: page === 1,
nextPage: page * limit >= count[0].count ? null : page + 1,
previousPage: page - 1 === 0 ? null : page - 1,
pageCount: Math.ceil(count[0].count / limit),
};

return { data, meta };
}
async paginatedQuery<
ReturnType extends drizzleOrm.InferModel<Table>,
Table extends AnyPgTable,
>(
table: Table,
{
limit,
page,
where,
takeAll,
with: queryWith,
}: {
limit: number;
page: number;
where?: drizzleOrm.SQL;
takeAll?: boolean;
// eslint-disable-next-line @typescript-eslint/ban-types
with?: object;
},
) {
const tableNameSymbol = Object.getOwnPropertySymbols(table).find(
(value) => value.description === 'Name',
);

const tableName = table[tableNameSymbol!].toString().toLowerCase();

const count = await (where?.queryChunks.length === 0
? this.db
.select({ count: sql<number>`count(*)`.mapWith(Number) })
.from(table)
: this.db
.select({ count: sql<number>`count(*)`.mapWith(Number) })
.from(table)
.where(where));

const offset = (page - 1) * limit;

const data: ReturnType[] = await this.db.query[tableName].findMany({
...(queryWith && { with: queryWith }),
...(where?.queryChunks.length !== 0 && { where }),
...(!takeAll && { limit, offset: offset <= 0 ? 0 : offset }),
});

const meta: IPageMeta = {
currentPage: page,
isLastPage: page * limit >= count[0].count,
isFirstPage: page === 1,
nextPage: page * limit >= count[0].count ? null : page + 1,
previousPage: page - 1 === 0 ? null : page - 1,
pageCount: Math.ceil(count[0].count / limit),
};

return { data, meta };
}
returnType is typed with only the base table fields, this doenst include the fields that get included from relations. Any clues or pointers ??
3 replies
DTDrizzle Team
Created by Suji on 5/30/2023 in #help
can you Infer relations?
im really loving how drizzle plays well with relations, but im wondering is there a way to get types for relations? in prisma you can use Prisma.YourModelGetPayload<{}> to generate a type with relations, is this possible with infermodel? i tired the most obvious way and that didnt work
InferModel<typeof userRelations>;
InferModel<typeof userRelations>;
4 replies
DTDrizzle Team
Created by Suji on 5/29/2023 in #help
Doent infer type in Callback syntax for query
Im querying the users table like this db.query.user.findFirst({ where: (user, { eq }) => { return eq(user.email, whereArgs?.email); }, }) in the where callback param user is typed as never ?? ive setup drizzle like this import * as schema from '@/db/schema'; const db = drizzle(pool, { schema }); any idea why this is the case??
2 replies