FitStack - V2 database schema

The FitStack - V2 database schema by Colton Bristow has 258 tables (Studios, Trainers, TrainerAbsences, Courses and 254 more), 2991 columns and 446 relationships, documented column by column.

ER diagram of the FitStack - V2 schema, showing 258 tables and their relationships
FIG. 1: entity relationship diagram, 258 tables
Tables
258
Columns
2991
Relationships
446
Enums
118

Tables (258)

Tables in the FitStack - V2 schema
TableColumnsDescription
Studios13Replaces ClassRooms (81). Glossary: Studio; avoid Room, Class Room.
Trainers11An Employee who leads Sessions. Replaces GymCoaches (80), which required an approved Coach.
TrainerAbsences9Sessions inside an absence are flagged for re-staffing; GymTrainerCapability.ManageAbsences gates it.
Courses21The template Sessions are made from. Glossary: Course; avoid Class.
CourseSchedules12The timetable rule. A job materialises Sessions 8 weeks ahead; editing a rule regenerates Sessions from a date forward, keeping those with Enrolments.
Sessions15One occurrence. Replaces Classes (81). Glossary: Session; avoid Class.
SessionCodes4How a Student proves they are in the room. From ClassCodes (81). No audit columns.
CoursePrices4Lets a Course cost different amounts by Membership Offer. From ClassPrices (81).
Enrolments17One Student's place in one Session. Replaces ClassAttendees (81). Glossary: Enrolment; avoid Booking.
Brands10The maker of an Equipment Entry. Glossary: Brand; avoid Manufacturer.
EquipmentKinds9MODERATED reference data, renamed from EquipmentTypes (80). What a plan needs — "a shoulder press machine", not "BowFlex #12341". An Entry may carry several Kinds: an adjustable bench is Flat + Incline + Decline.
EquipmentKindLinks2N:M. Was EquipmentEquipmentTypes (80). COMPOSITE PK.
EquipmentSettingOptions5The positions an Entry supports (Training: Equipment Setting). No audit columns: replaced wholesale with the Entry.
KindSubstitutes5Curated by FitStack admins. No audit columns.
ExerciseKinds5What an exercise needs. Complements ExerciseEquipments (21), which links to concrete Entries and stays for imported data; the resolver prefers Kinds. The "available here / use instead" answer for a Gym is: Units whose Entry has the Kind (and Setting) -> KindSubstitutes by Closeness.
GymZones9
GymEquipmentUnits17ONE ROW PER PHYSICAL UNIT. Replaces GymEquipment (80), which was one row per Entry per Gym with no way to say "the third one is out of order". The UI groups Units under their Entry ("Iso-Lateral Row × 3").
GymEquipmentUnitPhotos3
GymEquipmentMaintenance12
GymEquipmentReports13Members report a broken machine from the FitStack app; staff resolve it. Extends the live GymEquipmentReport (UserId, GymId, EquipmentId) with the Unit, text and a status.
GymProducts16Glossary: Gym Product; never "Product" on its own in FitStack Gym copy.
GymProductImages3
GymProductVariants13
GymStock6Merchandise only. Rentals and Services carry no Stock. No soft delete: a row is the count.
GymStockMovements8Append-only ledger; OnHand is the sum. No audit columns.
Orders23One sale. Glossary: Order; a Draft Order is the cart.
OrderLines7No audit columns: lines live and die with the Order.
MembershipAddOns12Glossary: Add-on. A locker rental attached to a Membership.
StripeTerminalReaders9
Sites15
SiteVersions9Version history for rollback. No soft delete: versions are kept.
SiteDomains13A Company's own domain serving its Site (ADR 0012: via the Firebase Hosting API).
Users37Does NOT inherit `Auditable` — it hand-rolls `IsDeleted` and `CreatedAt` and has no `ModifiedAt`/`DeletedAt`. Consequence: **no global soft-delete query filter applies to Users.** Deleted users are returned by every query unless the caller filters explicitly.
Roles4Seeded from the `UserType` enum by RoleSeeder.cs — one role per member.
UserRoles2
UserClaims4
RoleClaims4Claims of type `permission` here are folded into the JWT by JwtTokenGenerator.
UserLogins4External login links — Google and Apple OAuth.
AspNetUserTokens4Still present in the model snapshot even though `modelBuilder.Ignore<IdentityUserToken<string>>()` is called. Distinct from the application table `UserTokens` below — a naming collision worth renaming in v2.
UserTokens19AggregateRoot, not Auditable — `LastModifiedAt`, and no soft delete. Rows are only ever status-flipped to Revoked, never deleted, and no cleanup job exists — the table grows without bound per user. Never eager-load this collection off Users.
TokenEvents9Append-only audit of a token lifecycle. Entity base, no audit columns.
PasskeyCredentials14FIDO2 / WebAuthn. AggregateRoot base.
Permissions4Catalogue of named capabilities. Emitted into the JWT as `permission` claims by Infrastructure/Security/Tokens/JwtTokenGenerator.cs, from two sources: role claims of type `permission`, and direct user grants below. No audit columns — not `Auditable`, so no soft-delete filter.
RolePermissions3Join: a role confers a permission. No audit columns.
UserPermissions5Direct user grant, bypassing roles. C# class is `UserPermission`; the table is `UserPermissions`. **Missing dimensions, by design:** there is no subject ("on whose data"), no expiry, and no revocation record — only `GrantedAt`. Adding those here would make one table mean two different things, so scoped coach access lives in its own tables. Also missing: a unique index on `(UserId, PermissionId)`, so the same grant can be inserted twice.
UserProfiles22The five inline `*Url` columns duplicate what SocialTags models properly. v2 should pick one; keeping both guarantees they disagree.
Followings8Directed self-referencing follow edge.
UserBlocks8A block should hard-stop a coaching request (see 61). Nothing enforces that today — it is application logic, and it was absent from v1.
SocialPlatforms3DESIGN ONLY — not yet in the live database.
SocialTags4DESIGN ONLY. Generic social link, attachable to a user, gym or coach.
UserSocialTags2DESIGN ONLY.
UserSettings8Principal of Users.SettingsId (the FK sits on Users). No audit columns.
NotificationSettings4241 columns, one per event kind, each a `NotificationChannel` defaulting to PushNotification. Every new notification kind is a schema migration — the coaching domain adds five (see 72), which is the point at which a `(UserId, EventKey, Channel)` row-per-preference table starts to pay for itself. Flagged, not changed, to keep v2 diffable against production. No audit columns.
Media10Single media table for the whole product — avatars, post images, product photos, certification scans. Many referencing columns (`HeroMediaId`, `MediaId` on coach certifications, `ImageId` on Muscles) are loose `uuid` with no FK; v2 makes the coaching ones real FKs.
ProcessedWebhookEvents5Idempotency ledger for inbound webhooks. No audit columns.
UserHealthProfiles27Principal of the 1:1 from Users.HealthProfileId. The most sensitive table in the schema.
HealthMetricGoals9No audit columns — no soft-delete filter.
HealthSummaries5Precomputed daily rollup. No audit columns.
UserGoals20v1 coaching added `AssignedByCoachId uuid` + `AssignedAt` here with no FK. v2 REMOVES both — coach-assigned goals are rows in `CoachAssignments` (63) with `TargetType = Goal`.
DeviceHealthData19Raw per-sample health data from Apple Health / Health Connect. Highest-volume table in the product. **COMPOSITE PK `(Id, DateFrom)`** — the PK carries a time component so the table can be range-partitioned. Any FK to this table would need both columns; nothing references it, and nothing should. A coach reading this needs an active grant carrying an `activity.*` or `sleep.*` scope, and the query must be clamped to `Date >= now() - HistoryWindowDays`.
HealthMetricAggregations25Rollups over DeviceHealthData. Composite PK `(Id, IntervalStart)`. **Prefer serving coaches from here, not from DeviceHealthData.** An aggregate is what a coach actually needs, and it leaks far less than raw per-sample data — a good default for the `activity.summary` scope.
ActivitySamples10Time series inside one activity — heart-rate trace, pace curve.
BodyParts3
Muscles10Hand-rolls its audit columns and uses `UpdatedAt`, not `ModifiedAt` — the only table in the schema that does.
MuscleAliases3Alternate names used by imported exercise datasets, mapped onto canonical muscles.
MuscleAliasMuscles2N:M. COMPOSITE PK, no surrogate key.
AnatomicalPoints4Skeletal attachment landmarks.
MuscleOrigins3Where a muscle originates. Separate table from insertions rather than one table with a Type discriminator — matches the C#.
MuscleInsertions3Where a muscle inserts.
Equipment15
EquipmentMuscles5
UserEquipment4What kit a user owns — drives "can I do this workout at home". No audit columns.
Exercises20
ExerciseMuscles5
ExerciseEquipments3
ExerciseBodyParts2COMPOSITE PK, no surrogate.
EnergyExpenditures5
ActivityMuscleActivations7Lookup: which muscles a cardio activity loads. Feeds recovery estimation.
Workouts23The marketplace columns (PriceCents..StripePriceId) repeat identically on Programs, Meals, MealPlans and FitnessPlans — see 52.
WorkoutBlockTemplates7
WorkoutExerciseTemplates8
ExerciseSetTemplates8
Programs24
ProgramWeeks8
ProgramDays9
ProgramWorkouts12
ProgramSchedules3Required 1:1 from Programs. No audit columns.
ProgramScheduleDays5
ProgressionStrategies5Required 1:1 from Programs. No audit columns.
ProgramTags7
ProgramRatings9
ProgramReports8No audit columns.
ProgramEnrollments10v1 coaching added `AssignedByCoachId` + `AssignedAt` here. v2 REMOVES both — see CoachAssignments (63).
WorkoutLogs22One completed workout. In v1 every insert here was broadcast to all active coaches over SignalR with no consent — see 62.
ExerciseLogs26
CardioLogs4352 columns. `GpsRoute` is a full location trace — if a coaching scope ever exposes CardioLogs, GPS must be a distinct, Sensitive scope from the aggregate numbers. Sharing a pace curve is not sharing a home address.
CardioSplits25
ExerciseProgresses11Live progress inside a running session, as opposed to the after-the-fact ExerciseLogs.
SetProgress12SINGULAR table name — the only one in the schema.
CardioProgresses18
MuscleRecoverySummaries11Current state, one row per user-muscle. No audit columns.
MuscleRecoveryHistories9Time series behind the summary. No audit columns.
WorkoutSessions18
WorkoutSessionParticipants5No audit columns — no soft-delete filter.
WorkoutSessionInvitations9The existing invite precedent. The coaching invitation (61) is modelled separately — it needs withdrawal and expiry, which this lacks.
WorkoutSessionLeaderboards6
LeaderboardEntries13
RunSessions17
RunSessionParticipants3946 columns and no audit columns — a live-state row that outlives the session it describes.
RunSessionInvitations9
RunSessionLeaderboards6
RunLeaderboardEntries16
Meals30
MealRatings9
Recipes20
MealLogs32In v1 every insert here was pushed to all active coaches over SignalR with no consent — see 62.
MealLogIngredients13Crosses into the `product` schema — the NutriScan side of the product.
MealLogReviews10
MealPlans27
MealPlanCategories11
MealPlanDays8
MealPlanDayItems15Exactly one of MealId / RecipeId / ProductId should be set. Not enforced.
MealPlanFocusTags7
MealPlanEnrollments10v1 coaching added `AssignedByCoachId` + `AssignedAt` here. v2 REMOVES both — see CoachAssignments (63).
MealPlanReports8No audit columns.
InstacartOrderRequests14
NutritionLogs33THE ONLY TABLE IN THE `nutrition` SCHEMA. Everything else nutrition-related is in `public`. The split buys nothing and costs a schema qualifier on every query — either move it to `public` or move MealLogs and Meals in with it.
FitnessPlans20
FitnessPlanDays8
FitnessPlanMealItems13
FitnessPlanWorkoutItems12
FitnessPlanEnrollments10v1 coaching added `AssignedByCoachId` + `AssignedAt` here. v2 REMOVES both — see CoachAssignments (63).
FitnessPlanReports8No audit columns.
PlanVersions9No audit columns.
PlanSubscriptions22A user following a plan. Distinct from `PlanPurchases` (52), which is the money.
ScheduleRecurrenceRules13Reused by coaching check-ins (63) rather than inventing a second recurrence primitive.
ScheduledItems3350 columns and nine nullable FKs, of which at most one is set — the `ItemType` discriminator says which. Backing store for the `schedule.planned_items` data scope.
ScheduledItemLogs6Joins a planned item to what actually got logged. No audit columns.
PlanPurchases15Convention-mapped — there is no EF configuration file for this entity.
PlanImpressions11
PlanSaves10
PlanShares11
PlanClickThroughs11
PlanViewDurations13
CreatorMilestoneTrackers9Fires the Creator* notifications in NotificationSettings. Idempotency comes from the unique index.
Coaches18One row per user who coaches. `UserId` is unique, so coaching is a facet of an account, not a separate account. **Status is a gate, not a label.** Only `Approved` may hold active clients or hold data-access grants. Suspending a coach must cascade to `CoachAccessGrants` (62) — otherwise a suspended coach keeps reading client health data, which is exactly the failure the consent model exists to prevent. Reintroducing this domain also needs a `Coach` entry in the `UserType` enum; ordinal 7 was vacated by the removal migration. See 00-conventions.
CoachStatusEvents7v2 ADD. Append-only history of the approval workflow. v1 kept only the latest decision on the Coach row (`ApprovedAt`, `RejectionReason`), so a coach approved, suspended, then reinstated left no trace of the suspension — unanswerable in a dispute. No audit columns: this table IS the audit.
CoachCertifications13
CoachSpecialtyTags3Drives discovery filtering. Intentionally has NO audit columns — a removed tag is deleted outright.
CoachAvailabilities10One recurring weekly window. Times are the coach local wall clock. v2 ADD — needs a CHECK constraint DBML cannot express: `CONSTRAINT CK_CoachAvailabilities_TimeOrder CHECK ("StartTime" < "EndTime")`. v1 happily stored 17:00-09:00, which `GetAvailableSlots` rendered as an empty day with no error.
CoachInvitations16An offer, in either direction. Many invitations may exist over time for the same pair — that is the point — so there is NO unique index on `(CoachId, ClientId)`. Application rules the schema cannot state: - at most one `Pending` invitation per `(CoachId, ClientId)` at a time (enforce with a partial unique index: `... UNIQUE ("CoachId","ClientId") WHERE "Status" = 'Pending'`); - reject if a `UserBlock` exists in either direction; - reject if the coach is not `Approved`; - reject if the coach is at `MaxActiveClients`. Accepting an invitation does NOT grant data access. It creates the relationship; reading the client metrics needs a separate, explicit consent step (62). Keeping these apart is the whole design.
CoachClients13The working relationship. Exists only after an invitation is accepted. **The unique index changed shape.** v1 had a plain unique on `(CoachId, ClientId)`, which permanently barred re-engagement. v2 needs a PARTIAL unique index that DBML cannot express: CREATE UNIQUE INDEX "IX_CoachClients_CoachId_ClientId_Live" ON "CoachClients" ("CoachId", "ClientId") WHERE "Status" <> 'Ended' AND "IsDeleted" = false; So: one live relationship per pair, unlimited historical ones. **On transition to `Ended`, every live `CoachAccessGrant` for this pair must be revoked in the same transaction.** Nothing in the schema forces it; it belongs in the command handler and in an integration test.
CoachClientStatusEvents7v2 ADD. Append-only. Answers "when was I paused, and by whom". No audit columns — this IS the audit.
DataScopes14Seeded reference data — a `DataScopeSeeder` alongside RoleSeeder. A row here is a promise to the client about what a coach can see, so the vocabulary is data, not an enum: adding a scope must not require a deployment, and deprecating one must not orphan existing grants. Suggested initial seed: activity.summary, activity.steps, activity.heart_rate, body.weight, body.composition, body.measurements (all Sensitive), nutrition.meal_logs, nutrition.macros, training.workout_logs, training.program_adherence, sleep.summary, goals.progress, schedule.planned_items
CoachAccessRequests16The ask. Immutable once answered — a coach who wants more scopes files a new request rather than editing an approved one, so the record of what the client actually consented to cannot be rewritten after the fact. Enforce one pending request per relationship with a partial unique index: CREATE UNIQUE INDEX "IX_CoachAccessRequests_OnePending" ON "CoachAccessRequests" ("CoachClientId") WHERE "Status" = 'Pending' AND "IsDeleted" = false;
CoachAccessRequestScopes6Line items of the ask.
CoachAccessGrants17**The authorization record.** Every coach read of client data resolves through exactly one row here plus its scope rows. Never hard-delete and never soft-delete a grant to revoke it — set `Status = Revoked` with `RevokedAt`. A deleted grant destroys the evidence of what was once permitted, which is the one question that matters after a complaint. At most one Active grant per relationship: CREATE UNIQUE INDEX "IX_CoachAccessGrants_OneActive" ON "CoachAccessGrants" ("CoachClientId") WHERE "Status" = 'Active' AND "IsDeleted" = false; Widening consent = create a new grant, point the old one at it via `SupersededByGrantId`, set the old to `Superseded`. The history stays readable end to end. Cascading obligations (application-enforced, all worth an integration test): - `CoachClients.Status -> Ended` => revoke every Active grant for the pair - `CoachClients.Status -> Paused` => suspend them - `Coaches.Status -> Suspended` => suspend every grant held by the coach - client deletes their account => revoke all grants naming them
CoachAccessGrantScopes7**What the coach may actually see.** The enforcement query is: SELECT gs.* FROM "CoachAccessGrantScopes" gs JOIN "CoachAccessGrants" g ON g."Id" = gs."AccessGrantId" JOIN "DataScopes" s ON s."Id" = gs."DataScopeId" WHERE g."CoachId" = @coachId AND g."ClientId" = @clientId AND g."Status" = 'Active' AND (g."ExpiresAt" IS NULL OR g."ExpiresAt" > now()) AND gs."RevokedAt" IS NULL AND s."Key" = @requiredScopeKey; No row => 403, and a `CoachDataAccessLogs` entry with the matching `DeniedX` outcome. A non-null `HistoryWindowDays` additionally clamps the date filter on the underlying query — silently, not as an error.
CoachDataAccessLogs15**Append-only.** No audit columns, no updates, no deletes — the row IS the record. This is what lets a client be shown "your coach opened your weight history 4 times last week", and what makes an over-broad grant detectable instead of theoretical. v1 had nothing here: client meal and workout logs were pushed to coaches with no trace that it ever happened. Operationally: high write volume. Partition by month on `AccessedAt` and set a retention policy (24 months is a defensible default) before this becomes the largest table in the database.
ClientSharingPreferences10v2 ADD. Client-side standing policy, separate from any one coach. `BlockAllCoachAccess` is checked BEFORE grants, so a client can cut off every coach instantly without hunting through individual revocations.
CoachAssignments16**Replaces the v1 approach.** v1 grafted a `AssignedByCoachId uuid` + `AssignedAt` column pair onto four unrelated tables — `UserGoals`, `ProgramEnrollments`, `MealPlanEnrollments`, `FitnessPlanEnrollments` — with no FK on any of them. Costs of that shape: - "what has this coach assigned me" was a four-way UNION; - a fifth assignable type meant another migration on another table; - the client could not decline, and nothing recorded withdrawal. One table, one polymorphic target, one lifecycle. The trade is a lost FK on `TargetId`, which is already the established pattern here (see `PlanSubscription.PlanId`, `ScheduledItemLog.LogId`, `UserEvent.EntityId`). Writing an assignment requires an active relationship. It does NOT require a data-access grant — assigning work is a write into the client account, not a read of their history. The two authorizations are separate.
CoachCheckIns13One scheduled check-in occurrence. v2 ADD — no equivalent in v1.
CoachCheckInSubmissions12What the client volunteers is distinct from what the coach may query. Submitting a check-in is itself an act of consent for the values inside it, which is why the metrics are snapshotted here rather than joined live out of `DeviceHealthData`.
CoachCheckInMedia5Progress photos. Sensitive — treat as `body.*` scope material even though they arrive by submission.
CoachCheckInFeedback9Threaded discussion on one submission. Kept separate from `Messages` (71) on purpose: this is durable coaching record attached to a period of work, not chat.
CoachAppointments15v1 also carried `VideoCallSessionId uuid` here while `VideoCallSessions` carried `AppointmentId` — a denormalised cycle with no FK on either side that could disagree with itself. v2 keeps only the one real direction: `VideoCallSessions.AppointmentId`. v2 ADD — double-booking prevention, which v1 had nothing for: ALTER TABLE "CoachAppointments" ADD CONSTRAINT "EX_CoachAppointments_NoOverlap" EXCLUDE USING gist ( "CoachId" WITH =, tstzrange("StartsAt", "EndsAt") WITH && ) WHERE ("Status" = 'Scheduled' AND "IsDeleted" = false); Requires the btree_gist extension.
VideoCallSessions11WebRTC session. TURN credentials are issued at runtime and never stored.
CoachOfferings15What a coach sells. Renamed from the draft `CoachSubscriptions`, which confusingly named the PLAN rather than a client subscription TO a plan.
CoachClientSubscriptions17A client live subscription to one offering. Payment state and access state are independent: a lapsed subscription does NOT auto-revoke a `CoachAccessGrant`. Ending the relationship does. Coupling them would mean a failed card silently destroys consent records, which is the wrong failure mode — pause the relationship instead.
CoachClientInvoices17Payouts ride on the Stripe Connect account recorded in Users.StripeConnectedAccountId.
FeedPosts11
FeedPostMedia3
FeedPostReferences6
FeedPostViews4
PostMetrics8Denormalised counters. No audit columns.
PostLikes4No audit columns — a removed like is deleted outright.
PostComments9
PostCommentLikes4
PostCommentMetrics8
PostShares5
PostTags3
PostMentions3
CommentMentions3Was SINGULAR (`CommentMention`) because its EF configuration was never registered in `OnModelCreating`. Fixed 2026-08-17: the configuration is registered and the rename migration brings the table in line with the plural convention.
PostReports8
PostCommentReports9
Conversations7Generic DM thread. A coach-client conversation is just a Direct conversation — coaching adds no messaging tables of its own, but check-in feedback (63) is deliberately NOT stored here: that is durable coaching record attached to a period of work, not chat.
ConversationParticipants9
Messages10
Notifications19The coaching domain needs five new `Type` values. Because `Type` is free text, adding them costs nothing here — but each one also wants a delivery-preference column on `NotificationSettings` (04), which IS a migration: CoachInvitationReceived — a coach invited you / a client requested you CoachAccessRequested — a coach is asking to view your data << the consent prompt CoachAccessDecision — your client granted or denied access CoachAccessRevoked — a client withdrew consent CoachCheckInDue — a check-in is due `NotificationType.Achievement` (ordinal 6) is a permanent gap after the achievements removal; Warning is 7.
NotificationGroups18Rollup: "3 people liked your post". Consent notifications must NEVER be grouped — each one is an individual decision.
AchievementDefinitions16**NOT IN THE LIVE DATABASE — dropped 2026-08-04.** Seeded by `Persistence/Seeders/AchievementSeeder.cs` (211 lines, deleted), invoked from Program.cs. Three Hangfire jobs maintained it: AchievementDailyCheckJob, AchievementJobScheduler, AchievementPercentageJob. Restoring this also needs `NotificationType.Achievement` back — it was ordinal 6 and is now a pinned gap (Warning is 7).
UserAchievements10NOT IN THE LIVE DATABASE. The FK constraint name was truncated by Postgres to `FK_UserAchievements_AchievementDefinitions_AchievementDefiniti~`.
UserAchievementProgress9NOT IN THE LIVE DATABASE. SINGULAR table name (`UserAchievementProgress`).
Companies3A gym chain. One company owns many gyms.
Employees4OPEN QUESTION carried over from the Gym board: how are staff roles split? The board proposed simple RBAC — Client Admin, Equipment Admin, Class Admin, Coach Admin, Global Admin. Note this cannot reuse the global `Roles`/`UserPermissions` tables (02): those are platform-wide, and "Equipment Admin at Gym A" is scoped to one gym. The same actor/subject/scope shape as the coaching consent model (62) applies — an `EmployeeRoles(EmployeeId, GymId, Role)` table is the smaller version of that idea. Unresolved; decide before building.
Gyms12
GymHours5
GymCoaches4A coach working at a gym. THE JOIN BETWEEN THE GYM AND COACHING DOMAINS. Working at a gym confers no access to a client data. That still requires a `CoachAccessGrant` (62) from the individual client — being a member of the same gym is not consent.
GymClients4
ClientPresence4Check-in / check-out events. Checkout can be automatic via the gym geofence.
GymReviews6
GymSocialTags2
EquipmentTypes2MODERATED reference data. The identifying kind of equipment a workout plan needs — "shoulder press machine", not "BowFlex #12341". Gym owners may add equipment freely as long as it is tagged with a type, which is what keeps plan recommendations working.
EquipmentEquipmentTypes2N:M. Equipment may carry several types.
GymEquipment8A physical unit on a gym floor, versus the Equipment catalogue entry it instantiates.
ClassRooms8Carries its own address so a class can be held off-site (a park, a pool).
Classes8Taught by a GymCoach, so a class always resolves to a real Coach (60).
ClassCodes4How an attendee proves they are in the room.
ClassAttendees3
GymSubscriptions9A membership tier a gym offers.
ClassPrices4Lets a gym charge different prices for the same class depending on the member's subscription tier.
GymClientSubscriptions6A member holding a membership tier.
GymClientInvoices8Gym membership invoices. Distinct from `CoachClientInvoices` (64), which the Gym board accidentally wired to THIS table's parents.
Products23
Branding9SINGULAR table name. 1:1 principal of Products.BrandingId.
Nutrition62SINGULAR table name. 47 nutrient columns, all nullable — a label states only what it states.
Barcodes11
Ingredients10
ProductIngredients7
Categories6ORPHANED — no relation to Products is wired up. Either connect it or drop it.
ProductImages13
BoundingBoxes14The training labels. Consumed by ml.DatasetImages (91).
ProductSessions22One user scanning one product. C# class is `ProductSession`, in the file ProductionSession.cs.
NutriScanJobs18
NutriScanTasks12One inference task per bounding-box category. The unique index makes retries idempotent. DbSet is named `ScanTasks`.
ProductVersions13
ProductAnnotations13Human correction queue. Drives annotator pay via Users.PayRate (01).
ProductValidationIssues14
ProductReviews10
Datasets11No DbSet-level FK to Users — the ML schema deliberately keeps only denormalised identity.
DatasetImages10THE BRIDGE from `ml` to `product`. Its labels are the BoundingBoxes on the referenced ProductImage.
DatasetVersions5758 columns, of which ~30 are the augmentation recipe. Frozen once exported — reproducing a training run means replaying exactly this row.
TrainingRuns36
TrainingRunCallbackEvents20Progress stream from the external trainer. No DbSet — mapped by configuration only.
ModelDeployments28Models run ON DEVICE — this is what the mobile clients download.
ScanFeedback22CLOSES THE LOOP: wrong predictions become labelled training data. SINGULAR table name. No DbSet.
ShadowComparisons18Active vs candidate model on the same input. The evidence for a promotion decision. No DbSet.
DriftMetrics15Daily rollup detecting production drift from the training distribution. No DbSet.
MlAuditLog15SINGULAR table name; C# class is `MlAuditLogEntry`. No DbSet. Structurally the same idea as `CoachDataAccessLogs` (62) — who did what to which entity, with the outcome — and a good precedent to follow when implementing it.
UserEvents12Behavioural signal feeding the recommender.
RecScores11
PopularityScores9
RecommendationConfigs11Blend weights, tunable without a deploy.
RecommendationConfigAudits13
EngagementRollupsDaily9
UserRetentionRollups9
RecommendationEvalRollups12
FeedPostEmbeddings10Ignored by the model builder under the InMemory provider — pgvector has no InMemory equivalent.
WorkoutEmbeddings10
ExerciseEmbeddings10
MealEmbeddings10
UserInterestVectors12A learned taste profile per user, one vector per content domain.
StreamlabsConnections20No audit columns. Gated by the StreamlabsEligible policy (SuperAdmin, Admin, ContentCreator, Trainer, Influencer) — the policy that had `Coach` removed from it by commit 73923a4.
StreamlabsEventRules14Viewer donation -> extra reps. No audit columns.
StreamlabsGoals9
StreamlabsTriggerLogs11Append-only. No audit columns.
BugReports7Syncs to Jira. No audit columns. The DbSet is declared as `DbSet<BugReport?>`, which is unusual.
BugReportMedia3Screenshots. No audit columns.

Enums (118)

ReportReason
Spam, Harassment, InappropriateContent, Misinformation, Violence, Other
ReportStatus
Pending, Investigating, Resolved, Dismissed
InvitationStatus
Pending, Accepted, Declined, Expired
UserType
BasicUser, PremiumUser, QualityAssurance, Admin, SuperAdmin, Seller, Influencer, Coach, Trainer, Nutritionist, Pioneer, ContentCreator, Annotator
CourseStatus
Active, Paused, Archived
SessionStatus
Scheduled, Cancelled, Completed
EnrolmentStatus
Enrolled, Waitlisted, Cancelled, LateCancelled, NoShow, Attended
EnrolmentPaymentKind
Membership, DropIn, Comp
SessionCodeType
Qr, Nfc, Text, Keypad
UnitStatus
Active, OutOfOrder, InMaintenance, Retired
UnitMaintenanceFrequency
Daily, Weekly, Monthly, Quarterly, Yearly, Custom
EquipmentReportStatus
Open, Acknowledged, Resolved, Dismissed
EquipmentSettingKind
BenchAngle, CablePosition, RackPosition, SeatHeight, Resistance
GymProductKind
Merchandise, Rental, Service
GymProductStatus
Active, Archived
StockMovementReason
Sale, Return, Adjustment, Receive
OrderStatus
Draft, Paid, Refunded, PartiallyRefunded, Void
OrderChannel
Desk, Terminal, App, Web
OrderPaymentMethod
Card, Terminal, Cash, Link
TerminalReaderStatus
Online, Offline, Retired
SiteStatus
Draft, Published, Unpublished
SiteDomainStatus
Pending, Verifying, Active, Failed
TokenStatus
Active, Revoked, Expired, Used
TokenType
Access, Refresh
TokenEventType
Issued, Refreshed, Revoked, Expired, Used, ValidationFailed
UnitSystem
Metric, Imperial
ProfileDisplayVisibility
Off, FriendsOnly, Everyone, PrivateOnly
NotificationChannel
None, All, Email, PushNotification
ActivityLevel
Sedentary, LightlyActive, ModeratelyActive, VeryActive
GoalType
WeightLoss, WeightGain, MaintainWeight, BuildMuscle, IncreaseEndurance, ImproveFlexibility, ImproveBalance, GeneralFitness
GoalStatus
Active, Completed, Abandoned, Paused
TrackingDirection
Increase, Decrease, Maintain
HealthPlatformType
AppleHealth, GoogleHealthConnect, GoogleFit, SamsungHealth, HuaweiHealth, ManualEntry, Other
TimeInterval
None, Hour, Day, Week, Month, Year
ActivityKind
Cardio, Workout
ActivityMetricType
HeartRate, Distance, Calories, Pace, Cadence, Speed
MuscleGroup
UpperBody, LowerBody, Core, Back, Shoulders, Arms, Legs, Chest
MuscleRole
Primary, Secondary
MuscleUsageFrequency
MinimalUse, ModerateUse, FrequentUse, HighUse
ExerciseType
Compound, Isolation, Cardiovascular, Flexibility, Balance, Stretching
DifficultyLevel
Beginner, Intermediate, Advanced
GripType
Overhand, Underhand, Neutral, Mixed
EquipmentType
Machine, FreeWeight, Cardio, BodyWeight, MultiFunctional, Other
BlockType
Standard, Circuit, SuperSet
SetType
Standard, Timed, Pyramid, DropSet, Mechanical
TargetWeightType
PercentageOfOneRepMax, AbsoluteWeight
WorkoutType
UpperBody, LowerBody, Push, Pull, Legs, FullBody, Cardio, Recovery, Custom
ProgramType
Strength, Hypertrophy, Endurance, PowerBuilding, WeightLoss, GeneralFitness, SportSpecific, Custom
ProgressionType
Linear, Undulating, StepLoading, Deload, AutoRegulated, Custom
SplitType
Kilometer, Mile, Lap, Custom
CardioRunType
Easy, Tempo, Interval, LongRun, RacePace, Fartlek, Hill, Recovery, Progression, TimeTrial
WeatherCondition
Unknown, Clear, Cloudy, Rain, Snow, Fog, Storm
WorkoutStatus
InProgress, Completed, Cancelled, Paused, Scheduled
WorkoutSessionRole
Participant, Host, Moderator, Observer
LeaderboardMetric
TotalReps, TotalWeight, Duration, CompletionTime, AverageRPE
RunSessionStatus
Scheduled, InProgress, Paused, Completed, Cancelled
RunSessionRole
Participant, Host, Pacer, Observer
RunParticipantStatus
Ready, Active, Paused, Completed, Abandoned
RunLeaderboardMetric
Distance, Duration, AveragePace, ElevationGain, SplitsCompleted
MealType
Breakfast, Lunch, Dinner, Snack, Other
IngredientUnit
Each, Package, Tablespoon, Teaspoon, Cup, Ounce, FluidOunce, Pound, Gram, Kilogram, Milliliter, Liter
InstacartOrderSource
MealLog, MealPlan, Meal
PlanType
MealPlan, WorkoutProgram, CardioRoutine, FitnessPlan
PlanSubscriptionStatus
Active, Paused, Cancelled, Completed
ScheduleItemType
Workout, Meal, Product, Cardio
ScheduleItemStatus
Pending, Completed, Skipped, PartiallyCompleted
RecurrenceType
None, Daily, Weekly, Custom
ScheduleLogType
Workout, Meal, Nutrition, Cardio
MarketplacePlanType
MealPlan, WorkoutProgram, FitnessPlan, Workout, Meal, Product
PlanPurchaseStatus
Pending, Succeeded, Refunded, Failed
ShareChannel
Copy, Native, Feed, Community
ClickThroughSource
Feed, Search, Browse, Community, Profile, Recommendation
CreatorMilestoneCategory
Revenue, Impressions, Saves, Followers
CoachStatus
Draft, Pending, Approved, Rejected, Suspended
CoachSpecialty
Strength, Hypertrophy, Powerlifting, Olympic, Endurance, Running, Cycling, Cardio, Mobility, Yoga, Crossfit, Hiit, Calisthenics, Nutrition, WeightLoss, Bodybuilding, PrePostNatal, Senior, Youth, Rehab, Sport
CoachInvitationDirection
ClientRequested, CoachInvited
CoachInvitationStatus
Pending, Accepted, Declined, Withdrawn, Expired
CoachClientStatus
Active, Paused, Ended
DataScopeCategory
Activity, Body, Nutrition, Training, Sleep, Goals, Schedule
DataScopeSensitivity
Standard, Sensitive
AccessRequestStatus
Pending, Approved, PartiallyApproved, Denied, Withdrawn, Expired
AccessGrantStatus
Active, Expired, Revoked, Suspended, Superseded
DataAccessOperation
Read, Export, RealtimePush
DataAccessOutcome
Allowed, DeniedNoGrant, DeniedScopeNotGranted, DeniedGrantExpired, DeniedGrantRevoked, DeniedOutsideHistoryWindow
CoachAssignmentTargetType
Program, MealPlan, FitnessPlan, Goal, Workout
CoachAssignmentStatus
Assigned, Accepted, Declined, Completed, Withdrawn
AppointmentStatus
Scheduled, Completed, Cancelled, NoShow
CallEndReason
PeerEnded, Timeout, NetworkFailure, NoAnswer, Other
CheckInStatus
Scheduled, Submitted, Reviewed, Missed, Cancelled
CoachOfferingInterval
OneTime, Weekly, Monthly, Quarterly
CoachSubscriptionStatus
Trialing, Active, PastDue, Cancelled, Disabled
CoachInvoiceStatus
Draft, Open, Paid, PastDue, PaymentFailed, Void, Refunded
PostVisibility
Public, Friends, Private
PostType
Standard, WorkoutShare, ProgramShare, Progress, Question, Poll, Event, Article, Recipe, Transformation, Review
PostReferenceType
Workout, WorkoutSession, Program, Exercise, Equipment, Muscle, HealthMetric, UserProfile, Event, Article, Recipe, ExternalLink, Product, Poll, Challenge
ConversationType
Direct, Group
MessageContentType
Text, Image, System
AchievementCategory
Workout, Running, Nutrition, GeneralFitness
AchievementTier
Bronze, Silver, Gold, Platinum, Diamond
AchievementMetricType
TotalWeightLifted, TotalWorkoutsCompleted, TotalSetsCompleted, TotalRepsCompleted, TotalPersonalBests, TotalWorkoutMinutes, ConsecutiveWorkoutDays, WorkoutsInSingleWeek, WorkoutsInSingleMonth, TotalDistanceRun, TotalRunSessions, TotalRunMinutes, SingleRunDistance, SingleRunDuration, SingleRunPace, TotalMealsLogged, TotalCaloriesLogged, ConsecutiveDaysProteinGoalMet, ConsecutiveDaysCalorieGoalMet, ConsecutiveDaysMealsLogged, TotalActiveDays, TotalStepsLogged, ConsecutiveActiveDays, DaysOnPlatform
GymSubscriptionType
Daily, Monthly, Yearly
GymSubscriptionStatus
PastDue, Active, Cancelled, Disabled
GymInvoiceStatus
Paid, PastDue, PaymentFailed
MaintenanceFrequency
Daily, Weekly, Monthly, Quarterly, Yearly, Custom
GymEquipmentStatus
Active, Inactive, InMaintenance
PresenceActionType
CheckIn, CheckOut
AccessCodeType
Qr, Nfc, Text, Keypad
ModelType
Yolo, LayoutLm, Cnn, Ocr
TrainingStatus
Queued, Running, Completed, Failed, Cancelled, Cancelling
DeploymentStatus
Deploying, Active, Archived, Deprecated, Failed, PendingEval, Shadow, Cancelling, Cancelled
DatasetSplit
Train, Validation, Test
TrainingReadinessStatus
Unknown, Ready, NeedsReview, Excluded
DatasetVersionExportStatus
Pending, Exporting, Completed, Failed, Cancelling, Cancelled
RecEntityType
Program, Workout, Meal, MealPlan, FitnessPlan, Exercise, FeedPost, Community, Product, Ingredient
UserEventType
View, Click, Start, Complete, Like, Share, Purchase, Dismiss, Rate, Follow, Impression
UserEventSource
Unknown, Web, Ios, Android, Server
StreamlabsEventType
Follow, Subscription, Donation, Bits, Host, Raid, Superchat
StreamlabsActionType
AddReps, AddSets, StartExercise, StartWorkout, OverlayAlertOnly, CustomLabel

Document your own schema

This page is published from DB Planner, a collaborative ER diagram tool. Write the schema in the DBML editor or import it from SQL, then publish docs like these from the project's sharing settings.

More published database schemas