Database

PostgreSQL is the system of record. Redis (optional in MVP) is used for queueing and caching.

This document describes the MVP schema. Indexes, constraints, and migrations are owned by OrchestFlowAI.Infrastructure.


1. Conventions

  • Primary keys are uuid (v7 preferred for time-ordered indexing).
  • All tables include tenant_id, created_at, updated_at where applicable.
  • Soft delete via is_deleted + deleted_at on user-facing entities.
  • JSON columns are jsonb.
  • Timestamps are timestamptz (UTC).
  • Naming: snake_case tables and columns.

2. Tables (MVP)

tenants

ColumnTypeNotes
iduuid PK
nametext
created_attimestamptzdefault now()

users

ColumnTypeNotes
iduuid PK
tenant_iduuid FK→ tenants.id
emailcitextunique within tenant
display_nametext
roletextadmin | editor | approver | viewer
created_attimestamptz

workflows

ColumnTypeNotes
iduuid PK
tenant_iduuid FK
nametext
descriptiontext
created_byuuid FK→ users.id
created_attimestamptz
updated_attimestamptz
is_deletedbooleandefault false
deleted_attimestamptz

Index: (tenant_id, is_deleted).

workflow_versions

ColumnTypeNotes
iduuid PK
workflow_iduuid FK→ workflows.id
version_numberint
definition_jsonjsonbcanonical workflow definition
is_activebooleanonly one active per workflow
created_byuuid FK
created_attimestamptz

Constraints: unique (workflow_id, version_number). Partial unique on is_active=true.

workflow_executions

ColumnTypeNotes
iduuid PK
tenant_iduuid FK
workflow_iduuid FK
workflow_version_iduuid FK
statustext`Queued
started_attimestamptz
completed_attimestamptz
triggered_byuuid FK→ users.id (nullable for system triggers)
input_jsonjsonb
output_jsonjsonb
error_messagetext
correlation_idtext

Indexes: (tenant_id, status, started_at desc), (workflow_id, started_at desc).

node_executions

ColumnTypeNotes
iduuid PK
workflow_execution_iduuid FK
node_idtextid from workflow JSON
node_typetextdescriptor type
statustext`Pending
started_attimestamptz
completed_attimestamptz
input_jsonjsonb
output_jsonjsonb
error_messagetext
retry_countintdefault 0
stepintlogical clock for ordering

Index: (workflow_execution_id, step).

approval_requests

ColumnTypeNotes
iduuid PK
tenant_iduuid FK
workflow_execution_iduuid FK
node_execution_iduuid FK
statustext`Pending
payload_jsonjsonbwhat the approver sees
assignees_jsonjsonbarray of user/role refs
requested_attimestamptz
responded_attimestamptz
requested_byuuid FK
responded_byuuid FK
decisiontext`approved
commenttext
sla_minutesint

Indexes: (tenant_id, status, requested_at desc).

documents

ColumnTypeNotes
iduuid PK
tenant_iduuid FK
owner_iduuid FK→ users.id
filenametext
mime_typetext
size_bytesbigint
storage_uritexte.g. tenant/<id>/uploads/<uuid>.pdf
sha256text
created_attimestamptz

gmail_credentials

Stores OAuth2 credentials for Gmail integrations, scoped per tenant.

ColumnTypeNotes
iduuid PK
tenant_iduuid FK→ tenants.id; indexed
namevarchar(200)Friendly reference name; unique per tenant
client_idvarchar(500)Google OAuth2 client ID
client_secretvarchar(500)Google OAuth2 client secret
refresh_tokentextLong-lived refresh token with Gmail read scope
emailvarchar(320)Gmail address (populated after OAuth callback)
created_attimestamptz
updated_attimestamptz

Unique index: (tenant_id, name).

platform_settings

Stores per-tenant runtime-configurable key-value pairs (e.g. LLM API keys, default model). Hot-reloaded without restart via OpenAIApiKeyHolder.

ColumnTypeNotes
iduuid PK
tenant_iduuid FK→ tenants.id
keyvarchar(200)Setting key (e.g. llm.openai.apiKey)
valuetextSetting value
updated_attimestamptzLast updated

Unique index: (tenant_id, key).

secrets

Stores per-tenant encrypted named values for the Secret Vault.

ColumnTypeNotes
iduuid PK
tenant_iduuid FK→ tenants.id; tenant scope
namevarchar(200)Friendly name (e.g. openai-key)
encrypted_valuetextAES-256-CBC encrypted; never returned to clients
created_attimestamptz
updated_attimestamptz

Unique index: (tenant_id, name).

node_presets

Tenant-scoped saved config snapshots for node types.

ColumnTypeNotes
iduuid PK
tenant_iduuid FK→ tenants.id
namevarchar(200)Display name
node_typetextNode type key (e.g. integrations.http)
config_jsonjsonbSaved configuration values
created_byuuid FK→ users.id
created_attimestamptz
updated_attimestamptz

Index: (tenant_id, node_type).

execution_queue

Durable queue for workflow execution messages (used when Redis is unavailable).

ColumnTypeNotes
iduuid PK
tenant_iduuid FK
execution_iduuid FK→ workflow_executions.id
message_typetextrun | resume | cancel
payload_jsonjsonbMessage-specific data
visible_aftertimestamptzFor delayed/retry scheduling
locked_untiltimestamptzWorker lease lock expiry
attempt_countintdefault 0
created_attimestamptz

Index: (visible_after, locked_until) for worker polling.

tenant_invites

Pending user invitations scoped per tenant.

ColumnTypeNotes
iduuid PK
tenant_iduuid FK→ tenants.id
emailcitextInvitee email address
roletextRole to assign on accept
tokentextUnique invite token (32-char hex GUID)
invited_byuuid FK→ users.id
expires_attimestamptz24h from creation
accepted_attimestamptzNull until accepted
created_attimestamptz

Unique index: (tenant_id, token).

ai_usage_logs

ColumnTypeNotes
iduuid PK
tenant_iduuid FK
workflow_execution_iduuid FK
node_execution_iduuid FK
providertext
modeltext
prompt_versiontext
prompt_tokensint
completion_tokensint
total_tokensint
estimated_costnumeric(12,6)
created_attimestamptz

Indexes: (tenant_id, created_at desc), (workflow_execution_id).

audit_logs

ColumnTypeNotes
iduuid PK
tenant_iduuid FK
actor_iduuid FKnullable for system actors
actiontextworkflow.created, execution.started, …
target_typetext
target_iduuid
payload_jsonjsonb
created_attimestamptz

ai_chat_sessions

Stores interactive AI chat sessions (workflow designer, form generator).

ColumnTypeDescription
iduuid PKSession id
tenant_iduuidTenant
user_iduuidUser who started the session
surfacevarcharworkflow-assist, form-generator, node-assist
context_iduuid?Optional: workflow id, form id, etc.
created_attimestamp
updated_attimestampUpdated on each message added

ai_chat_messages

Individual turns within an AiChatSession.

ColumnTypeDescription
iduuid PKMessage id
session_iduuid FK→ ai_chat_sessions
rolevarcharuser, assistant, tool
content_texttextMessage content
tool_namevarchar?Tool name when Role=tool
tool_input_jsontext?Tool call arguments
tool_output_jsontext?Tool result
prompt_tokensintInput tokens (assistant messages only)
completion_tokensintOutput tokens (assistant messages only)
total_tokensintSum
modelvarchar?Model used
providervarchar?Provider id
created_attimestamp

3. Optional Tables (post-MVP)

  • tenant_settings — per-tenant config (default model, providers, retention).
  • prompts — prompt template storage with versions (currently in code).
  • knowledge_bases, kb_documents, kb_chunks, kb_embeddings — for RAG.
  • integrations + integration_credentials — connector credentials.
  • agents — agent configurations.

4. Migrations

  • Migrations live in OrchestFlowAI.Infrastructure/Migrations/.
  • EF Core migrations are used. The Infrastructure project is both the migrations project and its own startup project for dotnet ef commands.
  • Migrations are forward-only in production; backfills are explicit data scripts.
  • Auto-migration runs on API startup with 5 retries (fatal if all retries fail — app will not start with missing tables).
  • To add a migration:
    dotnet ef migrations add <Name> \
      --project packages/OrchestFlowAI.Infrastructure \
      --startup-project packages/OrchestFlowAI.Infrastructure
    
  • To apply manually (dev):
    dotnet ef database update \
      --project packages/OrchestFlowAI.Infrastructure \
      --startup-project packages/OrchestFlowAI.Infrastructure \
      --connection "Host=localhost;Database=OrchestFlowAI;Username=OrchestFlowAI;Password=<pwd>"
    

5. Indexing Strategy

Primary access patterns to optimize for in MVP:

  • "Show executions for workflow X" → (workflow_id, started_at desc)
  • "Show pending approvals for tenant T" → (tenant_id, status, requested_at)
  • "Show timeline for execution E" → (workflow_execution_id, step)
  • "Recent AI usage for tenant T" → (tenant_id, created_at desc)

Add indexes only after access patterns are confirmed; avoid speculative ones.


6. Data Retention

MVP defaults:

  • Document blobs retained until the workflow execution is hard-deleted.
  • Execution rows retained indefinitely.
  • AI usage logs retained 12 months (configurable).
  • Audit logs retained indefinitely.

Post-MVP: per-tenant retention policy + automated purge job.

PlatformSettings

Stores per-tenant runtime-configurable key-value pairs (e.g. LLM API keys, default model).

ColumnTypeNotes
IdUUIDPK
TenantIdUUIDFK → Tenants
KeyVARCHAR(200)Setting key (e.g. llm.openai.apiKey)
ValueTEXTSetting value
UpdatedAtTIMESTAMPTZLast updated

Unique index: (TenantId, Key).

Secrets

Stores per-tenant encrypted named values for the Secret Vault.

ColumnTypeNotes
IdUUIDPK
TenantIdUUIDTenant scope
NameVARCHAR(200)Friendly name (e.g. "openai-key")
EncryptedValueTEXTAES-256-CBC encrypted; never returned to clients
CreatedAtTIMESTAMPTZCreated timestamp
UpdatedAtTIMESTAMPTZLast updated

Unique index: (TenantId, Name).