DYELbrah
DYELbrah
Explore posts from servers
DTDrizzle Team
Created by DYELbrah on 10/19/2024 in #help
DrizzleKit check constraint generation missing value
I added a constraint to this table:
export const purchaseOrderLineItem = createTable(
"purchase_order_line_item",
{
id: varchar("id", { length: 21 }).primaryKey().notNull(),
length: numeric("length").notNull(),
width: numeric("width"),
quantity: integer("quantity").notNull(),
lineItemCost: numeric("line_item_cost").notNull(),
purchaseOrderId: varchar("purchase_order_id", { length: 21 })
.notNull()
.references(() => purchaseOrder.id),
productId: text("product_id")
.notNull()
.references(() => product.id),
},
(table) => {
return {
uniqueProductIdLengthWidthForSamePOKey: uniqueIndex(
"product_id_length_width_purchase_order_id_key",
).on(table.productId, table.length, table.width, table.purchaseOrderId),
quantityMinZero: check("quantity_min_zero", gt(table.quantity, 0)),
};
},
);
export const purchaseOrderLineItem = createTable(
"purchase_order_line_item",
{
id: varchar("id", { length: 21 }).primaryKey().notNull(),
length: numeric("length").notNull(),
width: numeric("width"),
quantity: integer("quantity").notNull(),
lineItemCost: numeric("line_item_cost").notNull(),
purchaseOrderId: varchar("purchase_order_id", { length: 21 })
.notNull()
.references(() => purchaseOrder.id),
productId: text("product_id")
.notNull()
.references(() => product.id),
},
(table) => {
return {
uniqueProductIdLengthWidthForSamePOKey: uniqueIndex(
"product_id_length_width_purchase_order_id_key",
).on(table.productId, table.length, table.width, table.purchaseOrderId),
quantityMinZero: check("quantity_min_zero", gt(table.quantity, 0)),
};
},
);
ALTER TABLE "purchase_order_line_item" ADD CONSTRAINT "quantity_min_zero" CHECK ("purchase_order_line_item"."quantity" > $1);
ALTER TABLE "purchase_order_line_item" ADD CONSTRAINT "quantity_min_zero" CHECK ("purchase_order_line_item"."quantity" > $1);
This generated the following SQL in the migration file. You can see that $1 was returned which should have been a 0, since the minimum is 0. This then leads to failing migrations. This leads to: Error during migration: NeonDbError: there is no parameter $1 Is this a known bug?
6 replies
DTDrizzle Team
Created by DYELbrah on 6/2/2024 in #help
Is it okay to manually edit migration files?
I recently had a migration file execute commands for dropping a table in the wrong order. Can I reorder them manually? This wouldn't result in any schema changes technically....
2 replies
DTDrizzle Team
Created by DYELbrah on 6/2/2024 in #help
Can't apply migration?
The following migration file was generated by Drizzle-Kit
DROP TABLE "worker_pay_period";--> statement-breakpoint
ALTER TABLE "pay_stub" DROP CONSTRAINT "pay_stub_pay_period_id_worker_pay_period_id_fk";
--> statement-breakpoint
ALTER TABLE "pay_stub" ADD COLUMN "pay_period_start" timestamp NOT NULL;--> statement-breakpoint
ALTER TABLE "pay_stub" ADD COLUMN "pay_period_end" timestamp NOT NULL;--> statement-breakpoint
ALTER TABLE "pay_stub" DROP COLUMN IF EXISTS "pay_period_id";
DROP TABLE "worker_pay_period";--> statement-breakpoint
ALTER TABLE "pay_stub" DROP CONSTRAINT "pay_stub_pay_period_id_worker_pay_period_id_fk";
--> statement-breakpoint
ALTER TABLE "pay_stub" ADD COLUMN "pay_period_start" timestamp NOT NULL;--> statement-breakpoint
ALTER TABLE "pay_stub" ADD COLUMN "pay_period_end" timestamp NOT NULL;--> statement-breakpoint
ALTER TABLE "pay_stub" DROP COLUMN IF EXISTS "pay_period_id";
I basically just dropped a table called worker_pay_period, this table was referenced inside my pay_stub table (hence why the last command deletes the FK column) For some reason when this executes I get:
severity: 'ERROR',
code: '2BP01',
detail: 'constraint pay_stub_pay_period_id_worker_pay_period_id_fk on table pay_stub depends on table worker_pay_period',
hint: 'Use DROP ... CASCADE to drop the dependent objects too.',
severity: 'ERROR',
code: '2BP01',
detail: 'constraint pay_stub_pay_period_id_worker_pay_period_id_fk on table pay_stub depends on table worker_pay_period',
hint: 'Use DROP ... CASCADE to drop the dependent objects too.',
If I'm not mistaken, Drizzle-Kit should've dropped the column inside the pay_stub table that references the dropped table. Is this a bug? Can I manually update the migration file to do this or would this cause issues?
1 replies
DTDrizzle Team
Created by DYELbrah on 6/1/2024 in #help
Updated Drizzle Kit and now all indexes were updated to use Btree? Why?
Today I generated a migration after updating drizzle-kit to ^0.22.1 It seems to have dropped all my previous indexes: Such as one that I created before the updated which generated:
CREATE INDEX IF NOT EXISTS "idx_product_description" ON "product" ("description");--> statement-breakpoint
CREATE INDEX IF NOT EXISTS "idx_product_description" ON "product" ("description");--> statement-breakpoint
The new migration file did:
DROP INDEX IF EXISTS "product_description_key";--> statement-breakpoint

CREATE UNIQUE INDEX IF NOT EXISTS "product_description_key" ON "product" USING btree (description);--> statement-breakpoint
DROP INDEX IF EXISTS "product_description_key";--> statement-breakpoint

CREATE UNIQUE INDEX IF NOT EXISTS "product_description_key" ON "product" USING btree (description);--> statement-breakpoint
Here's how that table with the index is defined in case that's useful
export const product = createTable(
"product",
{
id: varchar("id", { length: 21 }).primaryKey().notNull(),
weightByFoot: numeric("weight_by_foot").notNull(),
description: text("description").notNull(),
},
(table) => {
return {
idxProductDescription: index("idx_product_description").on(
table.description,
),
};
},
);
export const product = createTable(
"product",
{
id: varchar("id", { length: 21 }).primaryKey().notNull(),
weightByFoot: numeric("weight_by_foot").notNull(),
description: text("description").notNull(),
},
(table) => {
return {
idxProductDescription: index("idx_product_description").on(
table.description,
),
};
},
);
Why did this happen?
1 replies
DTDrizzle Team
Created by DYELbrah on 5/28/2024 in #help
Drizzle-kit detecting random enums?
Why am I getting this interactive prompt? How can I force select the first option? I get this when I run drizzle-kit push using pg.
Is account_type enum created or renamed from another enum?
❯ + account_type create enum
~ auth.aal_level › account_type rename enum
~ auth.code_challenge_method › account_type rename enum
~ auth.factor_status › account_type rename enum
~ auth.factor_type › account_type rename enum
~ auth.one_time_token_type › account_type rename enum
~ pgsodium.key_status › account_type rename enum
~ pgsodium.key_type › account_type rename enum
~ realtime.action › account_type rename enum
~ realtime.equality_op › account_type rename enum
Is account_type enum created or renamed from another enum?
❯ + account_type create enum
~ auth.aal_level › account_type rename enum
~ auth.code_challenge_method › account_type rename enum
~ auth.factor_status › account_type rename enum
~ auth.factor_type › account_type rename enum
~ auth.one_time_token_type › account_type rename enum
~ pgsodium.key_status › account_type rename enum
~ pgsodium.key_type › account_type rename enum
~ realtime.action › account_type rename enum
~ realtime.equality_op › account_type rename enum
1 replies
DTDrizzle Team
Created by DYELbrah on 5/28/2024 in #help
Drizzle-kit push remove interactivity?
In our GH Actions we're getting the following prompt: enum name created or renamed from another enum? Then we have to select a value, how can we stop this from happening as it's breaking our actions?
1 replies
TTCTheo's Typesafe Cult
Created by DYELbrah on 4/14/2024 in #questions
How to exclude specific routes from Clerk middleware?
Anyone know how I can exclude the middleware from Clerk from running on my routes in folder: /api/cron? Here's the current file:
import { authMiddleware } from "@clerk/nextjs";

// This example protects all routes including api/trpc routes
// Please edit this to allow other routes to be public as needed.
// See https://clerk.com/docs/references/nextjs/auth-middleware for more information about configuring your Middleware
export default authMiddleware({
debug: false,
});

export const config = {
matcher: ["/((?!.+\\.[\\w]+$|_next).*)", "/", "/(api|trpc)(.*)"],
};
import { authMiddleware } from "@clerk/nextjs";

// This example protects all routes including api/trpc routes
// Please edit this to allow other routes to be public as needed.
// See https://clerk.com/docs/references/nextjs/auth-middleware for more information about configuring your Middleware
export default authMiddleware({
debug: false,
});

export const config = {
matcher: ["/((?!.+\\.[\\w]+$|_next).*)", "/", "/(api|trpc)(.*)"],
};
I believe we need to update the matcher but not sure how to do it correctly.
3 replies
DTDrizzle Team
Created by DYELbrah on 4/5/2024 in #help
Is there anyway we can add middleware to a table to execute before update or insert?
Similar to check constraints, I'd like to be able to execute a function before a record is updated or inserted into a specific table. Ideally these functions would be defined on the drizzle db schema? Not sure if this is possible?
1 replies
DTDrizzle Team
Created by DYELbrah on 3/16/2024 in #help
Will Drizzle throw when we attempt to update and zero records where updated?
Lets say we have a query where we update where id = input.id. If there was no row where that criteria is met, will Drizzle throw? or will it go through? Thanks!
3 replies
DTDrizzle Team
Created by DYELbrah on 3/12/2024 in #help
What is the import { check } used for from from "drizzle-orm/pg-core"
Anyone know what the check function imported from "drizzle-orm/pg-core" does? I believe check constraints are still not implemented so I'm not sure? Here's what it's definition looks like:
import { entityKind } from "../entity.js";
import type { SQL } from "../sql/index.js";
import type { PgTable } from "./table.js";
export declare class CheckBuilder {
name: string;
value: SQL;
static readonly [entityKind]: string;
protected brand: 'PgConstraintBuilder';
constructor(name: string, value: SQL);
}
export declare class Check {
table: PgTable;
static readonly [entityKind]: string;
readonly name: string;
readonly value: SQL;
constructor(table: PgTable, builder: CheckBuilder);
}
export declare function check(name: string, value: SQL): CheckBuilder;
import { entityKind } from "../entity.js";
import type { SQL } from "../sql/index.js";
import type { PgTable } from "./table.js";
export declare class CheckBuilder {
name: string;
value: SQL;
static readonly [entityKind]: string;
protected brand: 'PgConstraintBuilder';
constructor(name: string, value: SQL);
}
export declare class Check {
table: PgTable;
static readonly [entityKind]: string;
readonly name: string;
readonly value: SQL;
constructor(table: PgTable, builder: CheckBuilder);
}
export declare function check(name: string, value: SQL): CheckBuilder;
4 replies
DTDrizzle Team
Created by DYELbrah on 3/6/2024 in #help
If we're using Drizzlekit push, do we need to ever generate migrations?
Is there anywhere I can explain what the migration scripts are for? When I push a change, can't we just db:push our current version and that's it? What's the point of ever generating a migration file?
1 replies
TTCTheo's Typesafe Cult
Created by DYELbrah on 3/6/2024 in #questions
Inside create t3 app with Drizzle, why do we pass the database through ctx on each procedure?
If I'm not mistaken, we ideally don't want to do this if we want to break our application into separate layers (One of them being a data acess layer that we use to connect to our database). Would there be an issue if I remove this from the context and just import the db directly from the src/server/db/index.ts file? Default way of doing this in T3:
create: publicProcedure
.input(z.object({ name: z.string().min(1) }))
.mutation(async ({ ctx, input }) => {
// simulate a slow db call
await new Promise((resolve) => setTimeout(resolve, 1000));

await ctx.db.insert(posts).values({ // NOTICE WE GRAB THE DB FROM CONTEXT
name: input.name,
});
}),
create: publicProcedure
.input(z.object({ name: z.string().min(1) }))
.mutation(async ({ ctx, input }) => {
// simulate a slow db call
await new Promise((resolve) => setTimeout(resolve, 1000));

await ctx.db.insert(posts).values({ // NOTICE WE GRAB THE DB FROM CONTEXT
name: input.name,
});
}),
What I would rather do:
import { db } from "@/server/db";
...
create: publicProcedure
.input(z.object({ name: z.string().min(1) }))
.mutation(async ({ input }) => {
// simulate a slow db call
await new Promise((resolve) => setTimeout(resolve, 1000));

await db.insert(posts).values({ // NOTICE WE GRAB THE DB FROM CONTEXT
name: input.name,
});
}),
import { db } from "@/server/db";
...
create: publicProcedure
.input(z.object({ name: z.string().min(1) }))
.mutation(async ({ input }) => {
// simulate a slow db call
await new Promise((resolve) => setTimeout(resolve, 1000));

await db.insert(posts).values({ // NOTICE WE GRAB THE DB FROM CONTEXT
name: input.name,
});
}),
Here's how it's being added to context now, I'd rather not use this? I feel like it's there for a reason though and I can't figure out why 😦
export const createTRPCContext = async (opts: { headers: Headers }) => {
return {
db,
...opts,
};
};
export const createTRPCContext = async (opts: { headers: Headers }) => {
return {
db,
...opts,
};
};
11 replies
DTDrizzle Team
Created by DYELbrah on 12/22/2023 in #help
$with using sql operator doesn't return type?
const companiesWithPrimaryAddress = db
.$with("companiesWithPrimaryAddress")
.as(
db
.select({
name: company.name,
phone: company.phone,
email: company.email,
notes: company.notes,
isTaxExempt: company.isTaxExempt,
addressType: address.addressType,
primaryAddress: sql<string>`CONCAT(address_one, ' ', address_two, ' ', city, ' ', state, ' ', zip, ' ', country)`,
})
.from(company)
.leftJoin(address, eq(company.name, address.entityId))
.where(eq(address.addressType, "primary")),
);
const companiesWithPrimaryAddress = db
.$with("companiesWithPrimaryAddress")
.as(
db
.select({
name: company.name,
phone: company.phone,
email: company.email,
notes: company.notes,
isTaxExempt: company.isTaxExempt,
addressType: address.addressType,
primaryAddress: sql<string>`CONCAT(address_one, ' ', address_two, ' ', city, ' ', state, ' ', zip, ' ', country)`,
})
.from(company)
.leftJoin(address, eq(company.name, address.entityId))
.where(eq(address.addressType, "primary")),
);
Whenever I make a call to this table using db.with(companiesWithPrimaryAddress) the type of primaryAddress is returned as 'never'? Anyone know why?
6 replies
DTDrizzle Team
Created by DYELbrah on 9/10/2023 in #help
Expected 1 arguments, but got 2.ts(2554)
Anyone know why I'm getting this type error?
await tx
.update(transactionTemplateEntries)
.set({
description: "",
isDefault: false,
amountExpression: expressionId,
templateId: input.templateId,
paymentMethodId: input.paymentMethodId,
accountId: input.accountId,
effectType: input.effectType,
})
.where(eq(transactionTemplateEntries.id, input.id)),
await tx
.update(transactionTemplateEntries)
.set({
description: "",
isDefault: false,
amountExpression: expressionId,
templateId: input.templateId,
paymentMethodId: input.paymentMethodId,
accountId: input.accountId,
effectType: input.effectType,
})
.where(eq(transactionTemplateEntries.id, input.id)),
2 replies
DTDrizzle Team
Created by DYELbrah on 9/7/2023 in #help
Timestamp from Postgres returns date object despite schema using string mode?
Hello team, I'm confused if this is a bug because I haven't seen any other threads about it. When I define my timestamp columns like this:
effectiveDate: timestamp("effective_date", { withTimezone: true, mode: 'string' }).notNull(),
effectiveDate: timestamp("effective_date", { withTimezone: true, mode: 'string' }).notNull(),
How come the return type of the column when I fetch data says string, however when I log the value or use it anywhere, it's actually a JS date object? Is this a known issue?
15 replies
DTDrizzle Team
Created by DYELbrah on 9/4/2023 in #help
Does throwing a regular javascript error inside a transaction, roll back automatically?
Curious if I need to actually call tx.rollback()? Or if we reach a regular error, or lets say a Postgres error occurs at some step, will everything be automatically rolled back? Or do we have to always try catch and rollback in the catch/finally block?
3 replies
DTDrizzle Team
Created by DYELbrah on 8/19/2023 in #help
date column not being returned as string by drizzle
Hello, I have the following table:
export const productSnapshot = pgTable("product_snapshot", {
productId: text("product_id").notNull().references(() => product.id),
// You can use { mode: "bigint" } if numbers are exceeding js number limitations
version: bigint("version", { mode: "number" }).notNull(),
material: text("material").notNull(),
shape: text("shape").notNull(),
alloy: text("alloy").notNull(),
// You can use { mode: "bigint" } if numbers are exceeding js number limitations
thickness: bigint("thickness", { mode: "number" }).notNull(),
dimension: text("dimension").notNull(),
// You can use { mode: "bigint" } if numbers are exceeding js number limitations
weightByFoot: bigint("weight_by_foot", { mode: "number" }).notNull(),
description: text("description").notNull(),
effectiveDate: timestamp("effective_date", { withTimezone: true, mode: 'string' }).defaultNow().notNull(),
},
export const productSnapshot = pgTable("product_snapshot", {
productId: text("product_id").notNull().references(() => product.id),
// You can use { mode: "bigint" } if numbers are exceeding js number limitations
version: bigint("version", { mode: "number" }).notNull(),
material: text("material").notNull(),
shape: text("shape").notNull(),
alloy: text("alloy").notNull(),
// You can use { mode: "bigint" } if numbers are exceeding js number limitations
thickness: bigint("thickness", { mode: "number" }).notNull(),
dimension: text("dimension").notNull(),
// You can use { mode: "bigint" } if numbers are exceeding js number limitations
weightByFoot: bigint("weight_by_foot", { mode: "number" }).notNull(),
description: text("description").notNull(),
effectiveDate: timestamp("effective_date", { withTimezone: true, mode: 'string' }).defaultNow().notNull(),
},
Whenever I try to query the effectiveDate from the drizzle table, TypeScript says the return type will be string, however, I verified that I am actually receiving a Date object. I am using mode 'string' as you can see. Is this a known issue?
9 replies
DTDrizzle Team
Created by DYELbrah on 8/14/2023 in #help
table not being camelcased when using joins?
For some reason when I use the following query:
const getProductByIdResult = await db
.select()
.from(product)
.leftJoin(productSnapshot, eq(product.id, productSnapshot.productId))
.where(sql`product_id = ${input.productId}`)
.orderBy(desc(productSnapshot.version))
.limit(1);
const getProductByIdResult = await db
.select()
.from(product)
.leftJoin(productSnapshot, eq(product.id, productSnapshot.productId))
.where(sql`product_id = ${input.productId}`)
.orderBy(desc(productSnapshot.version))
.limit(1);
I am geting the following type back:
const getProductByIdResult: {
product: {
id: string;
};
product_snapshot: {
alloy: string;
shape: string;
material: string;
productId: string;
description: string;
effectiveDate: string | null;
version: number;
thickness: number;
dimension: string;
weightByFoot: number;
} | null;
}[]
const getProductByIdResult: {
product: {
id: string;
};
product_snapshot: {
alloy: string;
shape: string;
material: string;
productId: string;
description: string;
effectiveDate: string | null;
version: number;
thickness: number;
dimension: string;
weightByFoot: number;
} | null;
}[]
Why is the name of the table not being camel cased?
12 replies
TTCTheo's Typesafe Cult
Created by DYELbrah on 7/24/2023 in #questions
DI libraries and using Singletons in NextJS / T3?
Hey guys, I'm just curious if I'm using a Dependency Injection (DI) library within the T3 stack (using NextJS + TRPC), is there any benefit at all to using services as singletons? Wouldn't my container definitions and everything basically just get restarted for every request, thus not really mattering since the same instance won't be used?
2 replies
TTCTheo's Typesafe Cult
Created by DYELbrah on 7/18/2023 in #questions
Fresh T3 install, auth.ts error: "next-auth" has no exported member getServerSession ???
Anyone know why I'm getting this typescript error was the function deprecated or removed recently?
3 replies