Product Analytics ER diagram and database schema

The Product Analytics database schema is a DB Planner template with 27 tables, 214 columns and 48 relationships, free to use. Core tables include api_keys, cohort_memberships, cohorts, daily_event_rollups. It can be opened as an interactive ER diagram or exported as PostgreSQL, MySQL, or SQL Server DDL.

ER diagram of the Product Analytics database schema, showing 27 tables and their relationships
FIG. 1: entity relationship diagram, 27 tables
Tables
27
Columns
214
Relationships
48
Category
Analytics
Exports
DBML, SQL, Prisma, C#
Price
Free

What this schema models

A complete product analytics database design, the kind of data model behind a tool similar to Mixpanel: 27 tables, 13 enums and 48 relationships covering workspaces, projects and API keys, anonymous devices and identified persons with an identity alias graph, person property history, sessions, a raw event log with an event and property registry, daily rollups, feature flags with targeting rules, experiments with variants and exposures, funnels, versioned cohorts, saved reports and dashboards. THE FOUR DESIGN RULES 1. Raw events are immutable. events is append-only, partitioned by month on occurred_at, with a client-generated id so a retried batch is deduplicated. Sessions, rollups, cohorts and report results are all derived, and can be rebuilt from it. 2. Identity resolves through aliases, never by rewriting events. Every event keeps the distinct_id it was sent with; identity_aliases maps each distinct id to a person. When an anonymous visitor logs in or two persons merge, only alias rows change, and the whole history follows. 3. What happened is separate from what it means. Events carry raw names and JSONB properties; event_definitions and property_definitions add display names, descriptions, types, PII flags and a verified or hidden status. Definitions are created automatically on first sight, so tracking is never blocked by governance, and renaming an event never touches a row of data. 4. Derived data is cached or versioned, never half-built. A cohort recompute writes membership version n+1 in full and then flips current_version in one update; persons.properties is a cache folded from person_property_changes; a report result is only ever a cache of its stored query. DETAILS WORTH STEALING - Daily rollups keep a HyperLogLog sketch beside the count, because distinct users cannot be added across days but sketches can be merged. - Feature flags bucket users by hash(key + salt + distinct id), so assignment is deterministic, needs no stored rows, and SDKs can evaluate flags locally. - Experiments log exposure when the variant is first seen, not when the user is bucketed, so people who never reached the changed screen do not dilute the result; the primary metric is fixed before launch. - First-touch attribution (referrer and UTM tags) lives on the device, because it happened before identity did. - Ingestion keys are public and write-only, secret keys read data, and both are stored only as hashes. - Person property history answers "what plan were they on when they did that?" WHAT YOU GET Clean DBML that imports directly into DB Planner, and a laid-out board with zones color-coded and framed: workspaces and access, identity and sessions, events and registry, flags and experiments, cohorts and funnels, and dashboards and reports. Every table carries a note. Written for Postgres: event and person properties, flag rules, cohort and funnel definitions and saved queries are jsonb (JSON in MySQL, NVARCHAR(MAX) in SQL Server), and the raw events table is meant to be partitioned by time. Useful for developers building in-house analytics or an analytics product, and for students who need a realistic product analytics ER diagram for a DBMS project. This is a schema design reference; at real event volumes the events table usually moves to a columnar store while the shape stays the same.

Tables (27)

Every table and its columns

workspaces

The billing and access boundary: one company using the product.

Columns of the workspaces table
ColumnTypeConstraintsReferencesDescription
iduuidPK
namevarchar(200)not null
slugvarchar(60)unique, not null
planworkspace_plannot null
monthly_event_quotabigintBilling limit. Ingestion keeps accepting past it and flags the overage; dropping data is never the answer
created_attimestamptznot null, default `now()`

users

People who log in to the analytics product. Not to be confused with persons, the end users being measured.

Columns of the users table
ColumnTypeConstraintsReferences
iduuidPK
emailvarchar(254)unique, not null
namevarchar(200)not null
created_attimestamptznot null, default `now()`

workspace_members

Who can see and change what in a workspace.

Columns of the workspace_members table
ColumnTypeConstraintsReferences
workspace_iduuidFK, not nullworkspaces.id
user_iduuidFK, not nullusers.id
rolemember_rolenot null
joined_attimestamptznot null, default `now()`

projects

One tracked product and environment, e.g. web app production. Everything below is scoped to a project, and staging is a separate project so test traffic never pollutes real numbers.

Columns of the projects table
ColumnTypeConstraintsReferencesDescription
iduuidPK
workspace_iduuidFK, not nullworkspaces.id
namevarchar(200)not null
timezonevarchar(64)not nullWhere a "day" starts for rollups and charts. Changing it means recomputing rollups
session_timeout_minutessmallintnot null, default 30
created_attimestamptznot null, default `now()`

Indexes: (workspace_id, name) unique

api_keys

Ingestion keys are public (they ship inside apps and web pages) and can only write events; secret keys read data and stay on servers. Two kinds, never one key that does both.

Columns of the api_keys table
ColumnTypeConstraintsReferencesDescription
iduuidPK
project_iduuidFK, not nullprojects.id
kindapi_key_kindnot null
key_prefixvarchar(12)not nullFirst characters, shown in the UI so a key can be recognised
key_hashchar(64)unique, not nullSHA-256 of the key. A secret key is shown once at creation and never stored in clear
labelvarchar(100)
created_byuuidFKusers.id
created_attimestamptznot null, default `now()`
last_used_attimestamptz
revoked_attimestamptz

devices

Browsers and app installs, known before anyone logs in. First-touch attribution lives here because it happened before identity did.

Columns of the devices table
ColumnTypeConstraintsReferencesDescription
iduuidPK
project_iduuidFK, not nullprojects.id
anonymous_idvarchar(100)not nullGenerated by the SDK on first launch and kept in local storage or the keychain
person_iduuidFKpersons.idCACHE of the alias resolution, set once the device is identified
platformvarchar(30)e.g. web, ios, android
first_seen_attimestamptznot null
last_seen_attimestamptznot null
initial_referrervarchar(500)First-touch attribution: captured once, never overwritten
initial_utm_sourcevarchar(100)
initial_utm_mediumvarchar(100)
initial_utm_campaignvarchar(200)

Indexes: (project_id, anonymous_id) unique

persons

The end users being measured, identified or not. One person can have many devices and many distinct ids.

Columns of the persons table
ColumnTypeConstraintsReferencesDescription
iduuidPK
project_iduuidFK, not nullprojects.id
external_idvarchar(200)Your own user id, sent with identify(). Null for persons only ever seen anonymously
propertiesjsonbnot null, default '{}'CACHE: the current value of every person property, folded from person_property_changes
merged_into_iduuidFKpersons.idSet when this person was merged into another; lookups follow it
first_seen_attimestamptznot null
last_seen_attimestamptznot null
deleted_attimestamptzErasure request. Their events are deleted by a background job; the row stays as a tombstone so the id is never reused

Indexes: (project_id, external_id) unique

identity_aliases

The identity graph. Events keep the distinct_id they were sent with and are never rewritten; queries resolve distinct_id to person here. When an anonymous visitor logs in, or two persons merge, only these rows change, and the whole history moves with them.

Columns of the identity_aliases table
ColumnTypeConstraintsReferencesDescription
project_iduuidFK, not nullprojects.id
distinct_idvarchar(200)not nullAny id an event has arrived with: an anonymous id or an external id
person_iduuidFK, not nullpersons.id
sourcealias_sourcenot null
created_attimestamptznot null, default `now()`
updated_attimestamptznot nullChanges when a merge repoints the alias at the surviving person

Indexes: (person_id)

person_property_changes

Every change to a person property, in order. persons.properties holds the latest values; this table answers "what plan were they on when they did that?"

Columns of the person_property_changes table
ColumnTypeConstraintsReferencesDescription
person_iduuidFK, not nullpersons.id
property_keyvarchar(200)not null
set_attimestamptznot null
operationproperty_operationnot nullset overwrites; set_once applies only if no value exists yet; unset removes it
valuejsonbNull for unset
source_event_iduuidThe event that carried the change, if any. Not a foreign key: events is partitioned

sessions

Derived by the sessionizer: a run of events from one device with no gap longer than the project session timeout. Rebuildable from events, so the rules can change.

Columns of the sessions table
ColumnTypeConstraintsReferencesDescription
iduuidPK
project_iduuidFK, not nullprojects.id
device_iduuidFK, not nulldevices.id
started_attimestamptznot null
ended_attimestamptznot null
duration_sintegernot null
event_countintegernot null
pageview_countintegernot null, default 0
entry_urlvarchar(2000)
exit_urlvarchar(2000)
referrervarchar(500)
utm_sourcevarchar(100)
utm_mediumvarchar(100)
utm_campaignvarchar(200)
countrychar(2)
is_bouncebooleannot nullA single pageview and nothing else

Indexes: (project_id, started_at), (device_id, started_at)

events

Raw events: append-only, never updated. PARTITION BY RANGE (occurred_at), monthly, with a BRIN index on occurred_at in each partition. Retention is DROP PARTITION. At real volume this table moves to a columnar store; the shape stays the same.

Columns of the events table
ColumnTypeConstraintsReferencesDescription
iduuidnot nullGenerated by the SDK, so a retried batch is recognised as a duplicate
project_iduuidFK, not nullprojects.id
event_namevarchar(200)not nullExactly as sent. Matched to event_definitions by name, never by foreign key
distinct_idvarchar(200)not nullAs sent. Resolved to a person through identity_aliases at query time
session_iduuidStamped by the sessionizer after ingest
occurred_attimestamptznot nullClient time corrected for clock skew (received_at minus sent_at). The partition key
sent_attimestamptzClient clock when the batch left the device
received_attimestamptznot null, default `now()`
propertiesjsonbnot null, default '{}'Everything else the SDK or caller attached. Promote hot keys to columns rather than indexing the whole document
urlvarchar(2000)Promoted from properties: filtered on constantly
platformvarchar(30)Promoted from properties
app_versionvarchar(30)Promoted from properties

Indexes: (project_id, event_name, occurred_at), (project_id, distinct_id, occurred_at)

event_definitions

The registry: what an event MEANS, kept apart from what happened. A row is created automatically the first time a name is seen, so tracking is never blocked by governance; verifying, describing and hiding come after.

Columns of the event_definitions table
ColumnTypeConstraintsReferencesDescription
iduuidPK
project_iduuidFK, not nullprojects.id
namevarchar(200)not nullThe raw event name as it appears in events
display_namevarchar(200)What the UI shows. Renaming here renames it everywhere without touching a single event
descriptiontext
categoryvarchar(100)
statusdefinition_statusnot null, default 'discovered'
owner_user_iduuidFKusers.id
first_seen_attimestamptznot null
last_seen_attimestamptznot null
volume_30dbigintCACHE from daily_event_rollups

Indexes: (project_id, name) unique

property_definitions

Registry of event, person and session properties, with types. Without it every filter has to guess whether "1" is a number.

Columns of the property_definitions table
ColumnTypeConstraintsReferencesDescription
iduuidPK
project_iduuidFK, not nullprojects.id
scopeproperty_scopenot null
namevarchar(200)not null
data_typeproperty_data_typenot nullInferred from the first values seen, then confirmed by a person. Decides which filters the UI offers
descriptiontext
is_piibooleannot null, default falseMasked in the UI and left out of exports
is_hiddenbooleannot null, default false
first_seen_attimestamptznot null

Indexes: (project_id, scope, name) unique

event_property_usage

Which properties actually arrive on which events, so the filter picker for an event lists only its own properties.

Columns of the event_property_usage table
ColumnTypeConstraintsReferences
event_definition_iduuidFK, not nullevent_definitions.id
property_definition_iduuidFK, not nullproperty_definitions.id
first_seen_attimestamptznot null
last_seen_attimestamptznot null

daily_event_rollups

Pre-aggregated daily counts that keep event lists, volume charts and simple trends off the raw table. Recomputed for any day that receives late events.

Columns of the daily_event_rollups table
ColumnTypeConstraintsReferencesDescription
project_iduuidFK, not nullprojects.id
event_namevarchar(200)not null
daydatenot nullIn the project timezone
event_countbigintnot null
unique_persons_estimateintegernot null
unique_persons_sketchbyteanot nullHyperLogLog sketch. Distinct counts cannot be added across days but sketches can be merged: weekly uniques merge seven of them
computed_attimestamptznot null

feature_flags

Feature flags. Evaluation is deterministic, which is what lets SDKs evaluate them locally instead of making a network call per check.

Columns of the feature_flags table
ColumnTypeConstraintsReferencesDescription
iduuidPK
project_iduuidFK, not nullprojects.id
keyvarchar(100)not nullReferenced in code, e.g. new-checkout. Never reused after archiving
namevarchar(200)not null
descriptiontext
is_enabledbooleannot null, default falseKill switch: off serves the default to everyone, whatever the rules say
hash_saltvarchar(40)not nullBucket = hash(key + salt + distinct_id) mod 100, so a user lands in the same bucket on every call with no assignment row stored
created_byuuidFKusers.id
created_attimestamptznot null, default `now()`
archived_attimestamptz

Indexes: (project_id, key) unique

flag_rules

Targeting: who gets the flag, as ordered conditions plus a percentage.

Columns of the flag_rules table
ColumnTypeConstraintsReferencesDescription
iduuidPK
feature_flag_iduuidFK, not nullfeature_flags.id
positionsmallintnot nullEvaluated in order; the first matching rule decides
cohort_iduuidFKcohorts.idMatch people in this cohort
conditionsjsonbProperty filters, e.g. [{"key": "plan", "op": "eq", "value": "pro"}]
rollout_pctnumeric(5,2)not null, default 100Share of matching people who get the flag
variant_keyvarchar(50)Multivariate flags: serve this variant to everyone the rule matches

Indexes: (feature_flag_id, position) unique

experiments

A/B tests: a hypothesis, a primary metric chosen in advance, and a flag that splits traffic.

Columns of the experiments table
ColumnTypeConstraintsReferencesDescription
iduuidPK
project_iduuidFK, not nullprojects.id
feature_flag_iduuidFK, unique, not nullfeature_flags.idAn experiment runs through its own flag; the variants are its buckets
namevarchar(200)not null
hypothesistext
primary_funnel_iduuidFKfunnels.idThe success metric, fixed before launch rather than picked after the results are in
statusexperiment_statusnot null, default 'draft'
minimum_sample_sizeintegerFrom the power calculation. Calling a winner before it is reached is how false positives ship
started_attimestamptz
ended_attimestamptz
winning_variant_iduuidFKexperiment_variants.id
created_byuuidFKusers.id

experiment_variants

The arms of an experiment.

Columns of the experiment_variants table
ColumnTypeConstraintsReferencesDescription
iduuidPK
experiment_iduuidFK, not nullexperiments.id
keyvarchar(50)not nulle.g. control, test-a. Matches the flag variant key
weight_pctnumeric(5,2)not nullThe weights of one experiment sum to 100
is_controlbooleannot null, default false

Indexes: (experiment_id, key) unique

experiment_exposures

One row per person per experiment, written the first time the flag is evaluated where its effect is visible. Analysis counts only exposed people, so users who never reached the changed screen do not dilute the result.

Columns of the experiment_exposures table
ColumnTypeConstraintsReferencesDescription
experiment_iduuidFK, not nullexperiments.id
distinct_idvarchar(200)not null
variant_iduuidFK, not nullexperiment_variants.id
first_exposed_attimestamptznot nullWhen the user first saw a variant, not when they were bucketed
exposure_countintegernot null, default 1

cohorts

Saved groups of persons: dynamic (a definition, recomputed on a schedule) or static (an uploaded list).

Columns of the cohorts table
ColumnTypeConstraintsReferencesDescription
iduuidPK
project_iduuidFK, not nullprojects.id
namevarchar(200)not null
kindcohort_kindnot null
definitionjsonbDynamic cohorts: the filter tree, e.g. did signed_up in the last 30 days AND plan = pro
current_versionintegernot null, default 0The membership version readers use
member_countintegerCACHE for the current version
last_computed_attimestamptz
created_byuuidFKusers.id
created_attimestamptznot null, default `now()`

cohort_memberships

Computed membership, by version. A recompute writes version n+1 in full, then flips cohorts.current_version in one update, so nobody ever reads a half-built cohort. Old versions are deleted afterwards.

Columns of the cohort_memberships table
ColumnTypeConstraintsReferences
cohort_iduuidFK, not nullcohorts.id
versionintegernot null
person_iduuidFK, not nullpersons.id

Indexes: (person_id)

funnels

Saved funnel definitions. Results are computed from events on demand and never stored here.

Columns of the funnels table
ColumnTypeConstraintsReferencesDescription
iduuidPK
project_iduuidFK, not nullprojects.id
namevarchar(200)not null
step_orderfunnel_ordernot null, default 'ordered'
conversion_window_secondsintegernot null, default 1209600From the first step to the last; 1209600 is 14 days
countingfunnel_countingnot null, default 'unique_persons'
exclusion_eventvarchar(200)An event that disqualifies a conversion if it happens between steps
created_byuuidFKusers.id
created_attimestamptznot null, default `now()`

funnel_steps

The ordered steps of a funnel.

Columns of the funnel_steps table
ColumnTypeConstraintsReferencesDescription
funnel_iduuidFK, not nullfunnels.id
positionsmallintnot null
event_namevarchar(200)not nullThe raw name, so changing a display name never breaks a funnel
filtersjsonbProperty filters on this step only
labelvarchar(200)

saved_reports

Saved insights: trends, funnels, retention, paths. A report is a stored query; its result is only ever a cache.

Columns of the saved_reports table
ColumnTypeConstraintsReferencesDescription
iduuidPK
project_iduuidFK, not nullprojects.id
namevarchar(200)not null
kindreport_kindnot null
funnel_iduuidFKfunnels.idFor funnel reports
cohort_iduuidFKcohorts.idOptional filter or breakdown by cohort
queryjsonbnot nullThe full query: events, filters, breakdowns and a relative date range (e.g. last 30 days) so it stays current
cached_resultjsonbCACHE of the last run. Dashboards render it and refresh in the background
cached_attimestamptz
created_byuuidFKusers.id
created_attimestamptznot null, default `now()`
updated_attimestamptznot null

dashboards

Collections of reports laid out on a grid.

Columns of the dashboards table
ColumnTypeConstraintsReferencesDescription
iduuidPK
project_iduuidFK, not nullprojects.id
namevarchar(200)not null
descriptiontext
is_sharedbooleannot null, default trueVisible to the whole workspace, not just its creator
share_tokenvarchar(64)uniqueSet when shared by public link; rotate it to revoke the link
created_byuuidFKusers.id
created_attimestamptznot null, default `now()`

dashboard_tiles

Where a report sits on a dashboard. One report can appear on many dashboards and is still edited in one place.

Columns of the dashboard_tiles table
ColumnTypeConstraintsReferencesDescription
iduuidPK
dashboard_iduuidFK, not nulldashboards.id
saved_report_iduuidFKsaved_reports.idNull for a text tile
text_bodytextMarkdown, for text tiles
grid_xsmallintnot null
grid_ysmallintnot null
grid_wsmallintnot null
grid_hsmallintnot null

Enums (13)

workspace_plan
free, growth, enterprise
member_role
viewer, analyst, admin, owner
api_key_kind
public_ingest, secret
alias_source
first_seen, identify, alias_call, merge
property_operation
set, set_once, unset
definition_status
discovered, verified, hidden, deprecated
property_scope
event, person, session
property_data_type
string, number, boolean, datetime, list
experiment_status
draft, running, stopped, concluded
cohort_kind
dynamic, static
funnel_order
strict, ordered, any_order
funnel_counting
unique_persons, unique_sessions, totals
report_kind
trend, funnel, retention, paths, stickiness, lifecycle

Relationships (48)

  • api_keys.created_by references users.id many to one
  • api_keys.project_id references projects.id many to one
  • cohort_memberships.cohort_id references cohorts.id many to one
  • cohort_memberships.person_id references persons.id many to one
  • cohorts.created_by references users.id many to one
  • cohorts.project_id references projects.id many to one
  • daily_event_rollups.project_id references projects.id many to one
  • dashboard_tiles.dashboard_id references dashboards.id many to one
  • dashboard_tiles.saved_report_id references saved_reports.id many to one
  • dashboards.created_by references users.id many to one
  • dashboards.project_id references projects.id many to one
  • devices.person_id references persons.id many to one
  • devices.project_id references projects.id many to one
  • event_definitions.owner_user_id references users.id many to one
  • event_definitions.project_id references projects.id many to one
  • event_property_usage.event_definition_id references event_definitions.id many to one
  • event_property_usage.property_definition_id references property_definitions.id many to one
  • events.project_id references projects.id many to one
  • experiment_exposures.experiment_id references experiments.id many to one
  • experiment_exposures.variant_id references experiment_variants.id many to one
  • experiment_variants.experiment_id references experiments.id many to one
  • experiments.created_by references users.id many to one
  • experiments.primary_funnel_id references funnels.id many to one
  • experiments.project_id references projects.id many to one
  • experiments.winning_variant_id references experiment_variants.id many to one
  • feature_flags.created_by references users.id many to one
  • feature_flags.id references experiments.feature_flag_id one to one
  • feature_flags.project_id references projects.id many to one
  • flag_rules.cohort_id references cohorts.id many to one
  • flag_rules.feature_flag_id references feature_flags.id many to one
  • funnel_steps.funnel_id references funnels.id many to one
  • funnels.created_by references users.id many to one
  • funnels.project_id references projects.id many to one
  • identity_aliases.person_id references persons.id many to one
  • identity_aliases.project_id references projects.id many to one
  • person_property_changes.person_id references persons.id many to one
  • persons.merged_into_id references persons.id many to one
  • persons.project_id references projects.id many to one
  • projects.workspace_id references workspaces.id many to one
  • property_definitions.project_id references projects.id many to one
  • saved_reports.cohort_id references cohorts.id many to one
  • saved_reports.created_by references users.id many to one
  • saved_reports.funnel_id references funnels.id many to one
  • saved_reports.project_id references projects.id many to one
  • sessions.device_id references devices.id many to one
  • sessions.project_id references projects.id many to one
  • workspace_members.user_id references users.id many to one
  • workspace_members.workspace_id references workspaces.id many to one

Product Analytics database schema in DBML

The schema as it is written: DBML, the text format DB Planner draws its diagrams from. Copy it into any DBML tool, or open it in the diagram above.

product-analytics.dbml dbml
// Product Analytics
// Zones (header colors): workspaces and access (gray), identity and sessions (teal),
// events and registry (blue), flags and experiments (amber),
// cohorts and funnels (purple), dashboards and reports (green).

// ---------------------------------------------------------------------------
// WORKSPACES AND ACCESS
// ---------------------------------------------------------------------------

Table workspaces [headercolor: #90a4ae] {
  id uuid [pk]
  name varchar(200) [not null]
  slug varchar(60) [not null, unique]
  plan workspace_plan [not null]
  monthly_event_quota bigint [note: 'Billing limit. Ingestion keeps accepting past it and flags the overage; dropping data is never the answer']
  created_at timestamptz [not null, default: `now()`]
  Note: 'The billing and access boundary: one company using the product.'
}

Table users [headercolor: #90a4ae] {
  id uuid [pk]
  email varchar(254) [not null, unique]
  name varchar(200) [not null]
  created_at timestamptz [not null, default: `now()`]
  Note: 'People who log in to the analytics product. Not to be confused with persons, the end users being measured.'
}

Table workspace_members [headercolor: #90a4ae] {
  workspace_id uuid [not null, ref: > workspaces.id]
  user_id uuid [not null, ref: > users.id]
  role member_role [not null]
  joined_at timestamptz [not null, default: `now()`]

  indexes {
    (workspace_id, user_id) [pk]
  }

  Note: 'Who can see and change what in a workspace.'
}

Table projects [headercolor: #90a4ae] {
  id uuid [pk]
  workspace_id uuid [not null, ref: > workspaces.id]
  name varchar(200) [not null]
  timezone varchar(64) [not null, note: 'Where a "day" starts for rollups and charts. Changing it means recomputing rollups']
  session_timeout_minutes smallint [not null, default: 30]
  created_at timestamptz [not null, default: `now()`]

  indexes {
    (workspace_id, name) [unique]
  }

  Note: 'One tracked product and environment, e.g. web app production. Everything below is scoped to a project, and staging is a separate project so test traffic never pollutes real numbers.'
}

Table api_keys [headercolor: #90a4ae] {
  id uuid [pk]
  project_id uuid [not null, ref: > projects.id]
  kind api_key_kind [not null]
  key_prefix varchar(12) [not null, note: 'First characters, shown in the UI so a key can be recognised']
  key_hash char(64) [not null, unique, note: 'SHA-256 of the key. A secret key is shown once at creation and never stored in clear']
  label varchar(100)
  created_by uuid [ref: > users.id]
  created_at timestamptz [not null, default: `now()`]
  last_used_at timestamptz
  revoked_at timestamptz
  Note: 'Ingestion keys are public (they ship inside apps and web pages) and can only write events; secret keys read data and stay on servers. Two kinds, never one key that does both.'
}

// ---------------------------------------------------------------------------
// IDENTITY AND SESSIONS: who did it, resolved without rewriting history
// ---------------------------------------------------------------------------

Table devices [headercolor: #4cd0b0] {
  id uuid [pk]
  project_id uuid [not null, ref: > projects.id]
  anonymous_id varchar(100) [not null, note: 'Generated by the SDK on first launch and kept in local storage or the keychain']
  person_id uuid [ref: > persons.id, note: 'CACHE of the alias resolution, set once the device is identified']
  platform varchar(30) [note: 'e.g. web, ios, android']
  first_seen_at timestamptz [not null]
  last_seen_at timestamptz [not null]
  initial_referrer varchar(500) [note: 'First-touch attribution: captured once, never overwritten']
  initial_utm_source varchar(100)
  initial_utm_medium varchar(100)
  initial_utm_campaign varchar(200)

  indexes {
    (project_id, anonymous_id) [unique]
  }

  Note: 'Browsers and app installs, known before anyone logs in. First-touch attribution lives here because it happened before identity did.'
}

Table persons [headercolor: #4cd0b0] {
  id uuid [pk]
  project_id uuid [not null, ref: > projects.id]
  external_id varchar(200) [note: 'Your own user id, sent with identify(). Null for persons only ever seen anonymously']
  properties jsonb [not null, default: '{}', note: 'CACHE: the current value of every person property, folded from person_property_changes']
  merged_into_id uuid [ref: > persons.id, note: 'Set when this person was merged into another; lookups follow it']
  first_seen_at timestamptz [not null]
  last_seen_at timestamptz [not null]
  deleted_at timestamptz [note: 'Erasure request. Their events are deleted by a background job; the row stays as a tombstone so the id is never reused']

  indexes {
    (project_id, external_id) [unique]
  }

  Note: 'The end users being measured, identified or not. One person can have many devices and many distinct ids.'
}

Table identity_aliases [headercolor: #4cd0b0] {
  project_id uuid [not null, ref: > projects.id]
  distinct_id varchar(200) [not null, note: 'Any id an event has arrived with: an anonymous id or an external id']
  person_id uuid [not null, ref: > persons.id]
  source alias_source [not null]
  created_at timestamptz [not null, default: `now()`]
  updated_at timestamptz [not null, note: 'Changes when a merge repoints the alias at the surviving person']

  indexes {
    (project_id, distinct_id) [pk]
    person_id
  }

  Note: 'The identity graph. Events keep the distinct_id they were sent with and are never rewritten; queries resolve distinct_id to person here. When an anonymous visitor logs in, or two persons merge, only these rows change, and the whole history moves with them.'
}

Table person_property_changes [headercolor: #4cd0b0] {
  person_id uuid [not null, ref: > persons.id]
  property_key varchar(200) [not null]
  set_at timestamptz [not null]
  operation property_operation [not null, note: 'set overwrites; set_once applies only if no value exists yet; unset removes it']
  value jsonb [note: 'Null for unset']
  source_event_id uuid [note: 'The event that carried the change, if any. Not a foreign key: events is partitioned']

  indexes {
    (person_id, property_key, set_at) [pk]
  }

  Note: 'Every change to a person property, in order. persons.properties holds the latest values; this table answers "what plan were they on when they did that?"'
}

Table sessions [headercolor: #4cd0b0] {
  id uuid [pk]
  project_id uuid [not null, ref: > projects.id]
  device_id uuid [not null, ref: > devices.id]
  started_at timestamptz [not null]
  ended_at timestamptz [not null]
  duration_s integer [not null]
  event_count integer [not null]
  pageview_count integer [not null, default: 0]
  entry_url varchar(2000)
  exit_url varchar(2000)
  referrer varchar(500)
  utm_source varchar(100)
  utm_medium varchar(100)
  utm_campaign varchar(200)
  country char(2)
  is_bounce boolean [not null, note: 'A single pageview and nothing else']

  indexes {
    (project_id, started_at)
    (device_id, started_at)
  }

  Note: 'Derived by the sessionizer: a run of events from one device with no gap longer than the project session timeout. Rebuildable from events, so the rules can change.'
}

// ---------------------------------------------------------------------------
// EVENTS AND REGISTRY: what happened, and separately what it means
// ---------------------------------------------------------------------------

Table events [headercolor: #4c8bf5] {
  id uuid [not null, note: 'Generated by the SDK, so a retried batch is recognised as a duplicate']
  project_id uuid [not null, ref: > projects.id]
  event_name varchar(200) [not null, note: 'Exactly as sent. Matched to event_definitions by name, never by foreign key']
  distinct_id varchar(200) [not null, note: 'As sent. Resolved to a person through identity_aliases at query time']
  session_id uuid [note: 'Stamped by the sessionizer after ingest']
  occurred_at timestamptz [not null, note: 'Client time corrected for clock skew (received_at minus sent_at). The partition key']
  sent_at timestamptz [note: 'Client clock when the batch left the device']
  received_at timestamptz [not null, default: `now()`]
  properties jsonb [not null, default: '{}', note: 'Everything else the SDK or caller attached. Promote hot keys to columns rather than indexing the whole document']
  url varchar(2000) [note: 'Promoted from properties: filtered on constantly']
  platform varchar(30) [note: 'Promoted from properties']
  app_version varchar(30) [note: 'Promoted from properties']

  indexes {
    (project_id, occurred_at, id) [pk, note: 'Includes the partition key, as Postgres requires of a partitioned table']
    (project_id, event_name, occurred_at)
    (project_id, distinct_id, occurred_at) [note: 'One person timeline']
  }

  Note: '''Raw events: append-only, never updated.
PARTITION BY RANGE (occurred_at), monthly, with a BRIN index on occurred_at in each partition. Retention is DROP PARTITION.
At real volume this table moves to a columnar store; the shape stays the same.'''
}

Table event_definitions [headercolor: #4c8bf5] {
  id uuid [pk]
  project_id uuid [not null, ref: > projects.id]
  name varchar(200) [not null, note: 'The raw event name as it appears in events']
  display_name varchar(200) [note: 'What the UI shows. Renaming here renames it everywhere without touching a single event']
  description text
  category varchar(100)
  status definition_status [not null, default: 'discovered']
  owner_user_id uuid [ref: > users.id]
  first_seen_at timestamptz [not null]
  last_seen_at timestamptz [not null]
  volume_30d bigint [note: 'CACHE from daily_event_rollups']

  indexes {
    (project_id, name) [unique]
  }

  Note: 'The registry: what an event MEANS, kept apart from what happened. A row is created automatically the first time a name is seen, so tracking is never blocked by governance; verifying, describing and hiding come after.'
}

Table property_definitions [headercolor: #4c8bf5] {
  id uuid [pk]
  project_id uuid [not null, ref: > projects.id]
  scope property_scope [not null]
  name varchar(200) [not null]
  data_type property_data_type [not null, note: 'Inferred from the first values seen, then confirmed by a person. Decides which filters the UI offers']
  description text
  is_pii boolean [not null, default: false, note: 'Masked in the UI and left out of exports']
  is_hidden boolean [not null, default: false]
  first_seen_at timestamptz [not null]

  indexes {
    (project_id, scope, name) [unique]
  }

  Note: 'Registry of event, person and session properties, with types. Without it every filter has to guess whether "1" is a number.'
}

Table event_property_usage [headercolor: #4c8bf5] {
  event_definition_id uuid [not null, ref: > event_definitions.id]
  property_definition_id uuid [not null, ref: > property_definitions.id]
  first_seen_at timestamptz [not null]
  last_seen_at timestamptz [not null]

  indexes {
    (event_definition_id, property_definition_id) [pk]
  }

  Note: 'Which properties actually arrive on which events, so the filter picker for an event lists only its own properties.'
}

Table daily_event_rollups [headercolor: #4c8bf5] {
  project_id uuid [not null, ref: > projects.id]
  event_name varchar(200) [not null]
  day date [not null, note: 'In the project timezone']
  event_count bigint [not null]
  unique_persons_estimate integer [not null]
  unique_persons_sketch bytea [not null, note: 'HyperLogLog sketch. Distinct counts cannot be added across days but sketches can be merged: weekly uniques merge seven of them']
  computed_at timestamptz [not null]

  indexes {
    (project_id, event_name, day) [pk]
  }

  Note: 'Pre-aggregated daily counts that keep event lists, volume charts and simple trends off the raw table. Recomputed for any day that receives late events.'
}

// ---------------------------------------------------------------------------
// FLAGS AND EXPERIMENTS
// ---------------------------------------------------------------------------

Table feature_flags [headercolor: #f5b74c] {
  id uuid [pk]
  project_id uuid [not null, ref: > projects.id]
  key varchar(100) [not null, note: 'Referenced in code, e.g. new-checkout. Never reused after archiving']
  name varchar(200) [not null]
  description text
  is_enabled boolean [not null, default: false, note: 'Kill switch: off serves the default to everyone, whatever the rules say']
  hash_salt varchar(40) [not null, note: 'Bucket = hash(key + salt + distinct_id) mod 100, so a user lands in the same bucket on every call with no assignment row stored']
  created_by uuid [ref: > users.id]
  created_at timestamptz [not null, default: `now()`]
  archived_at timestamptz

  indexes {
    (project_id, key) [unique]
  }

  Note: 'Feature flags. Evaluation is deterministic, which is what lets SDKs evaluate them locally instead of making a network call per check.'
}

Table flag_rules [headercolor: #f5b74c] {
  id uuid [pk]
  feature_flag_id uuid [not null, ref: > feature_flags.id]
  position smallint [not null, note: 'Evaluated in order; the first matching rule decides']
  cohort_id uuid [ref: > cohorts.id, note: 'Match people in this cohort']
  conditions jsonb [note: 'Property filters, e.g. [{"key": "plan", "op": "eq", "value": "pro"}]']
  rollout_pct numeric(5,2) [not null, default: 100, note: 'Share of matching people who get the flag']
  variant_key varchar(50) [note: 'Multivariate flags: serve this variant to everyone the rule matches']

  indexes {
    (feature_flag_id, position) [unique]
  }

  Note: 'Targeting: who gets the flag, as ordered conditions plus a percentage.'
}

Table experiments [headercolor: #f5b74c] {
  id uuid [pk]
  project_id uuid [not null, ref: > projects.id]
  feature_flag_id uuid [not null, unique, ref: - feature_flags.id, note: 'An experiment runs through its own flag; the variants are its buckets']
  name varchar(200) [not null]
  hypothesis text
  primary_funnel_id uuid [ref: > funnels.id, note: 'The success metric, fixed before launch rather than picked after the results are in']
  status experiment_status [not null, default: 'draft']
  minimum_sample_size integer [note: 'From the power calculation. Calling a winner before it is reached is how false positives ship']
  started_at timestamptz
  ended_at timestamptz
  winning_variant_id uuid [ref: > experiment_variants.id]
  created_by uuid [ref: > users.id]
  Note: 'A/B tests: a hypothesis, a primary metric chosen in advance, and a flag that splits traffic.'
}

Table experiment_variants [headercolor: #f5b74c] {
  id uuid [pk]
  experiment_id uuid [not null, ref: > experiments.id]
  key varchar(50) [not null, note: 'e.g. control, test-a. Matches the flag variant key']
  weight_pct numeric(5,2) [not null, note: 'The weights of one experiment sum to 100']
  is_control boolean [not null, default: false]

  indexes {
    (experiment_id, key) [unique]
  }

  Note: 'The arms of an experiment.'
}

Table experiment_exposures [headercolor: #f5b74c] {
  experiment_id uuid [not null, ref: > experiments.id]
  distinct_id varchar(200) [not null]
  variant_id uuid [not null, ref: > experiment_variants.id]
  first_exposed_at timestamptz [not null, note: 'When the user first saw a variant, not when they were bucketed']
  exposure_count integer [not null, default: 1]

  indexes {
    (experiment_id, distinct_id) [pk]
  }

  Note: 'One row per person per experiment, written the first time the flag is evaluated where its effect is visible. Analysis counts only exposed people, so users who never reached the changed screen do not dilute the result.'
}

// ---------------------------------------------------------------------------
// COHORTS AND FUNNELS: saved definitions, computed results
// ---------------------------------------------------------------------------

Table cohorts [headercolor: #b98cf0] {
  id uuid [pk]
  project_id uuid [not null, ref: > projects.id]
  name varchar(200) [not null]
  kind cohort_kind [not null]
  definition jsonb [note: 'Dynamic cohorts: the filter tree, e.g. did signed_up in the last 30 days AND plan = pro']
  current_version integer [not null, default: 0, note: 'The membership version readers use']
  member_count integer [note: 'CACHE for the current version']
  last_computed_at timestamptz
  created_by uuid [ref: > users.id]
  created_at timestamptz [not null, default: `now()`]
  Note: 'Saved groups of persons: dynamic (a definition, recomputed on a schedule) or static (an uploaded list).'
}

Table cohort_memberships [headercolor: #b98cf0] {
  cohort_id uuid [not null, ref: > cohorts.id]
  version integer [not null]
  person_id uuid [not null, ref: > persons.id]

  indexes {
    (cohort_id, version, person_id) [pk]
    person_id [note: 'Which cohorts is this person in? Flag evaluation asks this']
  }

  Note: 'Computed membership, by version. A recompute writes version n+1 in full, then flips cohorts.current_version in one update, so nobody ever reads a half-built cohort. Old versions are deleted afterwards.'
}

Table funnels [headercolor: #b98cf0] {
  id uuid [pk]
  project_id uuid [not null, ref: > projects.id]
  name varchar(200) [not null]
  step_order funnel_order [not null, default: 'ordered']
  conversion_window_seconds integer [not null, default: 1209600, note: 'From the first step to the last; 1209600 is 14 days']
  counting funnel_counting [not null, default: 'unique_persons']
  exclusion_event varchar(200) [note: 'An event that disqualifies a conversion if it happens between steps']
  created_by uuid [ref: > users.id]
  created_at timestamptz [not null, default: `now()`]
  Note: 'Saved funnel definitions. Results are computed from events on demand and never stored here.'
}

Table funnel_steps [headercolor: #b98cf0] {
  funnel_id uuid [not null, ref: > funnels.id]
  position smallint [not null]
  event_name varchar(200) [not null, note: 'The raw name, so changing a display name never breaks a funnel']
  filters jsonb [note: 'Property filters on this step only']
  label varchar(200)

  indexes {
    (funnel_id, position) [pk]
  }

  Note: 'The ordered steps of a funnel.'
}

// ---------------------------------------------------------------------------
// DASHBOARDS AND REPORTS
// ---------------------------------------------------------------------------

Table saved_reports [headercolor: #8bc34a] {
  id uuid [pk]
  project_id uuid [not null, ref: > projects.id]
  name varchar(200) [not null]
  kind report_kind [not null]
  funnel_id uuid [ref: > funnels.id, note: 'For funnel reports']
  cohort_id uuid [ref: > cohorts.id, note: 'Optional filter or breakdown by cohort']
  query jsonb [not null, note: 'The full query: events, filters, breakdowns and a relative date range (e.g. last 30 days) so it stays current']
  cached_result jsonb [note: 'CACHE of the last run. Dashboards render it and refresh in the background']
  cached_at timestamptz
  created_by uuid [ref: > users.id]
  created_at timestamptz [not null, default: `now()`]
  updated_at timestamptz [not null]
  Note: 'Saved insights: trends, funnels, retention, paths. A report is a stored query; its result is only ever a cache.'
}

Table dashboards [headercolor: #8bc34a] {
  id uuid [pk]
  project_id uuid [not null, ref: > projects.id]
  name varchar(200) [not null]
  description text
  is_shared boolean [not null, default: true, note: 'Visible to the whole workspace, not just its creator']
  share_token varchar(64) [unique, note: 'Set when shared by public link; rotate it to revoke the link']
  created_by uuid [ref: > users.id]
  created_at timestamptz [not null, default: `now()`]
  Note: 'Collections of reports laid out on a grid.'
}

Table dashboard_tiles [headercolor: #8bc34a] {
  id uuid [pk]
  dashboard_id uuid [not null, ref: > dashboards.id]
  saved_report_id uuid [ref: > saved_reports.id, note: 'Null for a text tile']
  text_body text [note: 'Markdown, for text tiles']
  grid_x smallint [not null]
  grid_y smallint [not null]
  grid_w smallint [not null]
  grid_h smallint [not null]
  Note: 'Where a report sits on a dashboard. One report can appear on many dashboards and is still edited in one place.'
}

// ---------------------------------------------------------------------------
// ENUMS
// ---------------------------------------------------------------------------

Enum workspace_plan {
  free
  growth
  enterprise
}

Enum member_role {
  viewer
  analyst
  admin
  owner
}

Enum api_key_kind {
  public_ingest [note: 'Write-only, safe to embed in a client']
  secret [note: 'Reads data; server-side only']
}

Enum alias_source {
  first_seen
  identify
  alias_call
  merge
}

Enum property_operation {
  set
  set_once
  unset
}

Enum definition_status {
  discovered
  verified
  hidden
  deprecated
}

Enum property_scope {
  event
  person
  session
}

Enum property_data_type {
  string
  number
  boolean
  datetime
  list
}

Enum experiment_status {
  draft
  running
  stopped
  concluded
}

Enum cohort_kind {
  dynamic
  static
}

Enum funnel_order {
  strict [note: 'Steps back to back, nothing in between']
  ordered [note: 'In order, other events allowed between']
  any_order
}

Enum funnel_counting {
  unique_persons
  unique_sessions
  totals
}

Enum report_kind {
  trend
  funnel
  retention
  paths
  stickiness
  lifecycle
}

Product Analytics database schema as SQL

The same schema as CREATE TABLE statements, exported by DB Planner. PostgreSQL is shown first; MySQL and SQL Server are below it.

PostgreSQL
postgresql.sql PostgreSQL
CREATE TYPE "workspace_plan" AS ENUM (
  'free',
  'growth',
  'enterprise'
);

CREATE TYPE "member_role" AS ENUM (
  'viewer',
  'analyst',
  'admin',
  'owner'
);

CREATE TYPE "api_key_kind" AS ENUM (
  'public_ingest',
  'secret'
);

CREATE TYPE "alias_source" AS ENUM (
  'first_seen',
  'identify',
  'alias_call',
  'merge'
);

CREATE TYPE "property_operation" AS ENUM (
  'set',
  'set_once',
  'unset'
);

CREATE TYPE "definition_status" AS ENUM (
  'discovered',
  'verified',
  'hidden',
  'deprecated'
);

CREATE TYPE "property_scope" AS ENUM (
  'event',
  'person',
  'session'
);

CREATE TYPE "property_data_type" AS ENUM (
  'string',
  'number',
  'boolean',
  'datetime',
  'list'
);

CREATE TYPE "experiment_status" AS ENUM (
  'draft',
  'running',
  'stopped',
  'concluded'
);

CREATE TYPE "cohort_kind" AS ENUM (
  'dynamic',
  'static'
);

CREATE TYPE "funnel_order" AS ENUM (
  'strict',
  'ordered',
  'any_order'
);

CREATE TYPE "funnel_counting" AS ENUM (
  'unique_persons',
  'unique_sessions',
  'totals'
);

CREATE TYPE "report_kind" AS ENUM (
  'trend',
  'funnel',
  'retention',
  'paths',
  'stickiness',
  'lifecycle'
);

CREATE TABLE "workspaces" (
  "id" uuid PRIMARY KEY,
  "name" varchar(200) NOT NULL,
  "slug" varchar(60) UNIQUE NOT NULL,
  "plan" workspace_plan NOT NULL,
  "monthly_event_quota" bigint,
  "created_at" timestamptz NOT NULL DEFAULT (now())
);

CREATE TABLE "users" (
  "id" uuid PRIMARY KEY,
  "email" varchar(254) UNIQUE NOT NULL,
  "name" varchar(200) NOT NULL,
  "created_at" timestamptz NOT NULL DEFAULT (now())
);

CREATE TABLE "workspace_members" (
  "workspace_id" uuid NOT NULL,
  "user_id" uuid NOT NULL,
  "role" member_role NOT NULL,
  "joined_at" timestamptz NOT NULL DEFAULT (now()),
  PRIMARY KEY ("workspace_id", "user_id")
);

CREATE TABLE "projects" (
  "id" uuid PRIMARY KEY,
  "workspace_id" uuid NOT NULL,
  "name" varchar(200) NOT NULL,
  "timezone" varchar(64) NOT NULL,
  "session_timeout_minutes" smallint NOT NULL DEFAULT 30,
  "created_at" timestamptz NOT NULL DEFAULT (now())
);

CREATE TABLE "api_keys" (
  "id" uuid PRIMARY KEY,
  "project_id" uuid NOT NULL,
  "kind" api_key_kind NOT NULL,
  "key_prefix" varchar(12) NOT NULL,
  "key_hash" char(64) UNIQUE NOT NULL,
  "label" varchar(100),
  "created_by" uuid,
  "created_at" timestamptz NOT NULL DEFAULT (now()),
  "last_used_at" timestamptz,
  "revoked_at" timestamptz
);

CREATE TABLE "devices" (
  "id" uuid PRIMARY KEY,
  "project_id" uuid NOT NULL,
  "anonymous_id" varchar(100) NOT NULL,
  "person_id" uuid,
  "platform" varchar(30),
  "first_seen_at" timestamptz NOT NULL,
  "last_seen_at" timestamptz NOT NULL,
  "initial_referrer" varchar(500),
  "initial_utm_source" varchar(100),
  "initial_utm_medium" varchar(100),
  "initial_utm_campaign" varchar(200)
);

CREATE TABLE "persons" (
  "id" uuid PRIMARY KEY,
  "project_id" uuid NOT NULL,
  "external_id" varchar(200),
  "properties" jsonb NOT NULL DEFAULT '{}',
  "merged_into_id" uuid,
  "first_seen_at" timestamptz NOT NULL,
  "last_seen_at" timestamptz NOT NULL,
  "deleted_at" timestamptz
);

CREATE TABLE "identity_aliases" (
  "project_id" uuid NOT NULL,
  "distinct_id" varchar(200) NOT NULL,
  "person_id" uuid NOT NULL,
  "source" alias_source NOT NULL,
  "created_at" timestamptz NOT NULL DEFAULT (now()),
  "updated_at" timestamptz NOT NULL,
  PRIMARY KEY ("project_id", "distinct_id")
);

CREATE TABLE "person_property_changes" (
  "person_id" uuid NOT NULL,
  "property_key" varchar(200) NOT NULL,
  "set_at" timestamptz NOT NULL,
  "operation" property_operation NOT NULL,
  "value" jsonb,
  "source_event_id" uuid,
  PRIMARY KEY ("person_id", "property_key", "set_at")
);

CREATE TABLE "sessions" (
  "id" uuid PRIMARY KEY,
  "project_id" uuid NOT NULL,
  "device_id" uuid NOT NULL,
  "started_at" timestamptz NOT NULL,
  "ended_at" timestamptz NOT NULL,
  "duration_s" integer NOT NULL,
  "event_count" integer NOT NULL,
  "pageview_count" integer NOT NULL DEFAULT 0,
  "entry_url" varchar(2000),
  "exit_url" varchar(2000),
  "referrer" varchar(500),
  "utm_source" varchar(100),
  "utm_medium" varchar(100),
  "utm_campaign" varchar(200),
  "country" char(2),
  "is_bounce" boolean NOT NULL
);

CREATE TABLE "events" (
  "id" uuid NOT NULL,
  "project_id" uuid NOT NULL,
  "event_name" varchar(200) NOT NULL,
  "distinct_id" varchar(200) NOT NULL,
  "session_id" uuid,
  "occurred_at" timestamptz NOT NULL,
  "sent_at" timestamptz,
  "received_at" timestamptz NOT NULL DEFAULT (now()),
  "properties" jsonb NOT NULL DEFAULT '{}',
  "url" varchar(2000),
  "platform" varchar(30),
  "app_version" varchar(30),
  PRIMARY KEY ("project_id", "occurred_at", "id")
);

CREATE TABLE "event_definitions" (
  "id" uuid PRIMARY KEY,
  "project_id" uuid NOT NULL,
  "name" varchar(200) NOT NULL,
  "display_name" varchar(200),
  "description" text,
  "category" varchar(100),
  "status" definition_status NOT NULL DEFAULT 'discovered',
  "owner_user_id" uuid,
  "first_seen_at" timestamptz NOT NULL,
  "last_seen_at" timestamptz NOT NULL,
  "volume_30d" bigint
);

CREATE TABLE "property_definitions" (
  "id" uuid PRIMARY KEY,
  "project_id" uuid NOT NULL,
  "scope" property_scope NOT NULL,
  "name" varchar(200) NOT NULL,
  "data_type" property_data_type NOT NULL,
  "description" text,
  "is_pii" boolean NOT NULL DEFAULT false,
  "is_hidden" boolean NOT NULL DEFAULT false,
  "first_seen_at" timestamptz NOT NULL
);

CREATE TABLE "event_property_usage" (
  "event_definition_id" uuid NOT NULL,
  "property_definition_id" uuid NOT NULL,
  "first_seen_at" timestamptz NOT NULL,
  "last_seen_at" timestamptz NOT NULL,
  PRIMARY KEY ("event_definition_id", "property_definition_id")
);

CREATE TABLE "daily_event_rollups" (
  "project_id" uuid NOT NULL,
  "event_name" varchar(200) NOT NULL,
  "day" date NOT NULL,
  "event_count" bigint NOT NULL,
  "unique_persons_estimate" integer NOT NULL,
  "unique_persons_sketch" bytea NOT NULL,
  "computed_at" timestamptz NOT NULL,
  PRIMARY KEY ("project_id", "event_name", "day")
);

CREATE TABLE "feature_flags" (
  "id" uuid PRIMARY KEY,
  "project_id" uuid NOT NULL,
  "key" varchar(100) NOT NULL,
  "name" varchar(200) NOT NULL,
  "description" text,
  "is_enabled" boolean NOT NULL DEFAULT false,
  "hash_salt" varchar(40) NOT NULL,
  "created_by" uuid,
  "created_at" timestamptz NOT NULL DEFAULT (now()),
  "archived_at" timestamptz
);

CREATE TABLE "flag_rules" (
  "id" uuid PRIMARY KEY,
  "feature_flag_id" uuid NOT NULL,
  "position" smallint NOT NULL,
  "cohort_id" uuid,
  "conditions" jsonb,
  "rollout_pct" numeric(5,2) NOT NULL DEFAULT 100,
  "variant_key" varchar(50)
);

CREATE TABLE "experiments" (
  "id" uuid PRIMARY KEY,
  "project_id" uuid NOT NULL,
  "feature_flag_id" uuid UNIQUE NOT NULL,
  "name" varchar(200) NOT NULL,
  "hypothesis" text,
  "primary_funnel_id" uuid,
  "status" experiment_status NOT NULL DEFAULT 'draft',
  "minimum_sample_size" integer,
  "started_at" timestamptz,
  "ended_at" timestamptz,
  "winning_variant_id" uuid,
  "created_by" uuid
);

CREATE TABLE "experiment_variants" (
  "id" uuid PRIMARY KEY,
  "experiment_id" uuid NOT NULL,
  "key" varchar(50) NOT NULL,
  "weight_pct" numeric(5,2) NOT NULL,
  "is_control" boolean NOT NULL DEFAULT false
);

CREATE TABLE "experiment_exposures" (
  "experiment_id" uuid NOT NULL,
  "distinct_id" varchar(200) NOT NULL,
  "variant_id" uuid NOT NULL,
  "first_exposed_at" timestamptz NOT NULL,
  "exposure_count" integer NOT NULL DEFAULT 1,
  PRIMARY KEY ("experiment_id", "distinct_id")
);

CREATE TABLE "cohorts" (
  "id" uuid PRIMARY KEY,
  "project_id" uuid NOT NULL,
  "name" varchar(200) NOT NULL,
  "kind" cohort_kind NOT NULL,
  "definition" jsonb,
  "current_version" integer NOT NULL DEFAULT 0,
  "member_count" integer,
  "last_computed_at" timestamptz,
  "created_by" uuid,
  "created_at" timestamptz NOT NULL DEFAULT (now())
);

CREATE TABLE "cohort_memberships" (
  "cohort_id" uuid NOT NULL,
  "version" integer NOT NULL,
  "person_id" uuid NOT NULL,
  PRIMARY KEY ("cohort_id", "version", "person_id")
);

CREATE TABLE "funnels" (
  "id" uuid PRIMARY KEY,
  "project_id" uuid NOT NULL,
  "name" varchar(200) NOT NULL,
  "step_order" funnel_order NOT NULL DEFAULT 'ordered',
  "conversion_window_seconds" integer NOT NULL DEFAULT 1209600,
  "counting" funnel_counting NOT NULL DEFAULT 'unique_persons',
  "exclusion_event" varchar(200),
  "created_by" uuid,
  "created_at" timestamptz NOT NULL DEFAULT (now())
);

CREATE TABLE "funnel_steps" (
  "funnel_id" uuid NOT NULL,
  "position" smallint NOT NULL,
  "event_name" varchar(200) NOT NULL,
  "filters" jsonb,
  "label" varchar(200),
  PRIMARY KEY ("funnel_id", "position")
);

CREATE TABLE "saved_reports" (
  "id" uuid PRIMARY KEY,
  "project_id" uuid NOT NULL,
  "name" varchar(200) NOT NULL,
  "kind" report_kind NOT NULL,
  "funnel_id" uuid,
  "cohort_id" uuid,
  "query" jsonb NOT NULL,
  "cached_result" jsonb,
  "cached_at" timestamptz,
  "created_by" uuid,
  "created_at" timestamptz NOT NULL DEFAULT (now()),
  "updated_at" timestamptz NOT NULL
);

CREATE TABLE "dashboards" (
  "id" uuid PRIMARY KEY,
  "project_id" uuid NOT NULL,
  "name" varchar(200) NOT NULL,
  "description" text,
  "is_shared" boolean NOT NULL DEFAULT true,
  "share_token" varchar(64) UNIQUE,
  "created_by" uuid,
  "created_at" timestamptz NOT NULL DEFAULT (now())
);

CREATE TABLE "dashboard_tiles" (
  "id" uuid PRIMARY KEY,
  "dashboard_id" uuid NOT NULL,
  "saved_report_id" uuid,
  "text_body" text,
  "grid_x" smallint NOT NULL,
  "grid_y" smallint NOT NULL,
  "grid_w" smallint NOT NULL,
  "grid_h" smallint NOT NULL
);

CREATE UNIQUE INDEX ON "projects" ("workspace_id", "name");

CREATE UNIQUE INDEX ON "devices" ("project_id", "anonymous_id");

CREATE UNIQUE INDEX ON "persons" ("project_id", "external_id");

CREATE INDEX ON "identity_aliases" ("person_id");

CREATE INDEX ON "sessions" ("project_id", "started_at");

CREATE INDEX ON "sessions" ("device_id", "started_at");

CREATE INDEX ON "events" ("project_id", "event_name", "occurred_at");

CREATE INDEX ON "events" ("project_id", "distinct_id", "occurred_at");

CREATE UNIQUE INDEX ON "event_definitions" ("project_id", "name");

CREATE UNIQUE INDEX ON "property_definitions" ("project_id", "scope", "name");

CREATE UNIQUE INDEX ON "feature_flags" ("project_id", "key");

CREATE UNIQUE INDEX ON "flag_rules" ("feature_flag_id", "position");

CREATE UNIQUE INDEX ON "experiment_variants" ("experiment_id", "key");

CREATE INDEX ON "cohort_memberships" ("person_id");

COMMENT ON TABLE "workspaces" IS 'The billing and access boundary: one company using the product.';

COMMENT ON COLUMN "workspaces"."monthly_event_quota" IS 'Billing limit. Ingestion keeps accepting past it and flags the overage; dropping data is never the answer';

COMMENT ON TABLE "users" IS 'People who log in to the analytics product. Not to be confused with persons, the end users being measured.';

COMMENT ON TABLE "workspace_members" IS 'Who can see and change what in a workspace.';

COMMENT ON TABLE "projects" IS 'One tracked product and environment, e.g. web app production. Everything below is scoped to a project, and staging is a separate project so test traffic never pollutes real numbers.';

COMMENT ON COLUMN "projects"."timezone" IS 'Where a "day" starts for rollups and charts. Changing it means recomputing rollups';

COMMENT ON TABLE "api_keys" IS 'Ingestion keys are public (they ship inside apps and web pages) and can only write events; secret keys read data and stay on servers. Two kinds, never one key that does both.';

COMMENT ON COLUMN "api_keys"."key_prefix" IS 'First characters, shown in the UI so a key can be recognised';

COMMENT ON COLUMN "api_keys"."key_hash" IS 'SHA-256 of the key. A secret key is shown once at creation and never stored in clear';

COMMENT ON TABLE "devices" IS 'Browsers and app installs, known before anyone logs in. First-touch attribution lives here because it happened before identity did.';

COMMENT ON COLUMN "devices"."anonymous_id" IS 'Generated by the SDK on first launch and kept in local storage or the keychain';

COMMENT ON COLUMN "devices"."person_id" IS 'CACHE of the alias resolution, set once the device is identified';

COMMENT ON COLUMN "devices"."platform" IS 'e.g. web, ios, android';

COMMENT ON COLUMN "devices"."initial_referrer" IS 'First-touch attribution: captured once, never overwritten';

COMMENT ON TABLE "persons" IS 'The end users being measured, identified or not. One person can have many devices and many distinct ids.';

COMMENT ON COLUMN "persons"."external_id" IS 'Your own user id, sent with identify(). Null for persons only ever seen anonymously';

COMMENT ON COLUMN "persons"."properties" IS 'CACHE: the current value of every person property, folded from person_property_changes';

COMMENT ON COLUMN "persons"."merged_into_id" IS 'Set when this person was merged into another; lookups follow it';

COMMENT ON COLUMN "persons"."deleted_at" IS 'Erasure request. Their events are deleted by a background job; the row stays as a tombstone so the id is never reused';

COMMENT ON TABLE "identity_aliases" IS 'The identity graph. Events keep the distinct_id they were sent with and are never rewritten; queries resolve distinct_id to person here. When an anonymous visitor logs in, or two persons merge, only these rows change, and the whole history moves with them.';

COMMENT ON COLUMN "identity_aliases"."distinct_id" IS 'Any id an event has arrived with: an anonymous id or an external id';

COMMENT ON COLUMN "identity_aliases"."updated_at" IS 'Changes when a merge repoints the alias at the surviving person';

COMMENT ON TABLE "person_property_changes" IS 'Every change to a person property, in order. persons.properties holds the latest values; this table answers "what plan were they on when they did that?"';

COMMENT ON COLUMN "person_property_changes"."operation" IS 'set overwrites; set_once applies only if no value exists yet; unset removes it';

COMMENT ON COLUMN "person_property_changes"."value" IS 'Null for unset';

COMMENT ON COLUMN "person_property_changes"."source_event_id" IS 'The event that carried the change, if any. Not a foreign key: events is partitioned';

COMMENT ON TABLE "sessions" IS 'Derived by the sessionizer: a run of events from one device with no gap longer than the project session timeout. Rebuildable from events, so the rules can change.';

COMMENT ON COLUMN "sessions"."is_bounce" IS 'A single pageview and nothing else';

COMMENT ON TABLE "events" IS 'Raw events: append-only, never updated.
PARTITION BY RANGE (occurred_at), monthly, with a BRIN index on occurred_at in each partition. Retention is DROP PARTITION.
At real volume this table moves to a columnar store; the shape stays the same.';

COMMENT ON COLUMN "events"."id" IS 'Generated by the SDK, so a retried batch is recognised as a duplicate';

COMMENT ON COLUMN "events"."event_name" IS 'Exactly as sent. Matched to event_definitions by name, never by foreign key';

COMMENT ON COLUMN "events"."distinct_id" IS 'As sent. Resolved to a person through identity_aliases at query time';

COMMENT ON COLUMN "events"."session_id" IS 'Stamped by the sessionizer after ingest';

COMMENT ON COLUMN "events"."occurred_at" IS 'Client time corrected for clock skew (received_at minus sent_at). The partition key';

COMMENT ON COLUMN "events"."sent_at" IS 'Client clock when the batch left the device';

COMMENT ON COLUMN "events"."properties" IS 'Everything else the SDK or caller attached. Promote hot keys to columns rather than indexing the whole document';

COMMENT ON COLUMN "events"."url" IS 'Promoted from properties: filtered on constantly';

COMMENT ON COLUMN "events"."platform" IS 'Promoted from properties';

COMMENT ON COLUMN "events"."app_version" IS 'Promoted from properties';

COMMENT ON TABLE "event_definitions" IS 'The registry: what an event MEANS, kept apart from what happened. A row is created automatically the first time a name is seen, so tracking is never blocked by governance; verifying, describing and hiding come after.';

COMMENT ON COLUMN "event_definitions"."name" IS 'The raw event name as it appears in events';

COMMENT ON COLUMN "event_definitions"."display_name" IS 'What the UI shows. Renaming here renames it everywhere without touching a single event';

COMMENT ON COLUMN "event_definitions"."volume_30d" IS 'CACHE from daily_event_rollups';

COMMENT ON TABLE "property_definitions" IS 'Registry of event, person and session properties, with types. Without it every filter has to guess whether "1" is a number.';

COMMENT ON COLUMN "property_definitions"."data_type" IS 'Inferred from the first values seen, then confirmed by a person. Decides which filters the UI offers';

COMMENT ON COLUMN "property_definitions"."is_pii" IS 'Masked in the UI and left out of exports';

COMMENT ON TABLE "event_property_usage" IS 'Which properties actually arrive on which events, so the filter picker for an event lists only its own properties.';

COMMENT ON TABLE "daily_event_rollups" IS 'Pre-aggregated daily counts that keep event lists, volume charts and simple trends off the raw table. Recomputed for any day that receives late events.';

COMMENT ON COLUMN "daily_event_rollups"."day" IS 'In the project timezone';

COMMENT ON COLUMN "daily_event_rollups"."unique_persons_sketch" IS 'HyperLogLog sketch. Distinct counts cannot be added across days but sketches can be merged: weekly uniques merge seven of them';

COMMENT ON TABLE "feature_flags" IS 'Feature flags. Evaluation is deterministic, which is what lets SDKs evaluate them locally instead of making a network call per check.';

COMMENT ON COLUMN "feature_flags"."key" IS 'Referenced in code, e.g. new-checkout. Never reused after archiving';

COMMENT ON COLUMN "feature_flags"."is_enabled" IS 'Kill switch: off serves the default to everyone, whatever the rules say';

COMMENT ON COLUMN "feature_flags"."hash_salt" IS 'Bucket = hash(key + salt + distinct_id) mod 100, so a user lands in the same bucket on every call with no assignment row stored';

COMMENT ON TABLE "flag_rules" IS 'Targeting: who gets the flag, as ordered conditions plus a percentage.';

COMMENT ON COLUMN "flag_rules"."position" IS 'Evaluated in order; the first matching rule decides';

COMMENT ON COLUMN "flag_rules"."cohort_id" IS 'Match people in this cohort';

COMMENT ON COLUMN "flag_rules"."conditions" IS 'Property filters, e.g. [{"key": "plan", "op": "eq", "value": "pro"}]';

COMMENT ON COLUMN "flag_rules"."rollout_pct" IS 'Share of matching people who get the flag';

COMMENT ON COLUMN "flag_rules"."variant_key" IS 'Multivariate flags: serve this variant to everyone the rule matches';

COMMENT ON TABLE "experiments" IS 'A/B tests: a hypothesis, a primary metric chosen in advance, and a flag that splits traffic.';

COMMENT ON COLUMN "experiments"."feature_flag_id" IS 'An experiment runs through its own flag; the variants are its buckets';

COMMENT ON COLUMN "experiments"."primary_funnel_id" IS 'The success metric, fixed before launch rather than picked after the results are in';

COMMENT ON COLUMN "experiments"."minimum_sample_size" IS 'From the power calculation. Calling a winner before it is reached is how false positives ship';

COMMENT ON TABLE "experiment_variants" IS 'The arms of an experiment.';

COMMENT ON COLUMN "experiment_variants"."key" IS 'e.g. control, test-a. Matches the flag variant key';

COMMENT ON COLUMN "experiment_variants"."weight_pct" IS 'The weights of one experiment sum to 100';

COMMENT ON TABLE "experiment_exposures" IS 'One row per person per experiment, written the first time the flag is evaluated where its effect is visible. Analysis counts only exposed people, so users who never reached the changed screen do not dilute the result.';

COMMENT ON COLUMN "experiment_exposures"."first_exposed_at" IS 'When the user first saw a variant, not when they were bucketed';

COMMENT ON TABLE "cohorts" IS 'Saved groups of persons: dynamic (a definition, recomputed on a schedule) or static (an uploaded list).';

COMMENT ON COLUMN "cohorts"."definition" IS 'Dynamic cohorts: the filter tree, e.g. did signed_up in the last 30 days AND plan = pro';

COMMENT ON COLUMN "cohorts"."current_version" IS 'The membership version readers use';

COMMENT ON COLUMN "cohorts"."member_count" IS 'CACHE for the current version';

COMMENT ON TABLE "cohort_memberships" IS 'Computed membership, by version. A recompute writes version n+1 in full, then flips cohorts.current_version in one update, so nobody ever reads a half-built cohort. Old versions are deleted afterwards.';

COMMENT ON TABLE "funnels" IS 'Saved funnel definitions. Results are computed from events on demand and never stored here.';

COMMENT ON COLUMN "funnels"."conversion_window_seconds" IS 'From the first step to the last; 1209600 is 14 days';

COMMENT ON COLUMN "funnels"."exclusion_event" IS 'An event that disqualifies a conversion if it happens between steps';

COMMENT ON TABLE "funnel_steps" IS 'The ordered steps of a funnel.';

COMMENT ON COLUMN "funnel_steps"."event_name" IS 'The raw name, so changing a display name never breaks a funnel';

COMMENT ON COLUMN "funnel_steps"."filters" IS 'Property filters on this step only';

COMMENT ON TABLE "saved_reports" IS 'Saved insights: trends, funnels, retention, paths. A report is a stored query; its result is only ever a cache.';

COMMENT ON COLUMN "saved_reports"."funnel_id" IS 'For funnel reports';

COMMENT ON COLUMN "saved_reports"."cohort_id" IS 'Optional filter or breakdown by cohort';

COMMENT ON COLUMN "saved_reports"."query" IS 'The full query: events, filters, breakdowns and a relative date range (e.g. last 30 days) so it stays current';

COMMENT ON COLUMN "saved_reports"."cached_result" IS 'CACHE of the last run. Dashboards render it and refresh in the background';

COMMENT ON TABLE "dashboards" IS 'Collections of reports laid out on a grid.';

COMMENT ON COLUMN "dashboards"."is_shared" IS 'Visible to the whole workspace, not just its creator';

COMMENT ON COLUMN "dashboards"."share_token" IS 'Set when shared by public link; rotate it to revoke the link';

COMMENT ON TABLE "dashboard_tiles" IS 'Where a report sits on a dashboard. One report can appear on many dashboards and is still edited in one place.';

COMMENT ON COLUMN "dashboard_tiles"."saved_report_id" IS 'Null for a text tile';

COMMENT ON COLUMN "dashboard_tiles"."text_body" IS 'Markdown, for text tiles';

ALTER TABLE "workspace_members" ADD FOREIGN KEY ("workspace_id") REFERENCES "workspaces" ("id");

ALTER TABLE "workspace_members" ADD FOREIGN KEY ("user_id") REFERENCES "users" ("id");

ALTER TABLE "projects" ADD FOREIGN KEY ("workspace_id") REFERENCES "workspaces" ("id");

ALTER TABLE "api_keys" ADD FOREIGN KEY ("project_id") REFERENCES "projects" ("id");

ALTER TABLE "api_keys" ADD FOREIGN KEY ("created_by") REFERENCES "users" ("id");

ALTER TABLE "devices" ADD FOREIGN KEY ("project_id") REFERENCES "projects" ("id");

ALTER TABLE "devices" ADD FOREIGN KEY ("person_id") REFERENCES "persons" ("id");

ALTER TABLE "persons" ADD FOREIGN KEY ("project_id") REFERENCES "projects" ("id");

ALTER TABLE "persons" ADD FOREIGN KEY ("merged_into_id") REFERENCES "persons" ("id");

ALTER TABLE "identity_aliases" ADD FOREIGN KEY ("project_id") REFERENCES "projects" ("id");

ALTER TABLE "identity_aliases" ADD FOREIGN KEY ("person_id") REFERENCES "persons" ("id");

ALTER TABLE "person_property_changes" ADD FOREIGN KEY ("person_id") REFERENCES "persons" ("id");

ALTER TABLE "sessions" ADD FOREIGN KEY ("project_id") REFERENCES "projects" ("id");

ALTER TABLE "sessions" ADD FOREIGN KEY ("device_id") REFERENCES "devices" ("id");

ALTER TABLE "events" ADD FOREIGN KEY ("project_id") REFERENCES "projects" ("id");

ALTER TABLE "event_definitions" ADD FOREIGN KEY ("project_id") REFERENCES "projects" ("id");

ALTER TABLE "event_definitions" ADD FOREIGN KEY ("owner_user_id") REFERENCES "users" ("id");

ALTER TABLE "property_definitions" ADD FOREIGN KEY ("project_id") REFERENCES "projects" ("id");

ALTER TABLE "event_property_usage" ADD FOREIGN KEY ("event_definition_id") REFERENCES "event_definitions" ("id");

ALTER TABLE "event_property_usage" ADD FOREIGN KEY ("property_definition_id") REFERENCES "property_definitions" ("id");

ALTER TABLE "daily_event_rollups" ADD FOREIGN KEY ("project_id") REFERENCES "projects" ("id");

ALTER TABLE "feature_flags" ADD FOREIGN KEY ("project_id") REFERENCES "projects" ("id");

ALTER TABLE "feature_flags" ADD FOREIGN KEY ("created_by") REFERENCES "users" ("id");

ALTER TABLE "flag_rules" ADD FOREIGN KEY ("feature_flag_id") REFERENCES "feature_flags" ("id");

ALTER TABLE "flag_rules" ADD FOREIGN KEY ("cohort_id") REFERENCES "cohorts" ("id");

ALTER TABLE "experiments" ADD FOREIGN KEY ("project_id") REFERENCES "projects" ("id");

ALTER TABLE "experiments" ADD FOREIGN KEY ("feature_flag_id") REFERENCES "feature_flags" ("id");

ALTER TABLE "experiments" ADD FOREIGN KEY ("primary_funnel_id") REFERENCES "funnels" ("id");

ALTER TABLE "experiments" ADD FOREIGN KEY ("winning_variant_id") REFERENCES "experiment_variants" ("id");

ALTER TABLE "experiments" ADD FOREIGN KEY ("created_by") REFERENCES "users" ("id");

ALTER TABLE "experiment_variants" ADD FOREIGN KEY ("experiment_id") REFERENCES "experiments" ("id");

ALTER TABLE "experiment_exposures" ADD FOREIGN KEY ("experiment_id") REFERENCES "experiments" ("id");

ALTER TABLE "experiment_exposures" ADD FOREIGN KEY ("variant_id") REFERENCES "experiment_variants" ("id");

ALTER TABLE "cohorts" ADD FOREIGN KEY ("project_id") REFERENCES "projects" ("id");

ALTER TABLE "cohorts" ADD FOREIGN KEY ("created_by") REFERENCES "users" ("id");

ALTER TABLE "cohort_memberships" ADD FOREIGN KEY ("cohort_id") REFERENCES "cohorts" ("id");

ALTER TABLE "cohort_memberships" ADD FOREIGN KEY ("person_id") REFERENCES "persons" ("id");

ALTER TABLE "funnels" ADD FOREIGN KEY ("project_id") REFERENCES "projects" ("id");

ALTER TABLE "funnels" ADD FOREIGN KEY ("created_by") REFERENCES "users" ("id");

ALTER TABLE "funnel_steps" ADD FOREIGN KEY ("funnel_id") REFERENCES "funnels" ("id");

ALTER TABLE "saved_reports" ADD FOREIGN KEY ("project_id") REFERENCES "projects" ("id");

ALTER TABLE "saved_reports" ADD FOREIGN KEY ("funnel_id") REFERENCES "funnels" ("id");

ALTER TABLE "saved_reports" ADD FOREIGN KEY ("cohort_id") REFERENCES "cohorts" ("id");

ALTER TABLE "saved_reports" ADD FOREIGN KEY ("created_by") REFERENCES "users" ("id");

ALTER TABLE "dashboards" ADD FOREIGN KEY ("project_id") REFERENCES "projects" ("id");

ALTER TABLE "dashboards" ADD FOREIGN KEY ("created_by") REFERENCES "users" ("id");

ALTER TABLE "dashboard_tiles" ADD FOREIGN KEY ("dashboard_id") REFERENCES "dashboards" ("id");

ALTER TABLE "dashboard_tiles" ADD FOREIGN KEY ("saved_report_id") REFERENCES "saved_reports" ("id");
MySQL
mysql.sql MySQL
CREATE TABLE `workspaces` (
  `id` uuid PRIMARY KEY,
  `name` varchar(200) NOT NULL,
  `slug` varchar(60) UNIQUE NOT NULL,
  `plan` ENUM ('free', 'growth', 'enterprise') NOT NULL,
  `monthly_event_quota` bigint COMMENT 'Billing limit. Ingestion keeps accepting past it and flags the overage; dropping data is never the answer',
  `created_at` timestamptz NOT NULL DEFAULT (now())
);

CREATE TABLE `users` (
  `id` uuid PRIMARY KEY,
  `email` varchar(254) UNIQUE NOT NULL,
  `name` varchar(200) NOT NULL,
  `created_at` timestamptz NOT NULL DEFAULT (now())
);

CREATE TABLE `workspace_members` (
  `workspace_id` uuid NOT NULL,
  `user_id` uuid NOT NULL,
  `role` ENUM ('viewer', 'analyst', 'admin', 'owner') NOT NULL,
  `joined_at` timestamptz NOT NULL DEFAULT (now()),
  PRIMARY KEY (`workspace_id`, `user_id`)
);

CREATE TABLE `projects` (
  `id` uuid PRIMARY KEY,
  `workspace_id` uuid NOT NULL,
  `name` varchar(200) NOT NULL,
  `timezone` varchar(64) NOT NULL COMMENT 'Where a "day" starts for rollups and charts. Changing it means recomputing rollups',
  `session_timeout_minutes` smallint NOT NULL DEFAULT 30,
  `created_at` timestamptz NOT NULL DEFAULT (now())
);

CREATE TABLE `api_keys` (
  `id` uuid PRIMARY KEY,
  `project_id` uuid NOT NULL,
  `kind` ENUM ('public_ingest', 'secret') NOT NULL,
  `key_prefix` varchar(12) NOT NULL COMMENT 'First characters, shown in the UI so a key can be recognised',
  `key_hash` char(64) UNIQUE NOT NULL COMMENT 'SHA-256 of the key. A secret key is shown once at creation and never stored in clear',
  `label` varchar(100),
  `created_by` uuid,
  `created_at` timestamptz NOT NULL DEFAULT (now()),
  `last_used_at` timestamptz,
  `revoked_at` timestamptz
);

CREATE TABLE `devices` (
  `id` uuid PRIMARY KEY,
  `project_id` uuid NOT NULL,
  `anonymous_id` varchar(100) NOT NULL COMMENT 'Generated by the SDK on first launch and kept in local storage or the keychain',
  `person_id` uuid COMMENT 'CACHE of the alias resolution, set once the device is identified',
  `platform` varchar(30) COMMENT 'e.g. web, ios, android',
  `first_seen_at` timestamptz NOT NULL,
  `last_seen_at` timestamptz NOT NULL,
  `initial_referrer` varchar(500) COMMENT 'First-touch attribution: captured once, never overwritten',
  `initial_utm_source` varchar(100),
  `initial_utm_medium` varchar(100),
  `initial_utm_campaign` varchar(200)
);

CREATE TABLE `persons` (
  `id` uuid PRIMARY KEY,
  `project_id` uuid NOT NULL,
  `external_id` varchar(200) COMMENT 'Your own user id, sent with identify(). Null for persons only ever seen anonymously',
  `properties` jsonb NOT NULL DEFAULT '{}' COMMENT 'CACHE: the current value of every person property, folded from person_property_changes',
  `merged_into_id` uuid COMMENT 'Set when this person was merged into another; lookups follow it',
  `first_seen_at` timestamptz NOT NULL,
  `last_seen_at` timestamptz NOT NULL,
  `deleted_at` timestamptz COMMENT 'Erasure request. Their events are deleted by a background job; the row stays as a tombstone so the id is never reused'
);

CREATE TABLE `identity_aliases` (
  `project_id` uuid NOT NULL,
  `distinct_id` varchar(200) NOT NULL COMMENT 'Any id an event has arrived with: an anonymous id or an external id',
  `person_id` uuid NOT NULL,
  `source` ENUM ('first_seen', 'identify', 'alias_call', 'merge') NOT NULL,
  `created_at` timestamptz NOT NULL DEFAULT (now()),
  `updated_at` timestamptz NOT NULL COMMENT 'Changes when a merge repoints the alias at the surviving person',
  PRIMARY KEY (`project_id`, `distinct_id`)
);

CREATE TABLE `person_property_changes` (
  `person_id` uuid NOT NULL,
  `property_key` varchar(200) NOT NULL,
  `set_at` timestamptz NOT NULL,
  `operation` ENUM ('set', 'set_once', 'unset') NOT NULL COMMENT 'set overwrites; set_once applies only if no value exists yet; unset removes it',
  `value` jsonb COMMENT 'Null for unset',
  `source_event_id` uuid COMMENT 'The event that carried the change, if any. Not a foreign key: events is partitioned',
  PRIMARY KEY (`person_id`, `property_key`, `set_at`)
);

CREATE TABLE `sessions` (
  `id` uuid PRIMARY KEY,
  `project_id` uuid NOT NULL,
  `device_id` uuid NOT NULL,
  `started_at` timestamptz NOT NULL,
  `ended_at` timestamptz NOT NULL,
  `duration_s` integer NOT NULL,
  `event_count` integer NOT NULL,
  `pageview_count` integer NOT NULL DEFAULT 0,
  `entry_url` varchar(2000),
  `exit_url` varchar(2000),
  `referrer` varchar(500),
  `utm_source` varchar(100),
  `utm_medium` varchar(100),
  `utm_campaign` varchar(200),
  `country` char(2),
  `is_bounce` boolean NOT NULL COMMENT 'A single pageview and nothing else'
);

CREATE TABLE `events` (
  `id` uuid NOT NULL COMMENT 'Generated by the SDK, so a retried batch is recognised as a duplicate',
  `project_id` uuid NOT NULL,
  `event_name` varchar(200) NOT NULL COMMENT 'Exactly as sent. Matched to event_definitions by name, never by foreign key',
  `distinct_id` varchar(200) NOT NULL COMMENT 'As sent. Resolved to a person through identity_aliases at query time',
  `session_id` uuid COMMENT 'Stamped by the sessionizer after ingest',
  `occurred_at` timestamptz NOT NULL COMMENT 'Client time corrected for clock skew (received_at minus sent_at). The partition key',
  `sent_at` timestamptz COMMENT 'Client clock when the batch left the device',
  `received_at` timestamptz NOT NULL DEFAULT (now()),
  `properties` jsonb NOT NULL DEFAULT '{}' COMMENT 'Everything else the SDK or caller attached. Promote hot keys to columns rather than indexing the whole document',
  `url` varchar(2000) COMMENT 'Promoted from properties: filtered on constantly',
  `platform` varchar(30) COMMENT 'Promoted from properties',
  `app_version` varchar(30) COMMENT 'Promoted from properties',
  PRIMARY KEY (`project_id`, `occurred_at`, `id`)
);

CREATE TABLE `event_definitions` (
  `id` uuid PRIMARY KEY,
  `project_id` uuid NOT NULL,
  `name` varchar(200) NOT NULL COMMENT 'The raw event name as it appears in events',
  `display_name` varchar(200) COMMENT 'What the UI shows. Renaming here renames it everywhere without touching a single event',
  `description` text,
  `category` varchar(100),
  `status` ENUM ('discovered', 'verified', 'hidden', 'deprecated') NOT NULL DEFAULT 'discovered',
  `owner_user_id` uuid,
  `first_seen_at` timestamptz NOT NULL,
  `last_seen_at` timestamptz NOT NULL,
  `volume_30d` bigint COMMENT 'CACHE from daily_event_rollups'
);

CREATE TABLE `property_definitions` (
  `id` uuid PRIMARY KEY,
  `project_id` uuid NOT NULL,
  `scope` ENUM ('event', 'person', 'session') NOT NULL,
  `name` varchar(200) NOT NULL,
  `data_type` ENUM ('string', 'number', 'boolean', 'datetime', 'list') NOT NULL COMMENT 'Inferred from the first values seen, then confirmed by a person. Decides which filters the UI offers',
  `description` text,
  `is_pii` boolean NOT NULL DEFAULT false COMMENT 'Masked in the UI and left out of exports',
  `is_hidden` boolean NOT NULL DEFAULT false,
  `first_seen_at` timestamptz NOT NULL
);

CREATE TABLE `event_property_usage` (
  `event_definition_id` uuid NOT NULL,
  `property_definition_id` uuid NOT NULL,
  `first_seen_at` timestamptz NOT NULL,
  `last_seen_at` timestamptz NOT NULL,
  PRIMARY KEY (`event_definition_id`, `property_definition_id`)
);

CREATE TABLE `daily_event_rollups` (
  `project_id` uuid NOT NULL,
  `event_name` varchar(200) NOT NULL,
  `day` date NOT NULL COMMENT 'In the project timezone',
  `event_count` bigint NOT NULL,
  `unique_persons_estimate` integer NOT NULL,
  `unique_persons_sketch` bytea NOT NULL COMMENT 'HyperLogLog sketch. Distinct counts cannot be added across days but sketches can be merged: weekly uniques merge seven of them',
  `computed_at` timestamptz NOT NULL,
  PRIMARY KEY (`project_id`, `event_name`, `day`)
);

CREATE TABLE `feature_flags` (
  `id` uuid PRIMARY KEY,
  `project_id` uuid NOT NULL,
  `key` varchar(100) NOT NULL COMMENT 'Referenced in code, e.g. new-checkout. Never reused after archiving',
  `name` varchar(200) NOT NULL,
  `description` text,
  `is_enabled` boolean NOT NULL DEFAULT false COMMENT 'Kill switch: off serves the default to everyone, whatever the rules say',
  `hash_salt` varchar(40) NOT NULL COMMENT 'Bucket = hash(key + salt + distinct_id) mod 100, so a user lands in the same bucket on every call with no assignment row stored',
  `created_by` uuid,
  `created_at` timestamptz NOT NULL DEFAULT (now()),
  `archived_at` timestamptz
);

CREATE TABLE `flag_rules` (
  `id` uuid PRIMARY KEY,
  `feature_flag_id` uuid NOT NULL,
  `position` smallint NOT NULL COMMENT 'Evaluated in order; the first matching rule decides',
  `cohort_id` uuid COMMENT 'Match people in this cohort',
  `conditions` jsonb COMMENT 'Property filters, e.g. [{"key": "plan", "op": "eq", "value": "pro"}]',
  `rollout_pct` numeric(5,2) NOT NULL DEFAULT 100 COMMENT 'Share of matching people who get the flag',
  `variant_key` varchar(50) COMMENT 'Multivariate flags: serve this variant to everyone the rule matches'
);

CREATE TABLE `experiments` (
  `id` uuid PRIMARY KEY,
  `project_id` uuid NOT NULL,
  `feature_flag_id` uuid UNIQUE NOT NULL COMMENT 'An experiment runs through its own flag; the variants are its buckets',
  `name` varchar(200) NOT NULL,
  `hypothesis` text,
  `primary_funnel_id` uuid COMMENT 'The success metric, fixed before launch rather than picked after the results are in',
  `status` ENUM ('draft', 'running', 'stopped', 'concluded') NOT NULL DEFAULT 'draft',
  `minimum_sample_size` integer COMMENT 'From the power calculation. Calling a winner before it is reached is how false positives ship',
  `started_at` timestamptz,
  `ended_at` timestamptz,
  `winning_variant_id` uuid,
  `created_by` uuid
);

CREATE TABLE `experiment_variants` (
  `id` uuid PRIMARY KEY,
  `experiment_id` uuid NOT NULL,
  `key` varchar(50) NOT NULL COMMENT 'e.g. control, test-a. Matches the flag variant key',
  `weight_pct` numeric(5,2) NOT NULL COMMENT 'The weights of one experiment sum to 100',
  `is_control` boolean NOT NULL DEFAULT false
);

CREATE TABLE `experiment_exposures` (
  `experiment_id` uuid NOT NULL,
  `distinct_id` varchar(200) NOT NULL,
  `variant_id` uuid NOT NULL,
  `first_exposed_at` timestamptz NOT NULL COMMENT 'When the user first saw a variant, not when they were bucketed',
  `exposure_count` integer NOT NULL DEFAULT 1,
  PRIMARY KEY (`experiment_id`, `distinct_id`)
);

CREATE TABLE `cohorts` (
  `id` uuid PRIMARY KEY,
  `project_id` uuid NOT NULL,
  `name` varchar(200) NOT NULL,
  `kind` ENUM ('dynamic', 'static') NOT NULL,
  `definition` jsonb COMMENT 'Dynamic cohorts: the filter tree, e.g. did signed_up in the last 30 days AND plan = pro',
  `current_version` integer NOT NULL DEFAULT 0 COMMENT 'The membership version readers use',
  `member_count` integer COMMENT 'CACHE for the current version',
  `last_computed_at` timestamptz,
  `created_by` uuid,
  `created_at` timestamptz NOT NULL DEFAULT (now())
);

CREATE TABLE `cohort_memberships` (
  `cohort_id` uuid NOT NULL,
  `version` integer NOT NULL,
  `person_id` uuid NOT NULL,
  PRIMARY KEY (`cohort_id`, `version`, `person_id`)
);

CREATE TABLE `funnels` (
  `id` uuid PRIMARY KEY,
  `project_id` uuid NOT NULL,
  `name` varchar(200) NOT NULL,
  `step_order` ENUM ('strict', 'ordered', 'any_order') NOT NULL DEFAULT 'ordered',
  `conversion_window_seconds` integer NOT NULL DEFAULT 1209600 COMMENT 'From the first step to the last; 1209600 is 14 days',
  `counting` ENUM ('unique_persons', 'unique_sessions', 'totals') NOT NULL DEFAULT 'unique_persons',
  `exclusion_event` varchar(200) COMMENT 'An event that disqualifies a conversion if it happens between steps',
  `created_by` uuid,
  `created_at` timestamptz NOT NULL DEFAULT (now())
);

CREATE TABLE `funnel_steps` (
  `funnel_id` uuid NOT NULL,
  `position` smallint NOT NULL,
  `event_name` varchar(200) NOT NULL COMMENT 'The raw name, so changing a display name never breaks a funnel',
  `filters` jsonb COMMENT 'Property filters on this step only',
  `label` varchar(200),
  PRIMARY KEY (`funnel_id`, `position`)
);

CREATE TABLE `saved_reports` (
  `id` uuid PRIMARY KEY,
  `project_id` uuid NOT NULL,
  `name` varchar(200) NOT NULL,
  `kind` ENUM ('trend', 'funnel', 'retention', 'paths', 'stickiness', 'lifecycle') NOT NULL,
  `funnel_id` uuid COMMENT 'For funnel reports',
  `cohort_id` uuid COMMENT 'Optional filter or breakdown by cohort',
  `query` jsonb NOT NULL COMMENT 'The full query: events, filters, breakdowns and a relative date range (e.g. last 30 days) so it stays current',
  `cached_result` jsonb COMMENT 'CACHE of the last run. Dashboards render it and refresh in the background',
  `cached_at` timestamptz,
  `created_by` uuid,
  `created_at` timestamptz NOT NULL DEFAULT (now()),
  `updated_at` timestamptz NOT NULL
);

CREATE TABLE `dashboards` (
  `id` uuid PRIMARY KEY,
  `project_id` uuid NOT NULL,
  `name` varchar(200) NOT NULL,
  `description` text,
  `is_shared` boolean NOT NULL DEFAULT true COMMENT 'Visible to the whole workspace, not just its creator',
  `share_token` varchar(64) UNIQUE COMMENT 'Set when shared by public link; rotate it to revoke the link',
  `created_by` uuid,
  `created_at` timestamptz NOT NULL DEFAULT (now())
);

CREATE TABLE `dashboard_tiles` (
  `id` uuid PRIMARY KEY,
  `dashboard_id` uuid NOT NULL,
  `saved_report_id` uuid COMMENT 'Null for a text tile',
  `text_body` text COMMENT 'Markdown, for text tiles',
  `grid_x` smallint NOT NULL,
  `grid_y` smallint NOT NULL,
  `grid_w` smallint NOT NULL,
  `grid_h` smallint NOT NULL
);

CREATE UNIQUE INDEX `projects_index_0` ON `projects` (`workspace_id`, `name`);

CREATE UNIQUE INDEX `devices_index_1` ON `devices` (`project_id`, `anonymous_id`);

CREATE UNIQUE INDEX `persons_index_2` ON `persons` (`project_id`, `external_id`);

CREATE INDEX `identity_aliases_index_3` ON `identity_aliases` (`person_id`);

CREATE INDEX `sessions_index_4` ON `sessions` (`project_id`, `started_at`);

CREATE INDEX `sessions_index_5` ON `sessions` (`device_id`, `started_at`);

CREATE INDEX `events_index_6` ON `events` (`project_id`, `event_name`, `occurred_at`);

CREATE INDEX `events_index_7` ON `events` (`project_id`, `distinct_id`, `occurred_at`);

CREATE UNIQUE INDEX `event_definitions_index_8` ON `event_definitions` (`project_id`, `name`);

CREATE UNIQUE INDEX `property_definitions_index_9` ON `property_definitions` (`project_id`, `scope`, `name`);

CREATE UNIQUE INDEX `feature_flags_index_10` ON `feature_flags` (`project_id`, `key`);

CREATE UNIQUE INDEX `flag_rules_index_11` ON `flag_rules` (`feature_flag_id`, `position`);

CREATE UNIQUE INDEX `experiment_variants_index_12` ON `experiment_variants` (`experiment_id`, `key`);

CREATE INDEX `cohort_memberships_index_13` ON `cohort_memberships` (`person_id`);

ALTER TABLE `workspaces` COMMENT = 'The billing and access boundary: one company using the product.';

ALTER TABLE `users` COMMENT = 'People who log in to the analytics product. Not to be confused with persons, the end users being measured.';

ALTER TABLE `workspace_members` COMMENT = 'Who can see and change what in a workspace.';

ALTER TABLE `projects` COMMENT = 'One tracked product and environment, e.g. web app production. Everything below is scoped to a project, and staging is a separate project so test traffic never pollutes real numbers.';

ALTER TABLE `api_keys` COMMENT = 'Ingestion keys are public (they ship inside apps and web pages) and can only write events; secret keys read data and stay on servers. Two kinds, never one key that does both.';

ALTER TABLE `devices` COMMENT = 'Browsers and app installs, known before anyone logs in. First-touch attribution lives here because it happened before identity did.';

ALTER TABLE `persons` COMMENT = 'The end users being measured, identified or not. One person can have many devices and many distinct ids.';

ALTER TABLE `identity_aliases` COMMENT = 'The identity graph. Events keep the distinct_id they were sent with and are never rewritten; queries resolve distinct_id to person here. When an anonymous visitor logs in, or two persons merge, only these rows change, and the whole history moves with them.';

ALTER TABLE `person_property_changes` COMMENT = 'Every change to a person property, in order. persons.properties holds the latest values; this table answers "what plan were they on when they did that?"';

ALTER TABLE `sessions` COMMENT = 'Derived by the sessionizer: a run of events from one device with no gap longer than the project session timeout. Rebuildable from events, so the rules can change.';

ALTER TABLE `events` COMMENT = 'Raw events: append-only, never updated.
PARTITION BY RANGE (occurred_at), monthly, with a BRIN index on occurred_at in each partition. Retention is DROP PARTITION.
At real volume this table moves to a columnar store; the shape stays the same.';

ALTER TABLE `event_definitions` COMMENT = 'The registry: what an event MEANS, kept apart from what happened. A row is created automatically the first time a name is seen, so tracking is never blocked by governance; verifying, describing and hiding come after.';

ALTER TABLE `property_definitions` COMMENT = 'Registry of event, person and session properties, with types. Without it every filter has to guess whether "1" is a number.';

ALTER TABLE `event_property_usage` COMMENT = 'Which properties actually arrive on which events, so the filter picker for an event lists only its own properties.';

ALTER TABLE `daily_event_rollups` COMMENT = 'Pre-aggregated daily counts that keep event lists, volume charts and simple trends off the raw table. Recomputed for any day that receives late events.';

ALTER TABLE `feature_flags` COMMENT = 'Feature flags. Evaluation is deterministic, which is what lets SDKs evaluate them locally instead of making a network call per check.';

ALTER TABLE `flag_rules` COMMENT = 'Targeting: who gets the flag, as ordered conditions plus a percentage.';

ALTER TABLE `experiments` COMMENT = 'A/B tests: a hypothesis, a primary metric chosen in advance, and a flag that splits traffic.';

ALTER TABLE `experiment_variants` COMMENT = 'The arms of an experiment.';

ALTER TABLE `experiment_exposures` COMMENT = 'One row per person per experiment, written the first time the flag is evaluated where its effect is visible. Analysis counts only exposed people, so users who never reached the changed screen do not dilute the result.';

ALTER TABLE `cohorts` COMMENT = 'Saved groups of persons: dynamic (a definition, recomputed on a schedule) or static (an uploaded list).';

ALTER TABLE `cohort_memberships` COMMENT = 'Computed membership, by version. A recompute writes version n+1 in full, then flips cohorts.current_version in one update, so nobody ever reads a half-built cohort. Old versions are deleted afterwards.';

ALTER TABLE `funnels` COMMENT = 'Saved funnel definitions. Results are computed from events on demand and never stored here.';

ALTER TABLE `funnel_steps` COMMENT = 'The ordered steps of a funnel.';

ALTER TABLE `saved_reports` COMMENT = 'Saved insights: trends, funnels, retention, paths. A report is a stored query; its result is only ever a cache.';

ALTER TABLE `dashboards` COMMENT = 'Collections of reports laid out on a grid.';

ALTER TABLE `dashboard_tiles` COMMENT = 'Where a report sits on a dashboard. One report can appear on many dashboards and is still edited in one place.';

ALTER TABLE `workspace_members` ADD FOREIGN KEY (`workspace_id`) REFERENCES `workspaces` (`id`);

ALTER TABLE `workspace_members` ADD FOREIGN KEY (`user_id`) REFERENCES `users` (`id`);

ALTER TABLE `projects` ADD FOREIGN KEY (`workspace_id`) REFERENCES `workspaces` (`id`);

ALTER TABLE `api_keys` ADD FOREIGN KEY (`project_id`) REFERENCES `projects` (`id`);

ALTER TABLE `api_keys` ADD FOREIGN KEY (`created_by`) REFERENCES `users` (`id`);

ALTER TABLE `devices` ADD FOREIGN KEY (`project_id`) REFERENCES `projects` (`id`);

ALTER TABLE `devices` ADD FOREIGN KEY (`person_id`) REFERENCES `persons` (`id`);

ALTER TABLE `persons` ADD FOREIGN KEY (`project_id`) REFERENCES `projects` (`id`);

ALTER TABLE `persons` ADD FOREIGN KEY (`merged_into_id`) REFERENCES `persons` (`id`);

ALTER TABLE `identity_aliases` ADD FOREIGN KEY (`project_id`) REFERENCES `projects` (`id`);

ALTER TABLE `identity_aliases` ADD FOREIGN KEY (`person_id`) REFERENCES `persons` (`id`);

ALTER TABLE `person_property_changes` ADD FOREIGN KEY (`person_id`) REFERENCES `persons` (`id`);

ALTER TABLE `sessions` ADD FOREIGN KEY (`project_id`) REFERENCES `projects` (`id`);

ALTER TABLE `sessions` ADD FOREIGN KEY (`device_id`) REFERENCES `devices` (`id`);

ALTER TABLE `events` ADD FOREIGN KEY (`project_id`) REFERENCES `projects` (`id`);

ALTER TABLE `event_definitions` ADD FOREIGN KEY (`project_id`) REFERENCES `projects` (`id`);

ALTER TABLE `event_definitions` ADD FOREIGN KEY (`owner_user_id`) REFERENCES `users` (`id`);

ALTER TABLE `property_definitions` ADD FOREIGN KEY (`project_id`) REFERENCES `projects` (`id`);

ALTER TABLE `event_property_usage` ADD FOREIGN KEY (`event_definition_id`) REFERENCES `event_definitions` (`id`);

ALTER TABLE `event_property_usage` ADD FOREIGN KEY (`property_definition_id`) REFERENCES `property_definitions` (`id`);

ALTER TABLE `daily_event_rollups` ADD FOREIGN KEY (`project_id`) REFERENCES `projects` (`id`);

ALTER TABLE `feature_flags` ADD FOREIGN KEY (`project_id`) REFERENCES `projects` (`id`);

ALTER TABLE `feature_flags` ADD FOREIGN KEY (`created_by`) REFERENCES `users` (`id`);

ALTER TABLE `flag_rules` ADD FOREIGN KEY (`feature_flag_id`) REFERENCES `feature_flags` (`id`);

ALTER TABLE `flag_rules` ADD FOREIGN KEY (`cohort_id`) REFERENCES `cohorts` (`id`);

ALTER TABLE `experiments` ADD FOREIGN KEY (`project_id`) REFERENCES `projects` (`id`);

ALTER TABLE `experiments` ADD FOREIGN KEY (`feature_flag_id`) REFERENCES `feature_flags` (`id`);

ALTER TABLE `experiments` ADD FOREIGN KEY (`primary_funnel_id`) REFERENCES `funnels` (`id`);

ALTER TABLE `experiments` ADD FOREIGN KEY (`winning_variant_id`) REFERENCES `experiment_variants` (`id`);

ALTER TABLE `experiments` ADD FOREIGN KEY (`created_by`) REFERENCES `users` (`id`);

ALTER TABLE `experiment_variants` ADD FOREIGN KEY (`experiment_id`) REFERENCES `experiments` (`id`);

ALTER TABLE `experiment_exposures` ADD FOREIGN KEY (`experiment_id`) REFERENCES `experiments` (`id`);

ALTER TABLE `experiment_exposures` ADD FOREIGN KEY (`variant_id`) REFERENCES `experiment_variants` (`id`);

ALTER TABLE `cohorts` ADD FOREIGN KEY (`project_id`) REFERENCES `projects` (`id`);

ALTER TABLE `cohorts` ADD FOREIGN KEY (`created_by`) REFERENCES `users` (`id`);

ALTER TABLE `cohort_memberships` ADD FOREIGN KEY (`cohort_id`) REFERENCES `cohorts` (`id`);

ALTER TABLE `cohort_memberships` ADD FOREIGN KEY (`person_id`) REFERENCES `persons` (`id`);

ALTER TABLE `funnels` ADD FOREIGN KEY (`project_id`) REFERENCES `projects` (`id`);

ALTER TABLE `funnels` ADD FOREIGN KEY (`created_by`) REFERENCES `users` (`id`);

ALTER TABLE `funnel_steps` ADD FOREIGN KEY (`funnel_id`) REFERENCES `funnels` (`id`);

ALTER TABLE `saved_reports` ADD FOREIGN KEY (`project_id`) REFERENCES `projects` (`id`);

ALTER TABLE `saved_reports` ADD FOREIGN KEY (`funnel_id`) REFERENCES `funnels` (`id`);

ALTER TABLE `saved_reports` ADD FOREIGN KEY (`cohort_id`) REFERENCES `cohorts` (`id`);

ALTER TABLE `saved_reports` ADD FOREIGN KEY (`created_by`) REFERENCES `users` (`id`);

ALTER TABLE `dashboards` ADD FOREIGN KEY (`project_id`) REFERENCES `projects` (`id`);

ALTER TABLE `dashboards` ADD FOREIGN KEY (`created_by`) REFERENCES `users` (`id`);

ALTER TABLE `dashboard_tiles` ADD FOREIGN KEY (`dashboard_id`) REFERENCES `dashboards` (`id`);

ALTER TABLE `dashboard_tiles` ADD FOREIGN KEY (`saved_report_id`) REFERENCES `saved_reports` (`id`);
SQL Server
sql-server.sql SQL Server
CREATE TABLE [workspaces] (
  [id] uuid PRIMARY KEY,
  [name] varchar(200) NOT NULL,
  [slug] varchar(60) UNIQUE NOT NULL,
  [plan] nvarchar(255) NOT NULL CHECK ([plan] IN ('free', 'growth', 'enterprise')),
  [monthly_event_quota] bigint,
  [created_at] timestamptz NOT NULL DEFAULT (now())
)
GO

CREATE TABLE [users] (
  [id] uuid PRIMARY KEY,
  [email] varchar(254) UNIQUE NOT NULL,
  [name] varchar(200) NOT NULL,
  [created_at] timestamptz NOT NULL DEFAULT (now())
)
GO

CREATE TABLE [workspace_members] (
  [workspace_id] uuid NOT NULL,
  [user_id] uuid NOT NULL,
  [role] nvarchar(255) NOT NULL CHECK ([role] IN ('viewer', 'analyst', 'admin', 'owner')),
  [joined_at] timestamptz NOT NULL DEFAULT (now()),
  PRIMARY KEY ([workspace_id], [user_id])
)
GO

CREATE TABLE [projects] (
  [id] uuid PRIMARY KEY,
  [workspace_id] uuid NOT NULL,
  [name] varchar(200) NOT NULL,
  [timezone] varchar(64) NOT NULL,
  [session_timeout_minutes] smallint NOT NULL DEFAULT (30),
  [created_at] timestamptz NOT NULL DEFAULT (now())
)
GO

CREATE TABLE [api_keys] (
  [id] uuid PRIMARY KEY,
  [project_id] uuid NOT NULL,
  [kind] nvarchar(255) NOT NULL CHECK ([kind] IN ('public_ingest', 'secret')),
  [key_prefix] varchar(12) NOT NULL,
  [key_hash] char(64) UNIQUE NOT NULL,
  [label] varchar(100),
  [created_by] uuid,
  [created_at] timestamptz NOT NULL DEFAULT (now()),
  [last_used_at] timestamptz,
  [revoked_at] timestamptz
)
GO

CREATE TABLE [devices] (
  [id] uuid PRIMARY KEY,
  [project_id] uuid NOT NULL,
  [anonymous_id] varchar(100) NOT NULL,
  [person_id] uuid,
  [platform] varchar(30),
  [first_seen_at] timestamptz NOT NULL,
  [last_seen_at] timestamptz NOT NULL,
  [initial_referrer] varchar(500),
  [initial_utm_source] varchar(100),
  [initial_utm_medium] varchar(100),
  [initial_utm_campaign] varchar(200)
)
GO

CREATE TABLE [persons] (
  [id] uuid PRIMARY KEY,
  [project_id] uuid NOT NULL,
  [external_id] varchar(200),
  [properties] jsonb NOT NULL DEFAULT '{}',
  [merged_into_id] uuid,
  [first_seen_at] timestamptz NOT NULL,
  [last_seen_at] timestamptz NOT NULL,
  [deleted_at] timestamptz
)
GO

CREATE TABLE [identity_aliases] (
  [project_id] uuid NOT NULL,
  [distinct_id] varchar(200) NOT NULL,
  [person_id] uuid NOT NULL,
  [source] nvarchar(255) NOT NULL CHECK ([source] IN ('first_seen', 'identify', 'alias_call', 'merge')),
  [created_at] timestamptz NOT NULL DEFAULT (now()),
  [updated_at] timestamptz NOT NULL,
  PRIMARY KEY ([project_id], [distinct_id])
)
GO

CREATE TABLE [person_property_changes] (
  [person_id] uuid NOT NULL,
  [property_key] varchar(200) NOT NULL,
  [set_at] timestamptz NOT NULL,
  [operation] nvarchar(255) NOT NULL CHECK ([operation] IN ('set', 'set_once', 'unset')),
  [value] jsonb,
  [source_event_id] uuid,
  PRIMARY KEY ([person_id], [property_key], [set_at])
)
GO

CREATE TABLE [sessions] (
  [id] uuid PRIMARY KEY,
  [project_id] uuid NOT NULL,
  [device_id] uuid NOT NULL,
  [started_at] timestamptz NOT NULL,
  [ended_at] timestamptz NOT NULL,
  [duration_s] integer NOT NULL,
  [event_count] integer NOT NULL,
  [pageview_count] integer NOT NULL DEFAULT (0),
  [entry_url] varchar(2000),
  [exit_url] varchar(2000),
  [referrer] varchar(500),
  [utm_source] varchar(100),
  [utm_medium] varchar(100),
  [utm_campaign] varchar(200),
  [country] char(2),
  [is_bounce] boolean NOT NULL
)
GO

CREATE TABLE [events] (
  [id] uuid NOT NULL,
  [project_id] uuid NOT NULL,
  [event_name] varchar(200) NOT NULL,
  [distinct_id] varchar(200) NOT NULL,
  [session_id] uuid,
  [occurred_at] timestamptz NOT NULL,
  [sent_at] timestamptz,
  [received_at] timestamptz NOT NULL DEFAULT (now()),
  [properties] jsonb NOT NULL DEFAULT '{}',
  [url] varchar(2000),
  [platform] varchar(30),
  [app_version] varchar(30),
  PRIMARY KEY ([project_id], [occurred_at], [id])
)
GO

CREATE TABLE [event_definitions] (
  [id] uuid PRIMARY KEY,
  [project_id] uuid NOT NULL,
  [name] varchar(200) NOT NULL,
  [display_name] varchar(200),
  [description] text,
  [category] varchar(100),
  [status] nvarchar(255) NOT NULL CHECK ([status] IN ('discovered', 'verified', 'hidden', 'deprecated')) DEFAULT 'discovered',
  [owner_user_id] uuid,
  [first_seen_at] timestamptz NOT NULL,
  [last_seen_at] timestamptz NOT NULL,
  [volume_30d] bigint
)
GO

CREATE TABLE [property_definitions] (
  [id] uuid PRIMARY KEY,
  [project_id] uuid NOT NULL,
  [scope] nvarchar(255) NOT NULL CHECK ([scope] IN ('event', 'person', 'session')),
  [name] varchar(200) NOT NULL,
  [data_type] nvarchar(255) NOT NULL CHECK ([data_type] IN ('string', 'number', 'boolean', 'datetime', 'list')),
  [description] text,
  [is_pii] boolean NOT NULL DEFAULT (false),
  [is_hidden] boolean NOT NULL DEFAULT (false),
  [first_seen_at] timestamptz NOT NULL
)
GO

CREATE TABLE [event_property_usage] (
  [event_definition_id] uuid NOT NULL,
  [property_definition_id] uuid NOT NULL,
  [first_seen_at] timestamptz NOT NULL,
  [last_seen_at] timestamptz NOT NULL,
  PRIMARY KEY ([event_definition_id], [property_definition_id])
)
GO

CREATE TABLE [daily_event_rollups] (
  [project_id] uuid NOT NULL,
  [event_name] varchar(200) NOT NULL,
  [day] date NOT NULL,
  [event_count] bigint NOT NULL,
  [unique_persons_estimate] integer NOT NULL,
  [unique_persons_sketch] bytea NOT NULL,
  [computed_at] timestamptz NOT NULL,
  PRIMARY KEY ([project_id], [event_name], [day])
)
GO

CREATE TABLE [feature_flags] (
  [id] uuid PRIMARY KEY,
  [project_id] uuid NOT NULL,
  [key] varchar(100) NOT NULL,
  [name] varchar(200) NOT NULL,
  [description] text,
  [is_enabled] boolean NOT NULL DEFAULT (false),
  [hash_salt] varchar(40) NOT NULL,
  [created_by] uuid,
  [created_at] timestamptz NOT NULL DEFAULT (now()),
  [archived_at] timestamptz
)
GO

CREATE TABLE [flag_rules] (
  [id] uuid PRIMARY KEY,
  [feature_flag_id] uuid NOT NULL,
  [position] smallint NOT NULL,
  [cohort_id] uuid,
  [conditions] jsonb,
  [rollout_pct] numeric(5,2) NOT NULL DEFAULT (100),
  [variant_key] varchar(50)
)
GO

CREATE TABLE [experiments] (
  [id] uuid PRIMARY KEY,
  [project_id] uuid NOT NULL,
  [feature_flag_id] uuid UNIQUE NOT NULL,
  [name] varchar(200) NOT NULL,
  [hypothesis] text,
  [primary_funnel_id] uuid,
  [status] nvarchar(255) NOT NULL CHECK ([status] IN ('draft', 'running', 'stopped', 'concluded')) DEFAULT 'draft',
  [minimum_sample_size] integer,
  [started_at] timestamptz,
  [ended_at] timestamptz,
  [winning_variant_id] uuid,
  [created_by] uuid
)
GO

CREATE TABLE [experiment_variants] (
  [id] uuid PRIMARY KEY,
  [experiment_id] uuid NOT NULL,
  [key] varchar(50) NOT NULL,
  [weight_pct] numeric(5,2) NOT NULL,
  [is_control] boolean NOT NULL DEFAULT (false)
)
GO

CREATE TABLE [experiment_exposures] (
  [experiment_id] uuid NOT NULL,
  [distinct_id] varchar(200) NOT NULL,
  [variant_id] uuid NOT NULL,
  [first_exposed_at] timestamptz NOT NULL,
  [exposure_count] integer NOT NULL DEFAULT (1),
  PRIMARY KEY ([experiment_id], [distinct_id])
)
GO

CREATE TABLE [cohorts] (
  [id] uuid PRIMARY KEY,
  [project_id] uuid NOT NULL,
  [name] varchar(200) NOT NULL,
  [kind] nvarchar(255) NOT NULL CHECK ([kind] IN ('dynamic', 'static')),
  [definition] jsonb,
  [current_version] integer NOT NULL DEFAULT (0),
  [member_count] integer,
  [last_computed_at] timestamptz,
  [created_by] uuid,
  [created_at] timestamptz NOT NULL DEFAULT (now())
)
GO

CREATE TABLE [cohort_memberships] (
  [cohort_id] uuid NOT NULL,
  [version] integer NOT NULL,
  [person_id] uuid NOT NULL,
  PRIMARY KEY ([cohort_id], [version], [person_id])
)
GO

CREATE TABLE [funnels] (
  [id] uuid PRIMARY KEY,
  [project_id] uuid NOT NULL,
  [name] varchar(200) NOT NULL,
  [step_order] nvarchar(255) NOT NULL CHECK ([step_order] IN ('strict', 'ordered', 'any_order')) DEFAULT 'ordered',
  [conversion_window_seconds] integer NOT NULL DEFAULT (1209600),
  [counting] nvarchar(255) NOT NULL CHECK ([counting] IN ('unique_persons', 'unique_sessions', 'totals')) DEFAULT 'unique_persons',
  [exclusion_event] varchar(200),
  [created_by] uuid,
  [created_at] timestamptz NOT NULL DEFAULT (now())
)
GO

CREATE TABLE [funnel_steps] (
  [funnel_id] uuid NOT NULL,
  [position] smallint NOT NULL,
  [event_name] varchar(200) NOT NULL,
  [filters] jsonb,
  [label] varchar(200),
  PRIMARY KEY ([funnel_id], [position])
)
GO

CREATE TABLE [saved_reports] (
  [id] uuid PRIMARY KEY,
  [project_id] uuid NOT NULL,
  [name] varchar(200) NOT NULL,
  [kind] nvarchar(255) NOT NULL CHECK ([kind] IN ('trend', 'funnel', 'retention', 'paths', 'stickiness', 'lifecycle')),
  [funnel_id] uuid,
  [cohort_id] uuid,
  [query] jsonb NOT NULL,
  [cached_result] jsonb,
  [cached_at] timestamptz,
  [created_by] uuid,
  [created_at] timestamptz NOT NULL DEFAULT (now()),
  [updated_at] timestamptz NOT NULL
)
GO

CREATE TABLE [dashboards] (
  [id] uuid PRIMARY KEY,
  [project_id] uuid NOT NULL,
  [name] varchar(200) NOT NULL,
  [description] text,
  [is_shared] boolean NOT NULL DEFAULT (true),
  [share_token] varchar(64) UNIQUE,
  [created_by] uuid,
  [created_at] timestamptz NOT NULL DEFAULT (now())
)
GO

CREATE TABLE [dashboard_tiles] (
  [id] uuid PRIMARY KEY,
  [dashboard_id] uuid NOT NULL,
  [saved_report_id] uuid,
  [text_body] text,
  [grid_x] smallint NOT NULL,
  [grid_y] smallint NOT NULL,
  [grid_w] smallint NOT NULL,
  [grid_h] smallint NOT NULL
)
GO

CREATE UNIQUE INDEX [projects_index_0] ON [projects] ("workspace_id", "name")
GO

CREATE UNIQUE INDEX [devices_index_1] ON [devices] ("project_id", "anonymous_id")
GO

CREATE UNIQUE INDEX [persons_index_2] ON [persons] ("project_id", "external_id")
GO

CREATE INDEX [identity_aliases_index_3] ON [identity_aliases] ("person_id")
GO

CREATE INDEX [sessions_index_4] ON [sessions] ("project_id", "started_at")
GO

CREATE INDEX [sessions_index_5] ON [sessions] ("device_id", "started_at")
GO

CREATE INDEX [events_index_6] ON [events] ("project_id", "event_name", "occurred_at")
GO

CREATE INDEX [events_index_7] ON [events] ("project_id", "distinct_id", "occurred_at")
GO

CREATE UNIQUE INDEX [event_definitions_index_8] ON [event_definitions] ("project_id", "name")
GO

CREATE UNIQUE INDEX [property_definitions_index_9] ON [property_definitions] ("project_id", "scope", "name")
GO

CREATE UNIQUE INDEX [feature_flags_index_10] ON [feature_flags] ("project_id", "key")
GO

CREATE UNIQUE INDEX [flag_rules_index_11] ON [flag_rules] ("feature_flag_id", "position")
GO

CREATE UNIQUE INDEX [experiment_variants_index_12] ON [experiment_variants] ("experiment_id", "key")
GO

CREATE INDEX [cohort_memberships_index_13] ON [cohort_memberships] ("person_id")
GO

EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'The billing and access boundary: one company using the product.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'workspaces';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Billing limit. Ingestion keeps accepting past it and flags the overage; dropping data is never the answer',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'workspaces',
@level2type = N'Column', @level2name = 'monthly_event_quota';
GO

EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'People who log in to the analytics product. Not to be confused with persons, the end users being measured.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'users';
GO

EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'Who can see and change what in a workspace.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'workspace_members';
GO

EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'One tracked product and environment, e.g. web app production. Everything below is scoped to a project, and staging is a separate project so test traffic never pollutes real numbers.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'projects';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Where a "day" starts for rollups and charts. Changing it means recomputing rollups',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'projects',
@level2type = N'Column', @level2name = 'timezone';
GO

EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'Ingestion keys are public (they ship inside apps and web pages) and can only write events; secret keys read data and stay on servers. Two kinds, never one key that does both.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'api_keys';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'First characters, shown in the UI so a key can be recognised',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'api_keys',
@level2type = N'Column', @level2name = 'key_prefix';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'SHA-256 of the key. A secret key is shown once at creation and never stored in clear',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'api_keys',
@level2type = N'Column', @level2name = 'key_hash';
GO

EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'Browsers and app installs, known before anyone logs in. First-touch attribution lives here because it happened before identity did.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'devices';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Generated by the SDK on first launch and kept in local storage or the keychain',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'devices',
@level2type = N'Column', @level2name = 'anonymous_id';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'CACHE of the alias resolution, set once the device is identified',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'devices',
@level2type = N'Column', @level2name = 'person_id';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'e.g. web, ios, android',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'devices',
@level2type = N'Column', @level2name = 'platform';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'First-touch attribution: captured once, never overwritten',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'devices',
@level2type = N'Column', @level2name = 'initial_referrer';
GO

EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'The end users being measured, identified or not. One person can have many devices and many distinct ids.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'persons';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Your own user id, sent with identify(). Null for persons only ever seen anonymously',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'persons',
@level2type = N'Column', @level2name = 'external_id';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'CACHE: the current value of every person property, folded from person_property_changes',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'persons',
@level2type = N'Column', @level2name = 'properties';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Set when this person was merged into another; lookups follow it',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'persons',
@level2type = N'Column', @level2name = 'merged_into_id';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Erasure request. Their events are deleted by a background job; the row stays as a tombstone so the id is never reused',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'persons',
@level2type = N'Column', @level2name = 'deleted_at';
GO

EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'The identity graph. Events keep the distinct_id they were sent with and are never rewritten; queries resolve distinct_id to person here. When an anonymous visitor logs in, or two persons merge, only these rows change, and the whole history moves with them.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'identity_aliases';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Any id an event has arrived with: an anonymous id or an external id',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'identity_aliases',
@level2type = N'Column', @level2name = 'distinct_id';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Changes when a merge repoints the alias at the surviving person',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'identity_aliases',
@level2type = N'Column', @level2name = 'updated_at';
GO

EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'Every change to a person property, in order. persons.properties holds the latest values; this table answers "what plan were they on when they did that?"',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'person_property_changes';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'set overwrites; set_once applies only if no value exists yet; unset removes it',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'person_property_changes',
@level2type = N'Column', @level2name = 'operation';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Null for unset',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'person_property_changes',
@level2type = N'Column', @level2name = 'value';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'The event that carried the change, if any. Not a foreign key: events is partitioned',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'person_property_changes',
@level2type = N'Column', @level2name = 'source_event_id';
GO

EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'Derived by the sessionizer: a run of events from one device with no gap longer than the project session timeout. Rebuildable from events, so the rules can change.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'sessions';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'A single pageview and nothing else',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'sessions',
@level2type = N'Column', @level2name = 'is_bounce';
GO

EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'Raw events: append-only, never updated.
PARTITION BY RANGE (occurred_at), monthly, with a BRIN index on occurred_at in each partition. Retention is DROP PARTITION.
At real volume this table moves to a columnar store; the shape stays the same.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'events';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Generated by the SDK, so a retried batch is recognised as a duplicate',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'events',
@level2type = N'Column', @level2name = 'id';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Exactly as sent. Matched to event_definitions by name, never by foreign key',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'events',
@level2type = N'Column', @level2name = 'event_name';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'As sent. Resolved to a person through identity_aliases at query time',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'events',
@level2type = N'Column', @level2name = 'distinct_id';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Stamped by the sessionizer after ingest',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'events',
@level2type = N'Column', @level2name = 'session_id';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Client time corrected for clock skew (received_at minus sent_at). The partition key',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'events',
@level2type = N'Column', @level2name = 'occurred_at';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Client clock when the batch left the device',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'events',
@level2type = N'Column', @level2name = 'sent_at';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Everything else the SDK or caller attached. Promote hot keys to columns rather than indexing the whole document',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'events',
@level2type = N'Column', @level2name = 'properties';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Promoted from properties: filtered on constantly',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'events',
@level2type = N'Column', @level2name = 'url';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Promoted from properties',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'events',
@level2type = N'Column', @level2name = 'platform';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Promoted from properties',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'events',
@level2type = N'Column', @level2name = 'app_version';
GO

EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'The registry: what an event MEANS, kept apart from what happened. A row is created automatically the first time a name is seen, so tracking is never blocked by governance; verifying, describing and hiding come after.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'event_definitions';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'The raw event name as it appears in events',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'event_definitions',
@level2type = N'Column', @level2name = 'name';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'What the UI shows. Renaming here renames it everywhere without touching a single event',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'event_definitions',
@level2type = N'Column', @level2name = 'display_name';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'CACHE from daily_event_rollups',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'event_definitions',
@level2type = N'Column', @level2name = 'volume_30d';
GO

EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'Registry of event, person and session properties, with types. Without it every filter has to guess whether "1" is a number.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'property_definitions';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Inferred from the first values seen, then confirmed by a person. Decides which filters the UI offers',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'property_definitions',
@level2type = N'Column', @level2name = 'data_type';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Masked in the UI and left out of exports',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'property_definitions',
@level2type = N'Column', @level2name = 'is_pii';
GO

EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'Which properties actually arrive on which events, so the filter picker for an event lists only its own properties.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'event_property_usage';
GO

EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'Pre-aggregated daily counts that keep event lists, volume charts and simple trends off the raw table. Recomputed for any day that receives late events.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'daily_event_rollups';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'In the project timezone',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'daily_event_rollups',
@level2type = N'Column', @level2name = 'day';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'HyperLogLog sketch. Distinct counts cannot be added across days but sketches can be merged: weekly uniques merge seven of them',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'daily_event_rollups',
@level2type = N'Column', @level2name = 'unique_persons_sketch';
GO

EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'Feature flags. Evaluation is deterministic, which is what lets SDKs evaluate them locally instead of making a network call per check.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'feature_flags';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Referenced in code, e.g. new-checkout. Never reused after archiving',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'feature_flags',
@level2type = N'Column', @level2name = 'key';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Kill switch: off serves the default to everyone, whatever the rules say',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'feature_flags',
@level2type = N'Column', @level2name = 'is_enabled';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Bucket = hash(key + salt + distinct_id) mod 100, so a user lands in the same bucket on every call with no assignment row stored',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'feature_flags',
@level2type = N'Column', @level2name = 'hash_salt';
GO

EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'Targeting: who gets the flag, as ordered conditions plus a percentage.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'flag_rules';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Evaluated in order; the first matching rule decides',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'flag_rules',
@level2type = N'Column', @level2name = 'position';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Match people in this cohort',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'flag_rules',
@level2type = N'Column', @level2name = 'cohort_id';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Property filters, e.g. [{"key": "plan", "op": "eq", "value": "pro"}]',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'flag_rules',
@level2type = N'Column', @level2name = 'conditions';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Share of matching people who get the flag',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'flag_rules',
@level2type = N'Column', @level2name = 'rollout_pct';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Multivariate flags: serve this variant to everyone the rule matches',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'flag_rules',
@level2type = N'Column', @level2name = 'variant_key';
GO

EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'A/B tests: a hypothesis, a primary metric chosen in advance, and a flag that splits traffic.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'experiments';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'An experiment runs through its own flag; the variants are its buckets',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'experiments',
@level2type = N'Column', @level2name = 'feature_flag_id';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'The success metric, fixed before launch rather than picked after the results are in',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'experiments',
@level2type = N'Column', @level2name = 'primary_funnel_id';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'From the power calculation. Calling a winner before it is reached is how false positives ship',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'experiments',
@level2type = N'Column', @level2name = 'minimum_sample_size';
GO

EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'The arms of an experiment.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'experiment_variants';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'e.g. control, test-a. Matches the flag variant key',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'experiment_variants',
@level2type = N'Column', @level2name = 'key';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'The weights of one experiment sum to 100',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'experiment_variants',
@level2type = N'Column', @level2name = 'weight_pct';
GO

EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'One row per person per experiment, written the first time the flag is evaluated where its effect is visible. Analysis counts only exposed people, so users who never reached the changed screen do not dilute the result.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'experiment_exposures';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'When the user first saw a variant, not when they were bucketed',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'experiment_exposures',
@level2type = N'Column', @level2name = 'first_exposed_at';
GO

EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'Saved groups of persons: dynamic (a definition, recomputed on a schedule) or static (an uploaded list).',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'cohorts';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Dynamic cohorts: the filter tree, e.g. did signed_up in the last 30 days AND plan = pro',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'cohorts',
@level2type = N'Column', @level2name = 'definition';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'The membership version readers use',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'cohorts',
@level2type = N'Column', @level2name = 'current_version';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'CACHE for the current version',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'cohorts',
@level2type = N'Column', @level2name = 'member_count';
GO

EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'Computed membership, by version. A recompute writes version n+1 in full, then flips cohorts.current_version in one update, so nobody ever reads a half-built cohort. Old versions are deleted afterwards.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'cohort_memberships';
GO

EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'Saved funnel definitions. Results are computed from events on demand and never stored here.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'funnels';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'From the first step to the last; 1209600 is 14 days',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'funnels',
@level2type = N'Column', @level2name = 'conversion_window_seconds';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'An event that disqualifies a conversion if it happens between steps',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'funnels',
@level2type = N'Column', @level2name = 'exclusion_event';
GO

EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'The ordered steps of a funnel.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'funnel_steps';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'The raw name, so changing a display name never breaks a funnel',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'funnel_steps',
@level2type = N'Column', @level2name = 'event_name';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Property filters on this step only',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'funnel_steps',
@level2type = N'Column', @level2name = 'filters';
GO

EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'Saved insights: trends, funnels, retention, paths. A report is a stored query; its result is only ever a cache.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'saved_reports';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'For funnel reports',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'saved_reports',
@level2type = N'Column', @level2name = 'funnel_id';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Optional filter or breakdown by cohort',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'saved_reports',
@level2type = N'Column', @level2name = 'cohort_id';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'The full query: events, filters, breakdowns and a relative date range (e.g. last 30 days) so it stays current',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'saved_reports',
@level2type = N'Column', @level2name = 'query';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'CACHE of the last run. Dashboards render it and refresh in the background',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'saved_reports',
@level2type = N'Column', @level2name = 'cached_result';
GO

EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'Collections of reports laid out on a grid.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'dashboards';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Visible to the whole workspace, not just its creator',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'dashboards',
@level2type = N'Column', @level2name = 'is_shared';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Set when shared by public link; rotate it to revoke the link',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'dashboards',
@level2type = N'Column', @level2name = 'share_token';
GO

EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'Where a report sits on a dashboard. One report can appear on many dashboards and is still edited in one place.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'dashboard_tiles';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Null for a text tile',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'dashboard_tiles',
@level2type = N'Column', @level2name = 'saved_report_id';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Markdown, for text tiles',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'dashboard_tiles',
@level2type = N'Column', @level2name = 'text_body';
GO

ALTER TABLE [workspace_members] ADD FOREIGN KEY ([workspace_id]) REFERENCES [workspaces] ([id])
GO

ALTER TABLE [workspace_members] ADD FOREIGN KEY ([user_id]) REFERENCES [users] ([id])
GO

ALTER TABLE [projects] ADD FOREIGN KEY ([workspace_id]) REFERENCES [workspaces] ([id])
GO

ALTER TABLE [api_keys] ADD FOREIGN KEY ([project_id]) REFERENCES [projects] ([id])
GO

ALTER TABLE [api_keys] ADD FOREIGN KEY ([created_by]) REFERENCES [users] ([id])
GO

ALTER TABLE [devices] ADD FOREIGN KEY ([project_id]) REFERENCES [projects] ([id])
GO

ALTER TABLE [devices] ADD FOREIGN KEY ([person_id]) REFERENCES [persons] ([id])
GO

ALTER TABLE [persons] ADD FOREIGN KEY ([project_id]) REFERENCES [projects] ([id])
GO

ALTER TABLE [persons] ADD FOREIGN KEY ([merged_into_id]) REFERENCES [persons] ([id])
GO

ALTER TABLE [identity_aliases] ADD FOREIGN KEY ([project_id]) REFERENCES [projects] ([id])
GO

ALTER TABLE [identity_aliases] ADD FOREIGN KEY ([person_id]) REFERENCES [persons] ([id])
GO

ALTER TABLE [person_property_changes] ADD FOREIGN KEY ([person_id]) REFERENCES [persons] ([id])
GO

ALTER TABLE [sessions] ADD FOREIGN KEY ([project_id]) REFERENCES [projects] ([id])
GO

ALTER TABLE [sessions] ADD FOREIGN KEY ([device_id]) REFERENCES [devices] ([id])
GO

ALTER TABLE [events] ADD FOREIGN KEY ([project_id]) REFERENCES [projects] ([id])
GO

ALTER TABLE [event_definitions] ADD FOREIGN KEY ([project_id]) REFERENCES [projects] ([id])
GO

ALTER TABLE [event_definitions] ADD FOREIGN KEY ([owner_user_id]) REFERENCES [users] ([id])
GO

ALTER TABLE [property_definitions] ADD FOREIGN KEY ([project_id]) REFERENCES [projects] ([id])
GO

ALTER TABLE [event_property_usage] ADD FOREIGN KEY ([event_definition_id]) REFERENCES [event_definitions] ([id])
GO

ALTER TABLE [event_property_usage] ADD FOREIGN KEY ([property_definition_id]) REFERENCES [property_definitions] ([id])
GO

ALTER TABLE [daily_event_rollups] ADD FOREIGN KEY ([project_id]) REFERENCES [projects] ([id])
GO

ALTER TABLE [feature_flags] ADD FOREIGN KEY ([project_id]) REFERENCES [projects] ([id])
GO

ALTER TABLE [feature_flags] ADD FOREIGN KEY ([created_by]) REFERENCES [users] ([id])
GO

ALTER TABLE [flag_rules] ADD FOREIGN KEY ([feature_flag_id]) REFERENCES [feature_flags] ([id])
GO

ALTER TABLE [flag_rules] ADD FOREIGN KEY ([cohort_id]) REFERENCES [cohorts] ([id])
GO

ALTER TABLE [experiments] ADD FOREIGN KEY ([project_id]) REFERENCES [projects] ([id])
GO

ALTER TABLE [experiments] ADD FOREIGN KEY ([feature_flag_id]) REFERENCES [feature_flags] ([id])
GO

ALTER TABLE [experiments] ADD FOREIGN KEY ([primary_funnel_id]) REFERENCES [funnels] ([id])
GO

ALTER TABLE [experiments] ADD FOREIGN KEY ([winning_variant_id]) REFERENCES [experiment_variants] ([id])
GO

ALTER TABLE [experiments] ADD FOREIGN KEY ([created_by]) REFERENCES [users] ([id])
GO

ALTER TABLE [experiment_variants] ADD FOREIGN KEY ([experiment_id]) REFERENCES [experiments] ([id])
GO

ALTER TABLE [experiment_exposures] ADD FOREIGN KEY ([experiment_id]) REFERENCES [experiments] ([id])
GO

ALTER TABLE [experiment_exposures] ADD FOREIGN KEY ([variant_id]) REFERENCES [experiment_variants] ([id])
GO

ALTER TABLE [cohorts] ADD FOREIGN KEY ([project_id]) REFERENCES [projects] ([id])
GO

ALTER TABLE [cohorts] ADD FOREIGN KEY ([created_by]) REFERENCES [users] ([id])
GO

ALTER TABLE [cohort_memberships] ADD FOREIGN KEY ([cohort_id]) REFERENCES [cohorts] ([id])
GO

ALTER TABLE [cohort_memberships] ADD FOREIGN KEY ([person_id]) REFERENCES [persons] ([id])
GO

ALTER TABLE [funnels] ADD FOREIGN KEY ([project_id]) REFERENCES [projects] ([id])
GO

ALTER TABLE [funnels] ADD FOREIGN KEY ([created_by]) REFERENCES [users] ([id])
GO

ALTER TABLE [funnel_steps] ADD FOREIGN KEY ([funnel_id]) REFERENCES [funnels] ([id])
GO

ALTER TABLE [saved_reports] ADD FOREIGN KEY ([project_id]) REFERENCES [projects] ([id])
GO

ALTER TABLE [saved_reports] ADD FOREIGN KEY ([funnel_id]) REFERENCES [funnels] ([id])
GO

ALTER TABLE [saved_reports] ADD FOREIGN KEY ([cohort_id]) REFERENCES [cohorts] ([id])
GO

ALTER TABLE [saved_reports] ADD FOREIGN KEY ([created_by]) REFERENCES [users] ([id])
GO

ALTER TABLE [dashboards] ADD FOREIGN KEY ([project_id]) REFERENCES [projects] ([id])
GO

ALTER TABLE [dashboards] ADD FOREIGN KEY ([created_by]) REFERENCES [users] ([id])
GO

ALTER TABLE [dashboard_tiles] ADD FOREIGN KEY ([dashboard_id]) REFERENCES [dashboards] ([id])
GO

ALTER TABLE [dashboard_tiles] ADD FOREIGN KEY ([saved_report_id]) REFERENCES [saved_reports] ([id])
GO

How to use this template

  1. Open the ER diagram to see the tables and how they relate.
  2. Copy it into your workspace. You get your own editable copy, in DBML.
  3. Export it as PostgreSQL, MySQL, or SQL Server DDL, or as Prisma, Drizzle, SQLAlchemy, TypeScript, Zod or C# models.

The copy opens in DB Planner’s ER diagram tool, with the schema as text in the DBML editor beside it. Have a database already? Turn its SQL into an ER diagram instead.

Frequently asked questions

Which table is at the centre of the Product Analytics database schema?
projects. It is referenced by 15 other tables: api_keys, cohorts, daily_event_rollups, dashboards, devices and 10 more.
How is api_keys related to projects?
api_keys.project_id references projects.id, a many to one relationship. All 48 relationships in the schema are listed on this page.
Which table in the Product Analytics database schema has the most columns?
sessions, with 16 columns, followed by events (12) and experiments (12). The schema has 214 columns across 27 tables.
Can I export it to PostgreSQL or MySQL?
Yes. Every DB Planner template exports as DBML, as PostgreSQL, MySQL, or SQL Server DDL, and as C# models.
Is this template free?
Yes. You can open it in the browser without an account, and copy it into your own workspace with a free DB Planner account.
Can I change it after copying it?
Yes. A copy is yours: you can rename tables, add columns, and export it. Changes the author makes later do not affect your copy.