DSM — Tutorial
This is the tutorial part of the DSM — Data Storage Model guide. See also Short info and samples.
Before you begin
Section titled “Before you begin”Choose a piece of information that must persist and one invalid row the system should reject. Basic table concepts help; SQL expertise is unnecessary for the walkthrough.
Understand the model
Section titled “Understand the model”Separate stored facts from business meaning
Section titled “Separate stored facts from business meaning”A storage model describes how data is represented for durable use. A reservation row might contain an identifier, a flight identifier and a seat count. Types describe the values a column can hold; nullability describes whether a value may be absent. A primary key identifies a row, while a foreign key expresses a relationship whose referenced row must exist.
A database constraint can reject a class of invalid states. For example, a positive seat-count check rejects zero or negative requests. This is different from a rule about the total confirmed seats across many rows. That broader rule may require transaction-level coordination as well as a domain requirement. Avoid assuming every business invariant becomes a simple column check.
Design for change and access
Section titled “Design for change and access”Ask how data will be read before adding indexes. A flight search by origin, destination and departure time supplies a reason to consider an appropriate index. The trade-off includes storage and write work. Explain the intended access pattern and measure performance in the target database before claiming a particular improvement.
A schema change also changes what existing data must satisfy. Making an optional contact field required may reject old rows unless they are backfilled. Review the migration as a sequence: establish valid values, check the population, then enforce the stronger constraint. A visual diff is useful for spotting the changed contract, but preservation of production data needs its own migration plan and evidence.
Visual walkthrough
Section titled “Visual walkthrough”Three rows meet two storage rules. A small table appears; a valid row is admitted; zero-seat and missing-flight rows are rejected with labelled reasons.
Pause and predict: Can these two row checks alone prevent several valid rows from overbooking a flight?
This is the text storyboard for a proposed short illustrated film. The written walkthrough and exercises are available now; a published movie will be added after its scenes, captions and model references have been reviewed.
Pull From a Live Database
Section titled “Pull From a Live Database”The fastest path to an accurate DSM is the database you already have. ctxbrew db pull reads a live Postgres catalog (information_schema / pg_catalog) and emits a DSM model:
# Credentials come from the DATABASE_URL environment variable ONLY —# never a CLI flag, never printed, never loggedDATABASE_URL=postgres://user:pass@host:5432/app ctxbrew db pull --dialect postgresNo live database? --from-json runs the identical pipeline on a captured catalog JSON document. Starting from code instead? ctxbrew init --from-code derives schema hypotheses from TypeScript source, marked unverified until you promote them.
Defining Tables Manually
Section titled “Defining Tables Manually”Author the file
Section titled “Author the file”There is no model command — schemas are authored as .dsm.json files under .contextbrew/dsm/, on the Studio canvas, or in the Studio’s DSM DSL text editor (same model, a plain-text form; whatever you author, the serialized file remains .dsm.json). Create .contextbrew/dsm/books.dsm.json:
{ "kind": "dsm-file", "schemaVersion": "0.1.0", "enums": [], "tables": [ { "kind": "table", "name": "books", "aggregate": "Book", "columns": [ { "kind": "column", "name": "id", "dataType": "UUID", "primaryKey": true, "defaultValue": "gen_random_uuid()" }, { "kind": "column", "name": "title", "dataType": "VARCHAR(255)", "nullable": false }, { "kind": "column", "name": "isbn", "dataType": "VARCHAR(13)", "unique": true, "nullable": false }, { "kind": "column", "name": "price", "dataType": "DECIMAL(10,2)", "nullable": false }, { "kind": "column", "name": "status", "dataType": "VARCHAR(20)", "nullable": false, "defaultValue": "DRAFT" }, { "kind": "column", "name": "created_at", "dataType": "TIMESTAMP", "nullable": false, "defaultValue": "now()" } ], "constraints": [ { "kind": "constraint", "name": "valid_isbn_length", "type": "check", "expression": "length(isbn) = 10 OR length(isbn) = 13" } ], "indexes": [ { "kind": "index", "name": "idx_books_title", "columns": ["title"] } ] }, { "kind": "table", "name": "order_items", "columns": [ { "kind": "column", "name": "id", "dataType": "UUID", "primaryKey": true }, { "kind": "column", "name": "order_id", "dataType": "UUID", "nullable": false }, { "kind": "column", "name": "book_id", "dataType": "UUID", "nullable": false }, { "kind": "column", "name": "quantity", "dataType": "INTEGER", "nullable": false } ], "constraints": [ { "kind": "constraint", "name": "fk_order_items_orders", "type": "foreign-key", "columns": ["order_id"], "references": "orders(id)" }, { "kind": "constraint", "name": "fk_order_items_books", "type": "foreign-key", "columns": ["book_id"], "references": "books(id)" } ], "indexes": [] } ], "migrations": []}ctxbrew dsm validate .contextbrew/dsm/books.dsm.jsonPrefer schema-as-code? DBML (dbdiagram), Prisma schema, and drizzle-kit TS files import into the same IR — see Import / export below.
Using Context Studio
Section titled “Using Context Studio”The DSM visual ERD displays:
- Tables as rectangular nodes with column lists
- Foreign key relationships as directed edges
- Constraint indicators (unique, check, not-null icons)
- Index badges on indexed columns
Data Type Mappings
Section titled “Data Type Mappings”ContextBrew supports 20+ data type mappings from DDD property types to database column types:
| DDD Type | PostgreSQL Type | TypeScript Type |
|---|---|---|
| UUID | uuid |
string |
| String | varchar(n) |
string |
| Integer | integer |
number |
| Decimal | numeric(p,s) |
number |
| Boolean | boolean |
boolean |
| DateTime | timestamptz |
Date |
| JSON | jsonb |
T (generic) |
| Enum | varchar + CHECK |
enum type |
CLI Reference
Section titled “CLI Reference”ctxbrew dsm validate <file> # Parse the file; exit 1 on any errorctxbrew dsm stats <file> # Collection sizes (tables, indexes…)ctxbrew dsm export <file> # Canonical DSL (--format json|yaml) or --to dbml-outctxbrew dsm import <file> # Canonicalization passctxbrew dsm diff <before> <after> # Semantic diff (report only)ctxbrew db pull # Live Postgres catalog → DSM (DATABASE_URL)ctxbrew schema dsm # Print the normative JSON SchemaImport / export
Section titled “Import / export”DSM is the widest interop surface. Inbound: SQL DDL (Postgres + SQLite subset), DBML, Prisma schema, drizzle-kit TS, MySQL DDL, and dbt schema.yml/properties.yml (models become tables; the generic unique/not_null/relationships tests become constraints; sources become data sources) — plus the live Postgres catalog via ctxbrew db pull. Outbound: canonical SQL DDL, DBML (dbdiagram), Drizzle ORM table definitions, and a data dictionary. Details: Import & Export.
