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.
- Tables
- 258
- Columns
- 2991
- Relationships
- 446
- Enums
- 118
Tables (258)
| Table | Columns | Description |
|---|---|---|
| Studios | 13 | Replaces ClassRooms (81). Glossary: Studio; avoid Room, Class Room. |
| Trainers | 11 | An Employee who leads Sessions. Replaces GymCoaches (80), which required an approved Coach. |
| TrainerAbsences | 9 | Sessions inside an absence are flagged for re-staffing; GymTrainerCapability.ManageAbsences gates it. |
| Courses | 21 | The template Sessions are made from. Glossary: Course; avoid Class. |
| CourseSchedules | 12 | The timetable rule. A job materialises Sessions 8 weeks ahead; editing a rule regenerates Sessions from a date forward, keeping those with Enrolments. |
| Sessions | 15 | One occurrence. Replaces Classes (81). Glossary: Session; avoid Class. |
| SessionCodes | 4 | How a Student proves they are in the room. From ClassCodes (81). No audit columns. |
| CoursePrices | 4 | Lets a Course cost different amounts by Membership Offer. From ClassPrices (81). |
| Enrolments | 17 | One Student's place in one Session. Replaces ClassAttendees (81). Glossary: Enrolment; avoid Booking. |
| Brands | 10 | The maker of an Equipment Entry. Glossary: Brand; avoid Manufacturer. |
| EquipmentKinds | 9 | MODERATED 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. |
| EquipmentKindLinks | 2 | N:M. Was EquipmentEquipmentTypes (80). COMPOSITE PK. |
| EquipmentSettingOptions | 5 | The positions an Entry supports (Training: Equipment Setting). No audit columns: replaced wholesale with the Entry. |
| KindSubstitutes | 5 | Curated by FitStack admins. No audit columns. |
| ExerciseKinds | 5 | What 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. |
| GymZones | 9 | |
| GymEquipmentUnits | 17 | ONE 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"). |
| GymEquipmentUnitPhotos | 3 | |
| GymEquipmentMaintenance | 12 | |
| GymEquipmentReports | 13 | Members 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. |
| GymProducts | 16 | Glossary: Gym Product; never "Product" on its own in FitStack Gym copy. |
| GymProductImages | 3 | |
| GymProductVariants | 13 | |
| GymStock | 6 | Merchandise only. Rentals and Services carry no Stock. No soft delete: a row is the count. |
| GymStockMovements | 8 | Append-only ledger; OnHand is the sum. No audit columns. |
| Orders | 23 | One sale. Glossary: Order; a Draft Order is the cart. |
| OrderLines | 7 | No audit columns: lines live and die with the Order. |
| MembershipAddOns | 12 | Glossary: Add-on. A locker rental attached to a Membership. |
| StripeTerminalReaders | 9 | |
| Sites | 15 | |
| SiteVersions | 9 | Version history for rollback. No soft delete: versions are kept. |
| SiteDomains | 13 | A Company's own domain serving its Site (ADR 0012: via the Firebase Hosting API). |
| Users | 37 | Does 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. |
| Roles | 4 | Seeded from the `UserType` enum by RoleSeeder.cs — one role per member. |
| UserRoles | 2 | |
| UserClaims | 4 | |
| RoleClaims | 4 | Claims of type `permission` here are folded into the JWT by JwtTokenGenerator. |
| UserLogins | 4 | External login links — Google and Apple OAuth. |
| AspNetUserTokens | 4 | Still 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. |
| UserTokens | 19 | AggregateRoot, 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. |
| TokenEvents | 9 | Append-only audit of a token lifecycle. Entity base, no audit columns. |
| PasskeyCredentials | 14 | FIDO2 / WebAuthn. AggregateRoot base. |
| Permissions | 4 | Catalogue 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. |
| RolePermissions | 3 | Join: a role confers a permission. No audit columns. |
| UserPermissions | 5 | Direct 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. |
| UserProfiles | 22 | The five inline `*Url` columns duplicate what SocialTags models properly. v2 should pick one; keeping both guarantees they disagree. |
| Followings | 8 | Directed self-referencing follow edge. |
| UserBlocks | 8 | A block should hard-stop a coaching request (see 61). Nothing enforces that today — it is application logic, and it was absent from v1. |
| SocialPlatforms | 3 | DESIGN ONLY — not yet in the live database. |
| SocialTags | 4 | DESIGN ONLY. Generic social link, attachable to a user, gym or coach. |
| UserSocialTags | 2 | DESIGN ONLY. |
| UserSettings | 8 | Principal of Users.SettingsId (the FK sits on Users). No audit columns. |
| NotificationSettings | 42 | 41 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. |
| Media | 10 | Single 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. |
| ProcessedWebhookEvents | 5 | Idempotency ledger for inbound webhooks. No audit columns. |
| UserHealthProfiles | 27 | Principal of the 1:1 from Users.HealthProfileId. The most sensitive table in the schema. |
| HealthMetricGoals | 9 | No audit columns — no soft-delete filter. |
| HealthSummaries | 5 | Precomputed daily rollup. No audit columns. |
| UserGoals | 20 | v1 coaching added `AssignedByCoachId uuid` + `AssignedAt` here with no FK. v2 REMOVES both — coach-assigned goals are rows in `CoachAssignments` (63) with `TargetType = Goal`. |
| DeviceHealthData | 19 | Raw 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`. |
| HealthMetricAggregations | 25 | Rollups 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. |
| ActivitySamples | 10 | Time series inside one activity — heart-rate trace, pace curve. |
| BodyParts | 3 | |
| Muscles | 10 | Hand-rolls its audit columns and uses `UpdatedAt`, not `ModifiedAt` — the only table in the schema that does. |
| MuscleAliases | 3 | Alternate names used by imported exercise datasets, mapped onto canonical muscles. |
| MuscleAliasMuscles | 2 | N:M. COMPOSITE PK, no surrogate key. |
| AnatomicalPoints | 4 | Skeletal attachment landmarks. |
| MuscleOrigins | 3 | Where a muscle originates. Separate table from insertions rather than one table with a Type discriminator — matches the C#. |
| MuscleInsertions | 3 | Where a muscle inserts. |
| Equipment | 15 | |
| EquipmentMuscles | 5 | |
| UserEquipment | 4 | What kit a user owns — drives "can I do this workout at home". No audit columns. |
| Exercises | 20 | |
| ExerciseMuscles | 5 | |
| ExerciseEquipments | 3 | |
| ExerciseBodyParts | 2 | COMPOSITE PK, no surrogate. |
| EnergyExpenditures | 5 | |
| ActivityMuscleActivations | 7 | Lookup: which muscles a cardio activity loads. Feeds recovery estimation. |
| Workouts | 23 | The marketplace columns (PriceCents..StripePriceId) repeat identically on Programs, Meals, MealPlans and FitnessPlans — see 52. |
| WorkoutBlockTemplates | 7 | |
| WorkoutExerciseTemplates | 8 | |
| ExerciseSetTemplates | 8 | |
| Programs | 24 | |
| ProgramWeeks | 8 | |
| ProgramDays | 9 | |
| ProgramWorkouts | 12 | |
| ProgramSchedules | 3 | Required 1:1 from Programs. No audit columns. |
| ProgramScheduleDays | 5 | |
| ProgressionStrategies | 5 | Required 1:1 from Programs. No audit columns. |
| ProgramTags | 7 | |
| ProgramRatings | 9 | |
| ProgramReports | 8 | No audit columns. |
| ProgramEnrollments | 10 | v1 coaching added `AssignedByCoachId` + `AssignedAt` here. v2 REMOVES both — see CoachAssignments (63). |
| WorkoutLogs | 22 | One completed workout. In v1 every insert here was broadcast to all active coaches over SignalR with no consent — see 62. |
| ExerciseLogs | 26 | |
| CardioLogs | 43 | 52 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. |
| CardioSplits | 25 | |
| ExerciseProgresses | 11 | Live progress inside a running session, as opposed to the after-the-fact ExerciseLogs. |
| SetProgress | 12 | SINGULAR table name — the only one in the schema. |
| CardioProgresses | 18 | |
| MuscleRecoverySummaries | 11 | Current state, one row per user-muscle. No audit columns. |
| MuscleRecoveryHistories | 9 | Time series behind the summary. No audit columns. |
| WorkoutSessions | 18 | |
| WorkoutSessionParticipants | 5 | No audit columns — no soft-delete filter. |
| WorkoutSessionInvitations | 9 | The existing invite precedent. The coaching invitation (61) is modelled separately — it needs withdrawal and expiry, which this lacks. |
| WorkoutSessionLeaderboards | 6 | |
| LeaderboardEntries | 13 | |
| RunSessions | 17 | |
| RunSessionParticipants | 39 | 46 columns and no audit columns — a live-state row that outlives the session it describes. |
| RunSessionInvitations | 9 | |
| RunSessionLeaderboards | 6 | |
| RunLeaderboardEntries | 16 | |
| Meals | 30 | |
| MealRatings | 9 | |
| Recipes | 20 | |
| MealLogs | 32 | In v1 every insert here was pushed to all active coaches over SignalR with no consent — see 62. |
| MealLogIngredients | 13 | Crosses into the `product` schema — the NutriScan side of the product. |
| MealLogReviews | 10 | |
| MealPlans | 27 | |
| MealPlanCategories | 11 | |
| MealPlanDays | 8 | |
| MealPlanDayItems | 15 | Exactly one of MealId / RecipeId / ProductId should be set. Not enforced. |
| MealPlanFocusTags | 7 | |
| MealPlanEnrollments | 10 | v1 coaching added `AssignedByCoachId` + `AssignedAt` here. v2 REMOVES both — see CoachAssignments (63). |
| MealPlanReports | 8 | No audit columns. |
| InstacartOrderRequests | 14 | |
| NutritionLogs | 33 | THE 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. |
| FitnessPlans | 20 | |
| FitnessPlanDays | 8 | |
| FitnessPlanMealItems | 13 | |
| FitnessPlanWorkoutItems | 12 | |
| FitnessPlanEnrollments | 10 | v1 coaching added `AssignedByCoachId` + `AssignedAt` here. v2 REMOVES both — see CoachAssignments (63). |
| FitnessPlanReports | 8 | No audit columns. |
| PlanVersions | 9 | No audit columns. |
| PlanSubscriptions | 22 | A user following a plan. Distinct from `PlanPurchases` (52), which is the money. |
| ScheduleRecurrenceRules | 13 | Reused by coaching check-ins (63) rather than inventing a second recurrence primitive. |
| ScheduledItems | 33 | 50 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. |
| ScheduledItemLogs | 6 | Joins a planned item to what actually got logged. No audit columns. |
| PlanPurchases | 15 | Convention-mapped — there is no EF configuration file for this entity. |
| PlanImpressions | 11 | |
| PlanSaves | 10 | |
| PlanShares | 11 | |
| PlanClickThroughs | 11 | |
| PlanViewDurations | 13 | |
| CreatorMilestoneTrackers | 9 | Fires the Creator* notifications in NotificationSettings. Idempotency comes from the unique index. |
| Coaches | 18 | One 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. |
| CoachStatusEvents | 7 | v2 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. |
| CoachCertifications | 13 | |
| CoachSpecialtyTags | 3 | Drives discovery filtering. Intentionally has NO audit columns — a removed tag is deleted outright. |
| CoachAvailabilities | 10 | One 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. |
| CoachInvitations | 16 | An 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. |
| CoachClients | 13 | The 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. |
| CoachClientStatusEvents | 7 | v2 ADD. Append-only. Answers "when was I paused, and by whom". No audit columns — this IS the audit. |
| DataScopes | 14 | Seeded 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 |
| CoachAccessRequests | 16 | The 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; |
| CoachAccessRequestScopes | 6 | Line items of the ask. |
| CoachAccessGrants | 17 | **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 |
| CoachAccessGrantScopes | 7 | **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. |
| CoachDataAccessLogs | 15 | **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. |
| ClientSharingPreferences | 10 | v2 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. |
| CoachAssignments | 16 | **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. |
| CoachCheckIns | 13 | One scheduled check-in occurrence. v2 ADD — no equivalent in v1. |
| CoachCheckInSubmissions | 12 | What 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`. |
| CoachCheckInMedia | 5 | Progress photos. Sensitive — treat as `body.*` scope material even though they arrive by submission. |
| CoachCheckInFeedback | 9 | Threaded discussion on one submission. Kept separate from `Messages` (71) on purpose: this is durable coaching record attached to a period of work, not chat. |
| CoachAppointments | 15 | v1 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. |
| VideoCallSessions | 11 | WebRTC session. TURN credentials are issued at runtime and never stored. |
| CoachOfferings | 15 | What a coach sells. Renamed from the draft `CoachSubscriptions`, which confusingly named the PLAN rather than a client subscription TO a plan. |
| CoachClientSubscriptions | 17 | A 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. |
| CoachClientInvoices | 17 | Payouts ride on the Stripe Connect account recorded in Users.StripeConnectedAccountId. |
| FeedPosts | 11 | |
| FeedPostMedia | 3 | |
| FeedPostReferences | 6 | |
| FeedPostViews | 4 | |
| PostMetrics | 8 | Denormalised counters. No audit columns. |
| PostLikes | 4 | No audit columns — a removed like is deleted outright. |
| PostComments | 9 | |
| PostCommentLikes | 4 | |
| PostCommentMetrics | 8 | |
| PostShares | 5 | |
| PostTags | 3 | |
| PostMentions | 3 | |
| CommentMentions | 3 | Was 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. |
| PostReports | 8 | |
| PostCommentReports | 9 | |
| Conversations | 7 | Generic 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. |
| ConversationParticipants | 9 | |
| Messages | 10 | |
| Notifications | 19 | The 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. |
| NotificationGroups | 18 | Rollup: "3 people liked your post". Consent notifications must NEVER be grouped — each one is an individual decision. |
| AchievementDefinitions | 16 | **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). |
| UserAchievements | 10 | NOT IN THE LIVE DATABASE. The FK constraint name was truncated by Postgres to `FK_UserAchievements_AchievementDefinitions_AchievementDefiniti~`. |
| UserAchievementProgress | 9 | NOT IN THE LIVE DATABASE. SINGULAR table name (`UserAchievementProgress`). |
| Companies | 3 | A gym chain. One company owns many gyms. |
| Employees | 4 | OPEN 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. |
| Gyms | 12 | |
| GymHours | 5 | |
| GymCoaches | 4 | A 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. |
| GymClients | 4 | |
| ClientPresence | 4 | Check-in / check-out events. Checkout can be automatic via the gym geofence. |
| GymReviews | 6 | |
| GymSocialTags | 2 | |
| EquipmentTypes | 2 | MODERATED 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. |
| EquipmentEquipmentTypes | 2 | N:M. Equipment may carry several types. |
| GymEquipment | 8 | A physical unit on a gym floor, versus the Equipment catalogue entry it instantiates. |
| ClassRooms | 8 | Carries its own address so a class can be held off-site (a park, a pool). |
| Classes | 8 | Taught by a GymCoach, so a class always resolves to a real Coach (60). |
| ClassCodes | 4 | How an attendee proves they are in the room. |
| ClassAttendees | 3 | |
| GymSubscriptions | 9 | A membership tier a gym offers. |
| ClassPrices | 4 | Lets a gym charge different prices for the same class depending on the member's subscription tier. |
| GymClientSubscriptions | 6 | A member holding a membership tier. |
| GymClientInvoices | 8 | Gym membership invoices. Distinct from `CoachClientInvoices` (64), which the Gym board accidentally wired to THIS table's parents. |
| Products | 23 | |
| Branding | 9 | SINGULAR table name. 1:1 principal of Products.BrandingId. |
| Nutrition | 62 | SINGULAR table name. 47 nutrient columns, all nullable — a label states only what it states. |
| Barcodes | 11 | |
| Ingredients | 10 | |
| ProductIngredients | 7 | |
| Categories | 6 | ORPHANED — no relation to Products is wired up. Either connect it or drop it. |
| ProductImages | 13 | |
| BoundingBoxes | 14 | The training labels. Consumed by ml.DatasetImages (91). |
| ProductSessions | 22 | One user scanning one product. C# class is `ProductSession`, in the file ProductionSession.cs. |
| NutriScanJobs | 18 | |
| NutriScanTasks | 12 | One inference task per bounding-box category. The unique index makes retries idempotent. DbSet is named `ScanTasks`. |
| ProductVersions | 13 | |
| ProductAnnotations | 13 | Human correction queue. Drives annotator pay via Users.PayRate (01). |
| ProductValidationIssues | 14 | |
| ProductReviews | 10 | |
| Datasets | 11 | No DbSet-level FK to Users — the ML schema deliberately keeps only denormalised identity. |
| DatasetImages | 10 | THE BRIDGE from `ml` to `product`. Its labels are the BoundingBoxes on the referenced ProductImage. |
| DatasetVersions | 57 | 58 columns, of which ~30 are the augmentation recipe. Frozen once exported — reproducing a training run means replaying exactly this row. |
| TrainingRuns | 36 | |
| TrainingRunCallbackEvents | 20 | Progress stream from the external trainer. No DbSet — mapped by configuration only. |
| ModelDeployments | 28 | Models run ON DEVICE — this is what the mobile clients download. |
| ScanFeedback | 22 | CLOSES THE LOOP: wrong predictions become labelled training data. SINGULAR table name. No DbSet. |
| ShadowComparisons | 18 | Active vs candidate model on the same input. The evidence for a promotion decision. No DbSet. |
| DriftMetrics | 15 | Daily rollup detecting production drift from the training distribution. No DbSet. |
| MlAuditLog | 15 | SINGULAR 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. |
| UserEvents | 12 | Behavioural signal feeding the recommender. |
| RecScores | 11 | |
| PopularityScores | 9 | |
| RecommendationConfigs | 11 | Blend weights, tunable without a deploy. |
| RecommendationConfigAudits | 13 | |
| EngagementRollupsDaily | 9 | |
| UserRetentionRollups | 9 | |
| RecommendationEvalRollups | 12 | |
| FeedPostEmbeddings | 10 | Ignored by the model builder under the InMemory provider — pgvector has no InMemory equivalent. |
| WorkoutEmbeddings | 10 | |
| ExerciseEmbeddings | 10 | |
| MealEmbeddings | 10 | |
| UserInterestVectors | 12 | A learned taste profile per user, one vector per content domain. |
| StreamlabsConnections | 20 | No audit columns. Gated by the StreamlabsEligible policy (SuperAdmin, Admin, ContentCreator, Trainer, Influencer) — the policy that had `Coach` removed from it by commit 73923a4. |
| StreamlabsEventRules | 14 | Viewer donation -> extra reps. No audit columns. |
| StreamlabsGoals | 9 | |
| StreamlabsTriggerLogs | 11 | Append-only. No audit columns. |
| BugReports | 7 | Syncs to Jira. No audit columns. The DbSet is declared as `DbSet<BugReport?>`, which is unusual. |
| BugReportMedia | 3 | Screenshots. 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.