Provisioning Flow
Detailed walkthrough of the 'Organization Created' event lifecycle.
The Organization.Created event triggers a complex chain of provisioning steps to prepare the tenant's environment. This logic lives in features/pub-sub/subscribers/organization-created.ts.
Step 1: Schema creation
The subscriber uses basePrisma to execute a raw SQL command:
CREATE SCHEMA IF NOT EXISTS "{slug}".
We use PostgreSQL schemas to provide logical isolation between tenants while sharing the same physical database instance.
Step 2: Connection mapping
A new OrgConnection record is added to the global basePrisma database. This record stores the connStr (connection string) that the CRUD Engine will use to resolve the TenantPrisma client.
Step 3: Migration
The subscriber calls migrateNewOrg(slug, tx). This runs the initial DDL migrations against the newly created schema. This includes creating the core metadata tables (Entity, Field, View, etc.) that are required for the CRM to function.
Step 4: Metadata seeding
seedOrg(orgId) is called to populate the global database with basic organizational metadata.
Step 5: Tenant data seeding
Finally, seedData(tx, slug) is called via withOrgPrisma. This adds:
- Default
Entities(Contact, Account, Case). - Standard
Fieldsfor those entities. - Initial lookup values and system configuration.
Idempotency and safety
- Schema Check: Uses
IF NOT EXISTSto avoid crashes if a partially-created org is retried. - Slug Validation: The subscriber enforces a strict regex (
/^[a-z][a-z0-9_]*$/) on the slug to prevent SQL injection in schema names. - Transactionality: Steps within the subscriber are grouped logically into transactions where possible, though DDL operations often auto-commit in PostgreSQL.