Skip to main content

Schema Reference

All database tables are defined in lib/db/schema.ts. This document catalogs every table, its key columns, relationships, and purpose.

Users & Authentication

users

Core user table, used by NextAuth.js for authentication.

ColumnTypeNotes
idtext (PK)UUID, auto-generated
emailtextUnique
imagetextProfile image URL
emailVerifiedtimestampEmail verification date
passwordHashtextBcrypt hash for credentials auth
createdAttimestampAuto-set
updatedAttimestampAuto-set
deletedAttimestampSoft delete

Indexes: users_created_at_idx

accounts

OAuth and credentials account links, following the NextAuth.js adapter schema.

ColumnTypeNotes
userIdtext (FK)References users.id (cascade delete)
typetextAccount type (oauth, credentials, etc.)
providertextProvider name (google, github, credentials)
providerAccountIdtextProvider-specific account ID
emailtextAccount email
passwordHashtextFor client credentials auth
refresh_tokentextOAuth refresh token
access_tokentextOAuth access token
expires_atintegerToken expiration

Primary key: Composite on (provider, providerAccountId) Indexes: accounts_email_idx, accounts_provider_idx

sessions

Active user sessions.

ColumnTypeNotes
sessionTokentext (PK)Session identifier
userIdtext (FK)References users.id
expirestimestampSession expiration

verificationTokens

Email verification tokens.

ColumnTypeNotes
identifiertextUser identifier
emailtextEmail address
tokentextVerification token
expirestimestampToken expiration

Primary key: Composite on (identifier, token)

authenticators

WebAuthn/FIDO2 credential storage.

ColumnTypeNotes
credentialIDtextUnique credential identifier
userIdtext (FK)References users.id
providerAccountIdtextProvider account reference
credentialPublicKeytextPublic key for verification
counterintegerAuthentication counter

passwordResetTokens

Password reset tokens for forgot-password flow.

ColumnTypeNotes
idtext (PK)UUID
emailtextTarget email
tokentextUnique reset token
expirestimestampToken expiration

activityLogs

Tracks user and client activities for audit purposes.

ColumnTypeNotes
idserial (PK)Auto-increment
userIdtext (FK)References users.id (nullable)
clientIdtext (FK)References clientProfiles.id (nullable)
actiontextActivity type (SIGN_UP, SIGN_IN, etc.)
timestamptimestampWhen the activity occurred
ipAddressvarchar(45)Client IP address

Indexes: activity_logs_user_idx, activity_logs_timestamp_idx, activity_logs_action_idx

Roles & Permissions

roles

Role definitions for RBAC.

ColumnTypeNotes
idtext (PK)Role identifier (e.g., "admin", "client")
nametextUnique role name
descriptiontextHuman-readable description
isAdminbooleanWhether this is an admin role
statustext"active" or "inactive"
created_bytextWho created the role

permissions

Granular permission definitions.

ColumnTypeNotes
idtext (PK)UUID
keytextUnique permission key (e.g., "items:create")
descriptiontextHuman-readable description

rolePermissions

Many-to-many join table linking roles to permissions.

ColumnTypeNotes
roleIdtext (FK)References roles.id (cascade)
permissionIdtext (FK)References permissions.id (cascade)

Primary key: Composite on (roleId, permissionId)

userRoles

Many-to-many join table linking users to roles.

ColumnTypeNotes
userIdtext (FK)References users.id (cascade)
roleIdtext (FK)References roles.id (cascade)

Primary key: Composite on (userId, roleId)

Client Profiles

clientProfiles

Extended profile information for registered client users.

ColumnTypeNotes
idtext (PK)UUID
userIdtext (FK)References users.id (unique, cascade)
emailtextClient email
nametextFull name
displayNametextDisplay name
usernametextUnique username
biotextUser biography
jobTitletextProfessional title
companytextCompany name
industrytextIndustry sector
phonetextPhone number
websitetextPersonal website
locationtextLocation string
avatartextAvatar URL
accountTypetext"individual", "business", or "enterprise"
statustext"active", "inactive", "suspended", "banned", "trial"
plantext"free", "standard", or "premium"
timezonetextTimezone (default "UTC")
languagetextPreferred language (default "en")
countrytextCountry code
currencytextPreferred currency (default "USD")
defaultLatitudedoubleDefault location latitude
defaultLongitudedoubleDefault location longitude
twoFactorEnabledboolean2FA status
totalSubmissionsintegerSubmission count
warningCountintegerModeration warning count
suspendedAttimestampWhen suspended
bannedAttimestampWhen banned

Indexes: Multiple indexes on userId, email, status, plan, accountType, username, createdAt

Content & Engagement

comments

User comments on items.

ColumnTypeNotes
idtext (PK)UUID
contenttextComment text
userIdtext (FK)References clientProfiles.id
itemIdtextItem slug
ratingintegerRating (0-5)
editedAttimestampLast edit time
deletedAttimestampSoft delete

votes

Upvote/downvote on items.

ColumnTypeNotes
idtext (PK)UUID
userIdtext (FK)References clientProfiles.id
itemIdtextItem slug
voteTypetext"upvote" or "downvote"

Unique index: (userId, itemId) -- one vote per user per item

favorites

User favorites (bookmarks).

ColumnTypeNotes
idtext (PK)UUID
userIdtext (FK)References users.id
itemSlugtextItem slug
itemNametextDenormalized item name
itemIconUrltextDenormalized item icon
itemCategorytextDenormalized category

Unique index: (userId, itemSlug)

itemViews

Tracks unique daily item views for analytics.

ColumnTypeNotes
idtext (PK)UUID
itemIdtextItem slug
viewerIdtextAnonymous cookie-based viewer ID
viewedDateUtctextDate in YYYY-MM-DD format
viewedAttimestampExact view time

Unique index: (itemId, viewerId, viewedDateUtc) -- one view per viewer per day

Subscriptions & Payments

subscriptions

User subscription records supporting multiple payment providers.

ColumnTypeNotes
idtext (PK)UUID
userIdtext (FK)References users.id
planIdtextPlan identifier (free, standard, premium)
statustextactive, cancelled, expired, pending, paused
paymentProvidertextstripe, lemonsqueezy, polar, solidgate
subscriptionIdtextProvider subscription ID
customerIdtextProvider customer ID
autoRenewalbooleanAuto-renewal enabled
cancelAtPeriodEndbooleanCancel at period end
amountintegerSubscription amount (cents)
currencytextCurrency code
intervaltextBilling interval (month, year)

Indexes: user_subscription_idx, subscription_status_idx, provider_subscription_idx (unique)

subscriptionHistory

Audit trail for subscription changes.

ColumnTypeNotes
idtext (PK)UUID
subscriptionIdtext (FK)References subscriptions.id
actiontextChange action
previousStatustextStatus before change
newStatustextStatus after change

paymentProviders

Registry of available payment providers.

ColumnTypeNotes
idtext (PK)UUID
nametextProvider name (unique)
isActivebooleanWhether provider is enabled

paymentAccounts

Links users to their payment provider accounts.

ColumnTypeNotes
idtext (PK)UUID
userIdtext (FK)References users.id
providerIdtext (FK)References paymentProviders.id
customerIdtextProvider customer ID

Unique indexes: (userId, providerId), (customerId, providerId)

Admin & Moderation

notifications

In-app admin notifications.

ColumnTypeNotes
idtext (PK)UUID
userIdtext (FK)References users.id
typetextitem_submission, comment_reported, etc.
titletextNotification title
messagetextNotification body
isReadbooleanRead status

reports

Content report system for items and comments.

ColumnTypeNotes
idtext (PK)UUID
contentTypetext"item" or "comment"
contentIdtextReported content ID
reasontextspam, harassment, inappropriate, other
statustextpending, reviewed, resolved, dismissed
resolutiontextcontent_removed, user_warned, etc.
reportedBytext (FK)References clientProfiles.id
reviewedBytext (FK)References users.id

moderationHistory

Complete moderation action history.

ColumnTypeNotes
idtext (PK)UUID
userIdtext (FK)References clientProfiles.id
actiontextwarn, suspend, ban, unsuspend, unban, content_removed
reportIdtext (FK)References reports.id
performedBytext (FK)References users.id
detailsjsonbAdditional context

itemAuditLogs

Tracks changes to items in the admin panel.

ColumnTypeNotes
idtext (PK)UUID
itemIdtextItem slug (not FK; items are in Git)
itemNametextDenormalized item name
actiontextcreated, updated, status_changed, reviewed, deleted, restored
changesjsonbField-level change details
performedBytext (FK)References users.id

Other Tables

sponsorAds

Sponsored item advertisements with full payment lifecycle.

Key columns: userId, itemSlug, status (pending_payment, pending, rejected, active, expired, cancelled), interval (weekly, monthly), amount, paymentProvider, subscriptionId.

companies / itemsCompanies

Company records and item-company associations for directory listings.

surveys / surveyResponses

Survey builder with JSON-based question definitions and response storage.

twentyCrmConfig / integrationMappings

CRM integration tables for Twenty CRM sync functionality. The config table enforces a singleton pattern (only one row allowed).

newsletterSubscriptions

Email newsletter subscription tracking with subscribe/unsubscribe timestamps.

seedStatus

Singleton table tracking database seeding status (seeding, completed, failed) to prevent concurrent seed operations.

Type Exports

The schema file exports TypeScript types for every table using Drizzle's inference:

export type User = typeof users.$inferSelect;
export type NewUser = typeof users.$inferInsert;
export type Subscription = typeof subscriptions.$inferSelect;
export type NewSubscription = typeof subscriptions.$inferInsert;
// ... and so on for all tables

These types are used throughout the application for type-safe database operations.