Skip to content

Instantly share code, notes, and snippets.

@kyrregjerstad
Created June 26, 2024 17:16
Show Gist options
  • Save kyrregjerstad/736108f9235601a65ae8642d6acba9f2 to your computer and use it in GitHub Desktop.
Save kyrregjerstad/736108f9235601a65ae8642d6acba9f2 to your computer and use it in GitHub Desktop.
const user = createTable("user", {
  id: serial("id").primaryKey(),
  passwordHash: varchar("passwordHash", { length: 255 }).notNull(),
  email: varchar("email", { length: 255 }).notNull().unique(),
  createdAt: timestamp("createdAt", { withTimezone: true }).notNull().defaultNow(),
  updatedAt: timestamp("updatedAt", { withTimezone: true }),
});

export const userRelations = relations(user, ({ one, many }) => ({
  client: one(client),
  staff: one(staff),
  sessions: many(session, { relationName: "sessionUser" }),
}));

const client = createTable("client", {
  id: serial("id").primaryKey(),
  userId: bigint("userId", { mode: "number" }).references(() => user.id),
  contactId: bigint("contactId", { mode: "number" }).notNull().references(() => contact.id),
  createdAt: timestamp("createdAt", { withTimezone: true }).notNull().defaultNow(),
  updatedAt: timestamp("updatedAt", { withTimezone: true }),
  isVerified: boolean("isVerified").notNull(),
});

export const clientRelations = relations(client, ({ one }) => ({
  contact: one(contact, { fields: [client.contactId], references: [contact.id] }),
  user: one(user, { fields: [client.userId], references: [user.id] }),
}));

const staff = createTable("staff", {
  id: serial("id").primaryKey(),
  userId: bigint("userId", { mode: "number" }).notNull().references(() => user.id),
  contactId: bigint("contactId", { mode: "number" }).notNull().references(() => contact.id),
});

export const staffRelations = relations(staff, ({ one }) => ({
  contact: one(contact, { fields: [staff.contactId], references: [contact.id] }),
  user: one(user, { fields: [staff.userId], references: [user.id] }),
}));

const contact = createTable("contact", {
  id: serial("id").primaryKey(),
  contactEmail: varchar("contactEmail", { length: 255 }).notNull(),
  firstName: varchar("firstName", { length: 255 }).notNull(),
  lastName: varchar("lastName", { length: 255 }).notNull(),
  address: varchar("address", { length: 255 }),
  phoneNumber: varchar("phoneNumber", { length: 255 }),
  createdAt: timestamp("createdAt", { withTimezone: true }).notNull().defaultNow(),
  updatedAt: timestamp("updatedAt", { withTimezone: true }),
});

export const contactRelations = relations(contact, ({ one }) => ({
  staff: one(staff),
  client: one(client),
}));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment