xxxxx
xxxxx
DTDrizzle Team
Created by xxxxx on 10/12/2024 in #help
Using drizzle in monorepo
I am building a project where I have 2 next.js applications. Let's call them admin and web. The admin is responsible for CRUD operations to database and allows the admin user to manage content on their website, while web interacts with the database in a read-only way, displaying the content for the user. I want to share a single drizzle db client between both projects because this keeps types for both projects synced and I don't have to write changes in 2 places whenever I want to modify something schema related. How can I achieve such a thing in a turbo monorepo or any other way?
3 replies
DTDrizzle Team
Created by xxxxx on 9/28/2024 in #help
Don't understand many-to-many relationships
I have a database setup where a project can have multiple members and members can belong to many projects. A many-to-many relationship. I've created a join table UserToProject which has one-to-many relationship with the said tables. The thing is for some reason it does not work and I get an error: There is not enough information to infer relation "__public__.Project.userToProject" Here is my schema code:
export const User = pgTable("user", {
id: uuid("id").primaryKey().defaultRandom(),
username: varchar("username", { length: 255 }).notNull(),
email: varchar("email", { length: 255 }).notNull(),
password: varchar("password", { length: 255 }).notNull(),
createdAt: timestamp("created_at").defaultNow(),
})

export const UserRelations = relations(User, ({ many }) => ({
userToProject: many(UserToProject, { relationName: "projects" }),
}))

export const Project = pgTable("project", {
id: uuid("id").primaryKey().defaultRandom(),
name: varchar("name", { length: 255 }).notNull(),
website: jsonb("website"),
createdAt: timestamp("created_at").defaultNow(),
})

export const ProjectRelations = relations(Project, ({ many }) => ({
userToProject: many(UserToProject, { relationName: "members" }),
}))

export const UserToProject = pgTable(
"user_to_project",
{
userId: uuid("user_id")
.references(() => User.id)
.notNull(),
projectId: uuid("project_id")
.references(() => Project.id)
.notNull(),
},
(t) => ({
pk: primaryKey({ columns: [t.userId, t.projectId] }),
}),
)

export const UserToProjectRelations = relations(UserToProject, ({ one }) => ({
user: one(User, {
fields: [UserToProject.userId],
references: [User.id],
}),
project: one(Project, {
fields: [UserToProject.projectId],
references: [Project.id],
}),
}))
export const User = pgTable("user", {
id: uuid("id").primaryKey().defaultRandom(),
username: varchar("username", { length: 255 }).notNull(),
email: varchar("email", { length: 255 }).notNull(),
password: varchar("password", { length: 255 }).notNull(),
createdAt: timestamp("created_at").defaultNow(),
})

export const UserRelations = relations(User, ({ many }) => ({
userToProject: many(UserToProject, { relationName: "projects" }),
}))

export const Project = pgTable("project", {
id: uuid("id").primaryKey().defaultRandom(),
name: varchar("name", { length: 255 }).notNull(),
website: jsonb("website"),
createdAt: timestamp("created_at").defaultNow(),
})

export const ProjectRelations = relations(Project, ({ many }) => ({
userToProject: many(UserToProject, { relationName: "members" }),
}))

export const UserToProject = pgTable(
"user_to_project",
{
userId: uuid("user_id")
.references(() => User.id)
.notNull(),
projectId: uuid("project_id")
.references(() => Project.id)
.notNull(),
},
(t) => ({
pk: primaryKey({ columns: [t.userId, t.projectId] }),
}),
)

export const UserToProjectRelations = relations(UserToProject, ({ one }) => ({
user: one(User, {
fields: [UserToProject.userId],
references: [User.id],
}),
project: one(Project, {
fields: [UserToProject.projectId],
references: [Project.id],
}),
}))
Also a quick side question, are the docs getting worse, or am I going insane? I swear I cannot find the simplest things, even using the search.
1 replies
DTDrizzle Team
Created by xxxxx on 9/11/2024 in #help
Realtime connection to the database
No description
1 replies
DTDrizzle Team
Created by xxxxx on 7/15/2024 in #help
How to make one object have 2 different relationships with another object.
I have 2 tables Product and Media. The product has a thumbnail and also images of the product. The thumbnail is one media and images are many media. So in short I have to have one-to-one relation between Product.thumbnail and Media, and a one-to-many relation between Product.images and Media. My code follows the docs about relations but it does not work (my guess because of circular references).
export const Product = pgTable("product", {
id: uuid("id").primaryKey().defaultRandom(),
title: varchar("title", { length: 128 }).notNull(),
description: varchar("description", { length: 1024 }),
// the product "owns" the Media in thumbnail
thumbnailId: uuid("thumbnail_id").references(() => Media.id),
})

export const Media = pgTable("media", {
id: uuid("id").primaryKey().defaultRandom(),
url: varchar("url", { length: 512 }).notNull(),
// needs to reference productId to correctly implement a one-to-many relation
productId: uuid("product_id").references(() => Product.id),
})

export const ProductRelations = relations(Product, ({ one, many }) => ({
thumbnail: one(Media, {
fields: [Product.thumbnailId],
references: [Media.id],
}),
images: many(Media),
}))

export const MediaRelations = relations(Media, ({ one, many }) => ({
productThumbnail: one(Product),
productImages: one(Product, {
fields: [Media.productId],
references: [Product.id],
}),
}))
export const Product = pgTable("product", {
id: uuid("id").primaryKey().defaultRandom(),
title: varchar("title", { length: 128 }).notNull(),
description: varchar("description", { length: 1024 }),
// the product "owns" the Media in thumbnail
thumbnailId: uuid("thumbnail_id").references(() => Media.id),
})

export const Media = pgTable("media", {
id: uuid("id").primaryKey().defaultRandom(),
url: varchar("url", { length: 512 }).notNull(),
// needs to reference productId to correctly implement a one-to-many relation
productId: uuid("product_id").references(() => Product.id),
})

export const ProductRelations = relations(Product, ({ one, many }) => ({
thumbnail: one(Media, {
fields: [Product.thumbnailId],
references: [Media.id],
}),
images: many(Media),
}))

export const MediaRelations = relations(Media, ({ one, many }) => ({
productThumbnail: one(Product),
productImages: one(Product, {
fields: [Media.productId],
references: [Product.id],
}),
}))
These lines cause a TS error:
thumbnailId: uuid("thumbnail_id").references(() => Media.id),
productId: uuid("product_id").references(() => Product.id),
thumbnailId: uuid("thumbnail_id").references(() => Media.id),
productId: uuid("product_id").references(() => Product.id),
Function implicitly has return type 'any' because it does not have a return type annotation and is referenced directly or indirectly in one of its return expressions.
Function implicitly has return type 'any' because it does not have a return type annotation and is referenced directly or indirectly in one of its return expressions.
How do I correctly implement 2 different relations between 2 tables?
16 replies
DTDrizzle Team
Created by xxxxx on 7/14/2024 in #help
How to get good at Drizzle?
Hello I am currently having a huge problem with Drizzle, and relational databases in general. I start writing my schema, but after finishing a few tables (5-10) I get overwhelmed by the amount of objects and relations happening between them and don't know what to do, and how to properly connect them together. At this point I just delete my entire schema and start writing it from scratch, in hopes of implementing it correctly this time. This process repeats a few times and I never actually finish the database. I am also very confused when thinking about the later part of the application, where I would have to insert the data, as nested objects would have to be inserted in multiple layers which sounds so complicated at scale. Example having a product with variants of that product which have prices. I would have to create a price, then assign the price_id to a variant, then do the same for a product. The logic seems backwards, so instead of thinking about inserting a product I first have to insert a price then variant then product. And all that at just 3 levels of nesting. The example above would be even messier in code, while I am thinking of inserting something more elegant like this:
{
"product": {
"id": "b0a0c9f4-a4d0-4f5f-b8b6-e4a5d5c0b1d2",
"title": "Test Product",
"description": "This is a test product",
"variants": [
{
"options": [
{
"key": "color",
"value": "red"
},
{
"key": "size",
"value": "small"
}
],
"price": {
"amount": 100,
"currency": {
"code": "USD",
"name": "United States Dollar"
}
}
},
]
}
}
{
"product": {
"id": "b0a0c9f4-a4d0-4f5f-b8b6-e4a5d5c0b1d2",
"title": "Test Product",
"description": "This is a test product",
"variants": [
{
"options": [
{
"key": "color",
"value": "red"
},
{
"key": "size",
"value": "small"
}
],
"price": {
"amount": 100,
"currency": {
"code": "USD",
"name": "United States Dollar"
}
}
},
]
}
}
Do you have any tips on staying organised and not getting overwhelmed when writing Drizzle schemas?
7 replies
DTDrizzle Team
Created by xxxxx on 7/13/2024 in #help
How to create this kind of relation
No description
3 replies
DTDrizzle Team
Created by xxxxx on 6/12/2024 in #help
drizzle-kit defineConfig no "pg" driver available.
There seems to be no type for "pg" in the driver field of defineConfig in drizzle-kit.
import { defineConfig } from "drizzle-kit"

export default defineConfig({
schema: "/src/db/schema.ts",
out: "/src/db/migrations",
driver: "pg", // does not exist
// the only ones that are an option are: "aws-data-api", "d1-http", "expo", "turso"
})
import { defineConfig } from "drizzle-kit"

export default defineConfig({
schema: "/src/db/schema.ts",
out: "/src/db/migrations",
driver: "pg", // does not exist
// the only ones that are an option are: "aws-data-api", "d1-http", "expo", "turso"
})
3 replies
DTDrizzle Team
Created by xxxxx on 5/3/2024 in #help
PostgresError: column <column_name> referenced in foreign key constraint does not exist
I have this simple schema in which I am trying to create a one-to-many relationship between option and optionValue tables. However when running migration script I get the following error. PostgresError: column "option_id" referenced in foreign key constraint does not exist
import { pgPrefixIdKey } from "@/utils/drizzle"
import { relations } from "drizzle-orm"
import { pgTable, text, varchar } from "drizzle-orm/pg-core"

export const option = pgTable("option", {
id: pgPrefixIdKey({ prefix: "option" }).primaryKey(),
name: varchar("name", { length: 64 }).notNull(),
})

export const optionRelations = relations(option, ({ many }) => ({
values: many(optionValue),
}))

export const optionValue = pgTable("option_value", {
id: pgPrefixIdKey({ prefix: "option_value" }).primaryKey(),
value: varchar("value", { length: 64 }).notNull(),
optionId: text("option_id")
.notNull()
.references(() => option.id),
})

export const optionValueRelations = relations(optionValue, ({ one }) => ({
option: one(option, {
fields: [optionValue.optionId],
references: [option.id],
}),
}))
import { pgPrefixIdKey } from "@/utils/drizzle"
import { relations } from "drizzle-orm"
import { pgTable, text, varchar } from "drizzle-orm/pg-core"

export const option = pgTable("option", {
id: pgPrefixIdKey({ prefix: "option" }).primaryKey(),
name: varchar("name", { length: 64 }).notNull(),
})

export const optionRelations = relations(option, ({ many }) => ({
values: many(optionValue),
}))

export const optionValue = pgTable("option_value", {
id: pgPrefixIdKey({ prefix: "option_value" }).primaryKey(),
value: varchar("value", { length: 64 }).notNull(),
optionId: text("option_id")
.notNull()
.references(() => option.id),
})

export const optionValueRelations = relations(optionValue, ({ one }) => ({
option: one(option, {
fields: [optionValue.optionId],
references: [option.id],
}),
}))
I am new to postgres and relational databases in general and I don't get what is causing this. What I think I am doing is adding a values column to my option table, and then assigning optionId column of my optionValue table to referenced value of option.id column. I am pretty sure this is how it's also realized in the docs, but I might've overlooked something...
1 replies
DTDrizzle Team
Created by xxxxx on 5/3/2024 in #help
Create slug based on title field.
I currently have a product schema that has title field that is a nonNull text. I want to create a slug that is automatically generated. My current approach to this is using the .$defaultFn((title) => createSlug(title)) but I am struggling to find a way to reference title in the defaultFn. Is there some way to do this?
5 replies
DTDrizzle Team
Created by xxxxx on 5/2/2024 in #help
add a prefix to UUID?
I am wondering if there is a functionality where I can add a custom prefix the uuid's. These uuids would be used as a pirmary key in my case. The end result would be something like this: product_9B4F49D6F35C49FEA0dCC579A8ED4755
8 replies