# xDBML -- reference for AI assistants > xDBML is a text markup language to describe the semantics of structured and semi-structured data across relational, document, columnar, graph, view, and exchange formats. xDBML extends DBML into a true metadata and semantic data modeling language with richer support for validation, semantics, cardinality, annotations, and AI-friendly metadata, while deliberately staying readable and Git-friendly. When a user asks you to design, draft, edit, or render a schema for use with an xDBML tool, write xDBML -- not plain DBML -- and reach for the xDBML constructs below where they fit. Plain DBML still parses (it is a subset), but it misses the structures and metadata that make xDBML worth using. Follow this reference exactly. Do not borrow syntax from SQL DDL, other DBML dialects, Prisma, Spark or JSON Schema: where a habit from one of them and a rule here disagree, the rule here applies. Where xDBML accepts several spellings, write the one shown here. Each example below is checked against the xDBML parser. A block marked `// Wrong` shows a form assistants often write: its comment names the error a validator reports, or says that the form is accepted silently and means something other than intended. The `// Right` block after it is the form to write. ## Ground rules - The first line of every document is `xdbml: 0.7`. Without it, a parser reads the file as plain DBML and rejects every xDBML construct. - Comments are `//` to the end of the line, or `/* ... */`. `#` and `--` are errors. - Keywords match any casing, and names are case-sensitive. Write construct keywords capitalized (`Entity`, `Table`, `View`, `Ref`), settings and type keywords in lowercase. - A name is a bare identifier, `[A-Za-z_][A-Za-z0-9_]*`, or it is double-quoted: `"order details"`. A field may take the name of any keyword, without quotes: `note`, `type`, `date`, `records`. `Note:` starts a note; `indexes {`, `constraints {`, `checks {`, `records {` and `definitions {` start blocks, and so do `records (` and `records [`. - Entities, Views, Edges, Types, Enums and EntityPartials share one namespace: two of them never have the same name. - Declare every entity, Enum and Type that the document names. - Use `Entity` for a generic entity. Target-native synonyms also work and carry intent: `Table` (relational), `Collection` (document/MongoDB), `Record` (Avro). Namespacing uses `Container`, `Schema`, `Database`, `Keyspace`, `Namespace`, `Dataset` or `Bucket`. - Write `EntityPartial` and `EntityGroup`. `TablePartial` and `TableGroup`, the DBML keywords, are aliases and parse the same. - Prefer xDBML extensions over flat DBML where they fit: nested objects and arrays, polymorphism (`oneOf` / `union`), reusable `Type`s, precise min/max cardinality, `Edge`s, `View`s, supertype groups for generalization, and AI-readiness metadata (`synonyms`, `business_term`, `tags`, `granularity`). ## Quoting | Delimiter | Holds | Example | |---|---|---| | `'...'` | every string: notes, defaults, patterns, cardinalities, colors, constraint names | `note: 'Billing address'` | | `'''...'''` | text on several lines, and text that holds a `'`, such as most SQL | `source_query: '''SELECT id FROM orders WHERE status = 'open' AND total > 0'''` | | `"..."` | a name, or a type, that is not a bare identifier | `"order details"`, `"timestamp with time zone"` | | `` `...` `` | an expression the database evaluates | `` default: `now()` `` | - A `'` inside `'...'` ends the string. Write it `\'` (`'The customer\'s number'`), or use `'''...'''`. English notes often hold one. - Double quotes never delimit a string: `Note: "text"` is an error. - A type written in several words is one double-quoted name: `"double precision"`, `"timestamp with time zone"`, `"int unsigned"`. A one-word synonym works as well: `timestamptz`, `float8`. - In a qualified name or a path, quote each name on its own: `"sales"."Work Order"."Work Order ID"`, `("Work Order ID", "Part ID") [pk]`. A dot inside quotes is part of the name: `"sales.Work Order"` is one entity named `sales.Work Order`, not an entity of `sales`. - Colors are strings: `color: '#3498DB'`. ## Separators Settings and bodies separate their items differently: - Inside `[ ]`, a comma separates every two settings, also when each setting sits on its own line. A line break never replaces the comma. - Inside `{ }`, each item -- a field, an enum value, a constraint, an index, a group member -- takes its own line, with no comma or semicolon after it. A parser accepts and ignores them between the items of a body, but tools write newlines. ```xdbml Entity customers { customer_id int [pk] email varchar [unique, not null] } Entity vehicles { vehicle_id int [pk] customer_id int [not null] } Ref customer_vehicles: vehicles.customer_id > customers.customer_id [ source: '0..*', target: '1..1', source_role: 'owned vehicle', target_role: 'owner' ] ``` Other lists keep their own rules. In `indexes { }` a comma between two entries is an error, and a composite index is written `(a, b)`. A `records { }` row puts a comma between its values, one row per line; an empty field, `1, , 'x'`, reads as null. An entity takes one records block, in its body or at the top level as `records users (id, name) { ... }`, and `[example]` after the column list marks rows that illustrate the data. `union [T1, T2]` and `map [K, V]` need their commas. ## What goes where A construct takes its settings in brackets after its name, before its body: `materialized: true` inside a View body is a syntax error. A field with a body -- `object { }`, `oneOf { }`, `json { }` -- takes its settings after the closing brace. In a body, the `name: value` form is only for `Note:`, for `targets:` in a Project, for `source_query:` in a View, and for the settings of a `Dep` block. | Construct | Brackets after the name | Body holds | Declared | |---|---|---|---| | `Project` | none | `targets:`, `Note:` | top level, at most once | | `Container`, `Schema`, `Database`, ... | `type`, `target`, `color`, `note`, custom | entities, Views, Edges, Enums, `Note:`, sticky notes (`xdbml: 0.7`) | top level | | `Entity`, `Table`, `Collection`, `Record` | `note`, `color` (the header color), `grain`, `tags`, `synonyms`, `business_term`, custom | fields, `~partial`, `Note:`, `constraints { }`, `indexes { }`, `records { }`, `definitions { }` | top level or in a Container | | `View` | `materialized`, `refresh_schedule`, `refresh_on`, `source_database`, `storage_options`, `note`, `color`, `grain`, `synonyms`, `business_term` | `source_query:` once, fields, `Note:`, and nothing else | top level or in a Container | | `Edge` | `source`, `target` (entities), `source_cardinality`, `target_cardinality`, `undirected`, roles and verbs, `note` | fields, `~partial`, `Note:`, `constraints { }`, `indexes { }` | top level or in a Container | | `Enum` | none | values, each with an optional `[note: '...']` | top level or in a Container | | `Type` | `note`, `tags`, `synonyms`, `business_term` | fields, `~partial` | top level | | `EntityPartial` | `note`, `color` | fields, `Note:`, `constraints { }`, `indexes { }` | top level | | `Ref` | relationship settings | -- | top level, never in a Container | | `SupertypeGroup` | `supertype` (required), `completeness`, `exclusivity`, `strategy`, `merge`, `discriminator`, `note` | subtype names, each with an optional `[strategy: ...]` | top level | | `EntityGroup` | `color`, `note` | entity names | top level | | `DiagramView` | `note`, custom | `Note:`, and categories: `Entities`, `Views`, `Containers`, `EntityGroups`, `SupertypeGroups`, `Notes`, each with names or `*` | top level, never in a Container | | `Note name` (a sticky note) | `color` (`#rgb`, `#rrggbb` or `none`), custom | one string, Markdown | top level, or in a Container with `xdbml: 0.7` | | `Dep` (data lineage) | `note`, `color` (`#rgb` or `#rrggbb`), `source_database`, custom | dependencies `a -> b`, one per line, each with optional brackets holding `transformation`, `note`, `color`; `source_query:` once; other `key: value` lines; `Note:` | top level, never in a Container | A note goes either in the brackets as `note: '...'` or in the body as `Note: '...'`. ## Fields A field line is `name type [settings]`. Types. In a physical model, use the target's own type names; any type name is kept as written, and a name of several words is written in double quotes: `varchar(255)`, `decimal(14,2)`, `smallint`, `serial`, `bytea`, `timestamptz` or `"timestamp with time zone"` for PostgreSQL, `number(10)`, `varchar2(255)` and `"timestamp with local time zone"` for Oracle, `objectId`, `string`, `int32`, `int64`, `Decimal128`, `Date` for MongoDB. A logical model uses generic names: `int`, `bigint`, `varchar`, `decimal(p,s)`, `boolean`, `date`, `timestamp`. A field typed by an Enum or a Type names it (`status service_status`, `address Address`); an Enum declared in a Container is named with its qualifier (`status core.job_status`). A type name close to a declared Type or Enum (`Adress` next to `Type Address`) draws a `possible-type-typo` warning. A Type never takes the name of a built-in type, in any letter case: a field typed `money` or `Money` gets the built-in `money`, so `Type Money` is an error; name it `MonetaryAmount`. Collection and structured types use xDBML's own syntax, never the Spark, SQL or TypeScript forms: | Write | Never | |---|---| | `array [string]` | `array` | | `object { street string }` | `struct` | | `map [string, int]` | `map` | | `set [varchar]` | `set` | | a declared `Enum` | `enum('a', 'b')` as a type | `text[]` is PostgreSQL's own name for an array type. It passes through as a type name, and the model sees no element type in it: an array in the model is `array [T]`. Settings. These are all the field settings: - flags: `pk`, `unique`, `not null`, `null`, `increment` - values: `default`, `note`, `ref`, `check` - validation: `pattern`, `format`, `minLength`, `maxLength`, `minimum`, `maximum`, `exclusiveMinimum`, `exclusiveMaximum`, `multipleOf`, `minItems`, `maxItems`, `uniqueItems`, `minProperties`, `maxProperties` - AI-readiness: `tags`, `synonyms`, `business_term`, `granularity` - beside an inline `ref:` only: `foreign_master` - custom properties: any name that starts with `x_`, or a double-quoted name that starts with `x-`: `"x-hackolade-id": 'orders-12'` A word from another language is not a setting. A parser keeps it as an unknown property and nothing reads it. Write `increment`, not `auto_increment`, `autoincrement` or `identity`; `note`, not `comment` or `description`; `pk`, not `primary_key`. Leave out `nullable`: a field accepts null unless it is marked `not null`. An index is an entry in `indexes { }`, not an `[index]` flag, and a relationship is a `ref:` or a `Ref`, never `fk` or `references`. Values: - `default:` takes a string in single quotes (`'US'`), a number, `true`, `false`, `null`, or a backtick expression for anything the database computes: `` `now()` ``, `` `CURRENT_TIMESTAMP` ``, `` `gen_random_uuid()` ``. `default: 'now()'` is the text `now()`, not a call. - `tags:` and `synonyms:` are lists, also with a single item: `tags: ['kpi']`. - `granularity:` takes one bare word: `year`, `quarter`, `month`, `week`, `day`, `hour`, `minute`, `second`, `millisecond`, `microsecond`, `nanosecond`. - `business_term:` is a string: `'Gross Order Value'`, or a glossary URL. - `check:` is an expression in single quotes, or in backticks when it holds a quote: `` check: `status IN ('open', 'closed')` ``. - A primary key field is never null, and still carries `not null`. `null` on it is an error. ## Keys, checks and indexes Put a key on one field without a name inline (`[pk]`, `[unique]`). Put every named key, every key on several fields, and every check that involves several fields in the entity's `constraints` block, one per line, fields listed in key order. A check on one field goes on the field as `check:`. Declare each key once: a key written inline is not repeated in `constraints`. Never mark several fields `[pk]` for a composite key; several `[unique]` fields are separate keys, not one. Checks go in single quotes, or backticks when the expression holds a quote. ```xdbml Table pitstops { raceid int [not null] driverid int [not null] stop int [not null, check: 'stop >= 1'] lap int [not null] constraints { (raceid, driverid, stop) [pk, name: 'pk_pitstops'] (raceid, driverid, lap) [unique, name: 'uk_pitstops_lap'] 'lap >= stop' [name: 'chk_pitstops_lap'] } } ``` A `constraints` block appears at most once, in the body of an Entity, an EntityPartial or an Edge. A View has none. A key names fields declared in the same body. A key may name a nested field (`profile.email`) but never cross an array. In a document store, keys follow the same syntax. `indexes { }` lists physical access paths, one entry per line: a field, a composite `(a, b)`, or an expression `` (`lower(email)`) ``, each with optional settings `name`, `type` (`btree`, `hash`, ...), `unique` and `note`. A key belongs in `constraints`, not in `indexes`. ## Relationships A relationship between attributes names the foreign key of the child and the key of the parent it references: `Ref : . > . []` or inline on the foreign key field: `customer_id int [ref: > customers.customer_id, not null]`. Operators: `>` many-to-one, `<` one-to-many, `-` one-to-one, `<>` many-to-many. The referenced side depends on the operator: the right side of `>`, the left side of `<`, and either side of `-`. `a > b` and `b < a` declare the same relationship. The referenced side names the parent's primary key or one of its unique keys: all the fields of that key, and no other field. When the field on the referenced side is the child's own foreign key, the operator points the wrong way. Declare the referenced field `unique` when it is not the key. Cardinality: `source` describes the left endpoint and `target` the right one, each as a quoted `'min..max'` string: `'0..1'`, `'1..1'`, `'0..*'`, `'1..*'`, or `'N..M'`. With `>`, the source maximum is `*` and the target maximum is `1`; with `<`, the reverse. Never `'many'`, `'*'` or `'1'`. Without these settings, the cardinality follows from the operator, and a foreign key without `not null` makes the parent end optional: `customer_id int` under `>` gives the target `'0..1'`. State cardinality with `source` and `target`, not with DBML's `?` marks (`>?`, `?<`), which a parser reads but tools do not write. All relationship settings go in the brackets of the `Ref`. An inline `ref:` takes none but `foreign_master`: other settings beside it belong to the field, not to the relationship. | Setting | Values | |---|---| | `source`, `target` | `'min..max'` | | `delete`, `update` | `cascade`, `restrict`, `set null`, `set default`, `no action` | | `source_role`, `target_role`, `source_verb`, `target_verb` | text in single quotes | | `constraint_type` | `identifying`, `non_identifying` | | `foreign_master`, `inactive` | flags | | `undirected` | `true`, on a relationship between entities | | `color` | `'#rrggbb'` | | `note` | text in single quotes | `Ref fk_orders_customer: ...` names the foreign key constraint. `Ref` declarations sit at the top level, never inside a Container; an endpoint in a Container is qualified with it: `Ref: sales.orders.customer_id > core.customers.id`. The endpoints of a `Ref` are entities (`Entity`, `Table`, `Collection`, `Record`) and their fields, never a View or an Edge. A composite foreign key lists its fields in parentheses on both sides, and the parent declares that key in `constraints`: ```xdbml Table merchants { merchant_id int [not null] country_code char(2) [not null] constraints { (merchant_id, country_code) [pk] } } Table merchant_periods { period_id int [pk] merchant_id int [not null] country_code char(2) [not null] } Ref: merchant_periods.(merchant_id, country_code) > merchants.(merchant_id, country_code) ``` A path into a nested field continues with dots: `orders.shipping.country > countries.iso_code`. A path that crosses an array marks the crossing with `.[*]`: `orders.line_items.[*].sku > products.sku`. A relationship whose referenced fields are not a key is the error `ref-target-not-key`. The rule does not apply when the referenced entity declares no key, as in a conceptual or early logical model; to `<>` and `foreign_master` relationships; to relationships between entities; or when either entity sits in a Container whose target is not relational (document, graph, key-value, serialization format). A relationship can record denormalization rather than a key reference. Add `foreign_master` when the child attribute holds a copy of the parent's value, as document models often do; nothing is generated from it, it takes one attribute on each side, and a child attribute has at most one master: ```xdbml Collection customers { customer_id objectId [pk] name string address object { city string } } Collection orders { order_id objectId [pk] customer_id objectId [ref: > customers.customer_id] customerName string [ref: > customers.name, foreign_master] shipTo object { city string } } Ref: orders.shipTo.city > customers.address.city [foreign_master] ``` Relationships carry documentation for conceptual and logical modeling. A role names what the entity at one end plays. A verb reads the relationship in one direction: `source_verb` from the left entity toward the right one, `target_verb` from the right entity toward the left one, so this relationship reads "an order is bought by a customer" and "a customer places orders". `constraint_type` records whether the child's foreign key is part of its primary key. None of it reaches a generator: ```xdbml Entity customers { customer_id int [pk] } Entity orders { order_id int [pk] customer_id int [not null] } Ref places: orders.customer_id > customers.customer_id [ source_role: 'shopping cart', source_verb: 'is bought by', target_role: 'buyer', target_verb: 'places', constraint_type: non_identifying ] ``` An endpoint may also name an entity and stop there, for a relationship drawn before either entity has attributes. Such a relationship states no cardinality until one is written, takes its reading direction from the operator alone (`-` meaning linked with no direction stated, `<>` not allowed), and accepts `undirected: true` for one that reads the same way both ways: ```xdbml Entity Customer { } Entity Order { } Ref: Customer > Order [source_verb: 'places'] ``` ## Views A View's settings (`materialized`, `refresh_schedule`, `refresh_on`, `source_database`, `storage_options`) go in the brackets after the View name, before the body. The body holds the source query, once, as `source_query:`, the fields, and an optional `Note:`, and nothing else: no `constraints`, `indexes`, `checks` or `records` block. Write the source query in triple quotes, which hold the quotes of SQL literals. A `source_query` in the brackets is not the view's source query and draws a warning. A key on one field of a View is marked `[pk]`. A View declares no key on several fields, since its body holds no `constraints` block. A View is never the endpoint of a `Ref`. ```xdbml View top_customers [materialized: true, refresh_schedule: 'daily'] { source_query: '''SELECT id, SUM(total) AS ltv FROM orders WHERE status = 'paid' GROUP BY id''' id int [pk] ltv decimal(15,2) } View center_monthly_revenue [materialized: true, refresh_schedule: 'monthly'] { source_query: ''' SELECT center_id, date_trunc('month', issued_on) AS month, SUM(total) AS revenue FROM invoices GROUP BY center_id, date_trunc('month', issued_on) ''' center_id int [not null] month date [not null, granularity: month] revenue decimal(14,2) [tags: ['kpi']] Note: 'One row per service center and month' } ``` ## Edges An Edge is a relationship with its own properties -- use it, not a `Ref`, when the relationship itself carries attributes. `source:` and `target:` name the entities it connects, and its cardinality goes in `source_cardinality:` and `target_cardinality:`. In a `Ref`, `source:` and `target:` are cardinalities; in an Edge, they are entities. ```xdbml Entity Person { person_id int [pk] } Edge KNOWS [source: Person, target: Person, source_cardinality: '0..*', target_cardinality: '0..*'] { since date [not null] } ``` ## Supertype groups Generalization (supertype and subtypes) is a `SupertypeGroup`: one supertype, its subtypes along one axis, and whether every supertype instance is one of them (`completeness: total | partial`) and whether it can be several (`exclusivity: disjoint | overlapping`); leave either out when it is not known. Each subtype declares only its own attributes; never repeat the supertype's, that is an error. Use one group per axis: a supertype may anchor several groups, an entity is a subtype in one group only, and a subtype may be the supertype of another group. The group name is required and names the axis: ```xdbml Entity Party { party_id int [pk] name varchar } Entity Person { birth_date date } Entity Organization { legal_form varchar } SupertypeGroup legal_nature [supertype: Party, completeness: total, exclusivity: disjoint, strategy: roll_up, merge: flat, discriminator: nature] { Person Organization [strategy: roll_down] } ``` `strategy` (`preserved_hierarchy`, `roll_up`, `roll_down`, also per subtype), `merge` (`flat`, `nested`) and `discriminator` record how a physical model is meant to be derived; they add nothing to the logical model, and `discriminator` is not allowed on an overlapping group. A path through a subtype names only the subtype's own attributes, so to point a relationship at a subtype, name the subtype as an entity: `Ref: assignments.employee_id > Employee`, not `Employee.party_id`. ## Diagram views A diagram view is a named subset of the model's diagram, a subject area: it lists what to show, and declares nothing. Each category lists names, one per line, or `*` for every element of its kind: `Entities` (entities, whatever keyword declares them), `Views` (database views), `Containers`, `EntityGroups`, `SupertypeGroups` and `Notes` (sticky notes). `Tables` and `TableGroups`, the DBML names, are aliases of `Entities` and `EntityGroups`; write one name per category. Write a name in a Container with its Container, as in `sales.orders`. Relationships and Edges are never listed: one appears in a diagram view when both of its ends are there. ```xdbml Schema sales { Table orders { id int [pk] } Table order_lines { id int [pk] } Table returns { id int [pk] } } Schema billing { Table invoices { id int [pk] } } Schema crm { Table customers { id int [pk] } Table leads { id int [pk] } } DiagramView order_flow { Note: 'From the order to its invoice and payment' Containers { sales billing } Entities { sales.orders sales.order_lines crm.customers } } ``` A listed Container brings all of its entities, unless `Entities` names some of them: then it brings only those. Here `sales` brings `orders` and `order_lines` and leaves `returns` out, `billing` brings every entity, and `crm`, not listed, contributes `customers` alone. `Views` narrows the database views of a listed Container the same way, separately, and `Notes` its sticky notes. A listed EntityGroup or supertype group brings all of its members, whichever Container holds them. Each category appears once, and a diagram view has a unique name. ## Sticky notes A top-level `Note` with a name is a sticky note: an annotation drawn on the diagram, in the color of its `color` setting (`#rgb`, `#rrggbb`, or `none` for the text alone), or light yellow by default. Its text is Markdown: headings, `**bold**`, `*italic*`, `` `code` ``, links and lists render on the canvas. With `xdbml: 0.7`, a named `Note` in a Container body is a sticky note attached to it: it is drawn inside the Container's frame and moves with it, and the rest of the document names it with its Container, as in `sales.order_states`. The unnamed `Note:` of a Container body stays the Container's own note, and a top-level `Note:` without a name is the note of the project. ```xdbml xdbml: 0.7 Container sales [type: schema] { Note: 'Order management' Table orders { id int [pk] status varchar } Note order_states [color: #FBCFE8] { ''' An order moves from **placed** to **shipped** to **delivered**. - a cancelled order keeps its lines - a return points at one order line ''' } } Note release_plan [color: none, author: 'data-team'] { 'Fields marked deprecated leave the model in release 4.2.' } DiagramView ordering { Entities { sales.orders } Notes { sales.order_states } } ``` A sticky note takes no position and no size: the diagram places it and sizes it to its text. Settings other than `color` are custom properties. ## Data lineage A `Dep` records that data is computed from other data: an entity, a View or a field is produced from another by a job, a dbt model or a query that runs outside the model. The arrow points from upstream to downstream, `a -> b`, and `b <- a` states the same dependency. An end names an entity, a View, or a field of either, with its Container where it sits in one, and a nested field with its path, as in a `Ref`: `events.payload.customer.id`, `orders.line_items.[*].sku`. A dependency states no cardinality and constrains no value: it never replaces a `Ref`, which records how rows connect. ```xdbml Table raw_customers { id int [pk] first_name varchar last_name varchar signed_up date } Table stg_customers [dep: <- raw_customers] { customer_id int [pk, dep: <- raw_customers.id] full_name varchar } Table daily_signups { day date [pk, dep: <- raw_customers.signed_up] customers int } Dep: raw_customers -> daily_signups.customers [note: 'COUNT(*) per day'] Dep build_full_name [owner: 'analytics'] { raw_customers.first_name, raw_customers.last_name -> stg_customers.full_name Note: 'Joins the first and the last name.' } ``` The short form, `Dep name: a -> b [settings]`, states one dependency; its name is optional. A line may name several upstream ends, separated by commas, and one downstream end: `a.x, a.y -> b.z`. A block gathers dependencies into one downstream entity or View, the entity itself or its fields; a `key: value` line or a `Note:` in its body is a setting of the Dep, and brackets after a dependency hold settings of that dependency alone. Inline, `dep: <- source` or `dep: -> target` on an entity or a View names an entity or a View, and on a field names a field, qualified with its entity. A field never depends on itself, and a dependency is stated once in the document, once for each kind of transformation when it has one. A `Dep` stands at the top level; `use *` brings the Deps of a file, and a selective import brings none. The note is prose: the statement that computes the data goes in `source_query`, and the kind of each dependency in `transformation` (next section). ## Source-to-target mapping A `Dep` specifies how a target is loaded when its dependencies carry a `transformation`. Write one line per target field, with every source field that feeds it, then one line for each field that joins, looks up, filters or groups the rows, ending at the target entity itself. Put the statement that loads the target in `source_query:`, in the body of the block, in triple quotes, and its language in `source_database` (or `dialect`), in lowercase: `snowflake`, `oracle`, `ansi_sql`. No parser reads the statement: write it as the pipeline runs it. | `transformation` | The source fields | Ends at | |---|---|---| | `identity` | are copied unchanged | a field; between two entities, a copy of every row and field | | `calculation` | compute the value within the row | a field | | `aggregation` | compute the value over several rows | a field | | `join` | sit in a join condition | the entity, or a field | | `lookup` | sit in a join that finds at most one row | the entity, or a field | | `filter` | sit in a condition the rows meet | the entity, or a field | | `group_by` | group the rows | the entity, or a field | | `conditional` | are tested in a `CASE WHEN` of the value | a field | A line without `transformation` states lineage and no kind. A `CAST` written in the statement makes a `calculation`. One field may play several roles: state the same pair once for each kind. Give the target its `grain`, what one row represents. ```xdbml Container legacy [type: database, target: Oracle] { Table MBR { MBR_ID number [pk] FIRST_NM varchar2(50) LAST_NM varchar2(50) STATUS char(1) CNTRY_CD char(2) } Table COUNTRY { CODE char(2) [pk] NAME varchar2(80) } } Container dw [type: schema, target: Snowflake] { Table dim_member [grain: 'One row per member'] { member_key int [pk, increment] member_id int [unique] full_name varchar country_name varchar } } Dep load_dim_member [source_database: snowflake] { legacy.MBR.MBR_ID -> dw.dim_member.member_id [transformation: identity] legacy.MBR.FIRST_NM, legacy.MBR.LAST_NM -> dw.dim_member.full_name [transformation: calculation] legacy.COUNTRY.NAME -> dw.dim_member.country_name [transformation: identity] legacy.MBR.CNTRY_CD, legacy.COUNTRY.CODE -> dw.dim_member [transformation: lookup] legacy.MBR.STATUS -> dw.dim_member [transformation: filter] source_query: ''' SELECT m.MBR_ID AS member_id, TRIM(m.FIRST_NM) || ' ' || TRIM(m.LAST_NM) AS full_name, c.NAME AS country_name FROM legacy.MBR m LEFT JOIN legacy.COUNTRY c ON c.CODE = m.CNTRY_CD WHERE m.STATUS <> 'X' ''' } ``` ## Metrics A metric, such as total revenue, is a field of a View that is not materialized: a semantic layer computes it at query time. The View's `source_query` holds the SQL, and a `Dep` with `transformation: aggregation` states which fields each metric aggregates. ```xdbml Table fct_orders [grain: 'One row per order'] { order_id int [pk] revenue decimal(12, 2) } View sales_metrics [source_database: ansi_sql] { source_query: ''' SELECT SUM(revenue) AS total_revenue, SUM(revenue) / COUNT(DISTINCT order_id) AS average_order_value FROM fct_orders ''' total_revenue decimal(18, 2) [synonyms: ['revenue', 'total sales']] average_order_value decimal(12, 2) } Dep sales_metrics_lineage { fct_orders.revenue -> sales_metrics.total_revenue [transformation: aggregation] fct_orders.revenue, fct_orders.order_id -> sales_metrics.average_order_value [transformation: aggregation] } ``` ## Nesting and polymorphism ```xdbml Collection orders { _id objectId [pk] shipping object { street string [not null] country string } [not null] line_items array [ line_item object { sku string [not null] qty int32 [minimum: 1] price Decimal128 } ] payment oneOf { card object { last4 string } bank object { iban string } } [discriminator: kind] score union [int, decimal, null] flags map [string, bool] labels array [string] [maxItems: 10] } ``` The settings of a field with a body come after its closing brace. `array [T]` holds one element type; a comma list of scalars, `array [int, string]`, is shorthand for `array [union [int, string]]`, and a mix of object shapes is a `oneOf`. `json` stores an opaque JSON value; `json { ... }` describes its shape. ## Internal definitions A shape reused inside one entity goes in the entity's `definitions { }` block, as JSON Schema keeps it under `$defs`. Each entry is written like a `Type` without the keyword: a name and a body of fields, or a name, a type and settings. The fields of the entity, and the other entries, name it like any type. ```xdbml Project crm { targets: 'JSON Schema' } Entity customers { id string [not null] billing Address [not null] contacts array [Contact] definitions { Address { street string [not null] country CountryCode } CountryCode string [pattern: '^[A-Z]{2}$'] Contact { kind string [not null] address Address } } } ``` An internal definition is visible only inside its entity, so two entities may each declare an `Address` of a different shape. A shape reused across entities is a `Type` at the top level. JSON Schema, Avro, Protobuf and document targets such as MongoDB accept the block. Relational targets, Cassandra, ScyllaDB, Neo4j, Memgraph, Neptune and JanusGraph take none: there, a reused shape is a `Type`. An entity holds at most one `definitions` block, and a TablePartial, an Edge or a View holds none. ## Partials An `EntityPartial` declares a set of fields once, for several bodies. A `~name` line places them where it is written, in the order the EntityPartial declares them: in an Entity or an Edge, among the fields of an `object { }` or a `json { }`, or in the body of a `Type`. A field the body declares itself overrides an injected field of the same name; among partials, the last one injected applies. At the top level of an Entity or an Edge, a partial also brings the keys and checks of its `constraints { }`, the entries of its `indexes { }`, and its `color` and its note where the entity declares none. In a nested body it brings its fields only. The body of an EntityPartial holds no `~name` line, at any depth. `~` never names a `Type`: a Type is the type of a field (`billing Address`), and the field holds its shape as a nested value. ```xdbml EntityPartial audit { created_at timestamp [not null] created_by varchar } Entity invoices { invoice_id int [pk] ~audit total decimal(12,2) [not null] } Entity shipments { shipment_id int [pk] delivery object { ~audit carrier varchar } } ``` ## Projects and containers ```xdbml Project fleet { targets: [PostgreSQL, MongoDB] Note: 'Vehicles in PostgreSQL, telemetry in MongoDB' } Schema core [target: PostgreSQL] { Enum fuel_type { petrol diesel electric } Table vehicles { vehicle_id int [pk] fuel core.fuel_type [not null] } } Database telemetry [target: MongoDB] { Collection readings { _id objectId [pk] vehicle_id int [not null] taken_at Date [not null, granularity: second] } } Ref: telemetry.readings.vehicle_id > core.vehicles.vehicle_id ``` With one target in the Project, every Container inherits it. With several, every Container declares `target:`, one of the Project's targets. A Container holds entities, Views, Edges, Enums and notes; Types, Refs, groups and partials stay at the top level. ## AI-readiness and custom metadata ```xdbml Entity customers [x_owner: 'data-team@acme.com', x_retention_days: 2555] { id int [pk] mrr decimal [synonyms: ['monthly revenue'], business_term: 'MRR', tags: ['kpi'], granularity: month] } ``` Write settings in the brackets of the element they describe. A `Metadata` block sets a note, a color and custom properties on an element declared elsewhere, in the same file or, where it helps most, in an imported file you do not edit. It goes at the top level and names the kind of element and the element: ```xdbml Table customers { id int [pk] email varchar } Metadata Table customers { note: 'Customers of record' x_owner: 'data-team@acme.com' } Metadata Column customers.email { x_classification: 'confidential' } ``` The kinds are `Table`, `Column`, `TableGroup` and `Note`, and with `xdbml: 0.7` also `Entity`, `Field`, `EntityGroup`, `Container`, `View` and `DiagramView`. A block takes `note`, the element's `color` (on an entity, a View, a group, a sticky note or a Container), and custom properties. It does not take `synonyms`, `business_term`, `tags`, `granularity`, or a field setting such as `pk`: those read as custom properties there, with a warning. ## Common mistakes A missing comma between settings on separate lines. ```xdbml Entity customers { customer_id int [pk] } Entity vehicles { vehicle_id int [pk] customer_id int [not null] } // Wrong (parse-error): a line break does not separate settings Ref customer_vehicles: vehicles.customer_id > customers.customer_id [ source: '0..*' target: '1..1' ] // Right Ref customer_vehicles: vehicles.customer_id > customers.customer_id [ source: '0..*', target: '1..1' ] ``` A dependency written with a relationship operator. A `Dep` takes an arrow, `->` or `<-`, with no space inside. ```xdbml Table raw_orders { id int [pk] } Table stg_orders { order_id int [pk] } // Wrong (parse-error): '>' is the operator of a relationship Dep: raw_orders > stg_orders // Right Dep: raw_orders -> stg_orders ``` An inline `dep` on a field that names an entity. On a field, `dep` names a field; a dependency between entities goes in the entity's brackets. ```xdbml Table raw_orders { id int [pk] } // Wrong (dep-wrong-kind): a field depends on a field Table stg_orders { order_id int [pk, dep: <- raw_orders] } // Right Table stg_orders [dep: <- raw_orders] { order_id int [pk, dep: <- raw_orders.id] } ``` A query or a formula in a note, or in a setting of another name. A note is prose that no tool reads as code, and `rule:`, `expression:` or `type:` on a dependency is a custom property that no tool reads either. The kind goes in `transformation`, and the statement in `source_query:`, in the body of the block. ```xdbml Table raw_customers { id int [pk] first_name varchar last_name varchar } Table stg_customers { id int [pk] full_name varchar } // Wrong (accepted silently): the note and the rule are not read as code Dep load_stg_customers { raw_customers.first_name, raw_customers.last_name -> stg_customers.full_name [rule: 'first_name || last_name'] Note: 'SELECT id, first_name || last_name AS full_name FROM raw_customers' } // Right Dep load_stg_customers [source_database: ansi_sql] { raw_customers.first_name, raw_customers.last_name -> stg_customers.full_name [transformation: calculation] source_query: '''SELECT id, first_name || ' ' || last_name AS full_name FROM raw_customers''' } ``` A `Mapping` block, or a `Metric` declaration. Neither exists: a `Dep` is the mapping, and a metric is a field of a View. ```xdbml Table orders { id int [pk] amount decimal(12, 2) } View sales_metrics { source_query: 'SELECT SUM(amount) AS revenue FROM orders' revenue decimal(18, 2) } // Wrong (parse-error): there is no Mapping block Mapping load_sales { orders.amount -> sales_metrics.revenue } // Right Dep load_sales { orders.amount -> sales_metrics.revenue [transformation: aggregation] } ``` Several downstream ends on one line, or a line with no source. A line names its upstream ends, one or several, and one downstream end. ```xdbml Table a { x int } Table b { x int y int } // Wrong (parse-error): one downstream end per line Dep: a.x -> b.x, b.y // Right Dep load { a.x -> b.x a.x -> b.y } ``` A kind of transformation between two entities. Only `identity`, a copy of every row, applies there; the other kinds name the field that takes part. ```xdbml Table raw_orders { id int [pk] status varchar } Table stg_orders { id int [pk] } // Wrong (transformation-between-entities): which field filters is not named Dep: raw_orders -> stg_orders [transformation: filter] // Right Dep: raw_orders.status -> stg_orders [transformation: filter] ``` A sticky note without a name. A top-level `Note` without a name is the note of the project, and takes no settings. ```xdbml // Wrong (parse-error): settings belong to a sticky note, which has a name Note [color: #FDE68A] { 'Orders are archived after two years' } // Right Note archiving [color: #FDE68A] { 'Orders are archived after two years' } ``` A reversed relationship. The right side names the child's foreign key instead of the parent's key. ```xdbml Table service_orders { order_id int [pk] } Table warranties { warranty_id int [pk] order_id int [not null] } // Wrong (ref-target-not-key): with <, the left side is the referenced side Ref: warranties.order_id < service_orders.order_id // Right: with >, the right side is the referenced side Ref: warranties.order_id > service_orders.order_id // Right: the same relationship, written with < Ref: service_orders.order_id < warranties.order_id ``` A foreign key to one field of a composite key. ```xdbml Table order_lines { order_id int [not null] line_no int [not null] constraints { (order_id, line_no) [pk] } } Table shipments { shipment_id int [pk] order_id int [not null] line_no int [not null] } // Wrong (ref-target-not-key): order_lines.order_id is one of the two fields of the key Ref: shipments.order_id > order_lines.order_id // Right Ref: shipments.(order_id, line_no) > order_lines.(order_id, line_no) ``` A block in a View body. ```xdbml // Wrong (parse-error): a View takes no constraints block View center_monthly_revenue [materialized: true] { source_query: '''SELECT center_id, month FROM monthly_totals''' center_id int [not null] month date [not null] constraints { (center_id, month) [pk] } } // Right View center_monthly_revenue [materialized: true] { source_query: '''SELECT center_id, month FROM monthly_totals''' center_id int [not null] month date [not null] Note: 'One row per service center and month' } ``` A setting in a body. ```xdbml // Wrong (parse-error): settings go in the brackets View monthly_revenue { materialized: true source_query: 'SELECT month, SUM(total) AS revenue FROM orders GROUP BY month' month date [pk] } // Right View monthly_revenue [materialized: true] { source_query: 'SELECT month, SUM(total) AS revenue FROM orders GROUP BY month' month date [pk] } ``` A `Ref` inside a Container. ```xdbml // Wrong (parse-error): a Ref is a top-level declaration Schema shop { Table customers { id int [pk] } Table orders { id int [pk] customer_id int [not null] } Ref: orders.customer_id > customers.id } // Right Schema shop { Table customers { id int [pk] } Table orders { id int [pk] customer_id int [not null] } } Ref: shop.orders.customer_id > shop.customers.id ``` Relationship settings beside an inline `ref:`. ```xdbml Table customers { id int [pk] } // Wrong (accepted silently): delete: cascade becomes a property of the field, and the relationship has none Table orders { id int [pk] customer_id int [ref: > customers.id, delete: cascade] } // Right Table orders { id int [pk] customer_id int [not null] } Ref: orders.customer_id > customers.id [delete: cascade] ``` A quote inside a string, and a function call as a default. ```xdbml // Wrong (lex-error): the apostrophe ends the string Table customers { id int [pk, note: 'The customer's number'] } // Wrong (parse-error): a function call is an expression, written in backticks Table events { id int [pk] created_at timestamp [default: now()] } // Right Table customers { id int [pk, note: 'The customer\'s number'] } Table events { id int [pk] created_at timestamp [default: `now()`] } ``` Types from other languages. ```xdbml // Wrong (parse-error): Spark generics Table readings { id int [pk] samples array } // Wrong (unquoted-type-name): a type of several words without quotes, read as the quoted name with a warning Table readings { id int [pk] taken_at timestamp with time zone } // Wrong (accepted silently): string[] passes through as a type name, not as an array Table readings { id int [pk] labels string[] } // Right Table readings { id int [pk] samples array [double] taken_at "timestamp with time zone" labels array [string] } ``` Settings from other languages. ```xdbml // Wrong (accepted silently): none of these is an xDBML setting Table users { id int [pk, auto_increment] email varchar [nullable, comment: 'Login address'] } // Right Table users { id int [pk, increment] email varchar [note: 'Login address'] } ``` Cardinality in the entity settings of an Edge. ```xdbml Entity Person { person_id int [pk] } // Wrong (accepted silently): source and target name entities in an Edge Edge KNOWS [source: Person, target: Person, source: '0..*', target: '0..*'] { since date } // Right Edge KNOWS [source: Person, target: Person, source_cardinality: '0..*', target_cardinality: '0..*'] { since date } ``` A path across an array without `.[*]`. ```xdbml Collection products { sku string [pk] } Collection orders { _id objectId [pk] line_items array [ line_item object { sku string [not null] } ] } // Wrong (invalid-nested-path): the path crosses the array without saying so Ref: orders.line_items.sku > products.sku // Right Ref: orders.line_items.[*].sku > products.sku ``` A key declared twice. Keep `[pk]` or `[unique]` on a single unnamed field, and use `constraints` only for a named key or a key on several fields. ```xdbml // Wrong (duplicate-primary-key): the primary key is declared twice Table customers { customer_id int [pk] constraints { (customer_id) [pk] } } // Right Table customers { customer_id int [pk] } ``` A composite key written as several `[pk]` fields. Write one key line in `constraints`. ```xdbml // Wrong (accepted silently): accepted for DBML compatibility, never written Table enrollments { student_id int [pk] course_id int [pk] } // Right Table enrollments { student_id int [not null] course_id int [not null] constraints { (student_id, course_id) [pk] } } ``` Separators between items. Write one field or enum value per line, with nothing after it. Quote an enum value only when it holds characters outside an identifier, and then in double quotes. ```xdbml // Wrong (accepted silently): accepted and ignored, never written Enum service_status { 'scheduled' [note: 'Appointment booked'], 'on_hold' [note: 'Awaiting parts'], } // Right Enum service_status { scheduled [note: 'Appointment booked'] on_hold [note: 'Awaiting parts'] "on hold (legacy)" } ``` A comma between index entries. List one index per line, and write a composite index in parentheses. ```xdbml // Wrong (parse-error): a comma between two index entries Table people { id int [pk] email varchar name varchar indexes { email, name } } // Right: two indexes, then one composite index Table people { id int [pk] email varchar name varchar indexes { email name (email, name) } } ``` Naming a Type after a built-in type. `money`, `date`, `json`, `uuid` and the other built-in types take precedence over a Type of the same name, whatever its letter case, so the fields would never reach the Type. ```xdbml // Wrong (named-type-shadows-builtin): money is a built-in type Type Money { amount decimal(19,4) [not null] currency varchar(3) [not null] } // Right Type MonetaryAmount { amount decimal(19,4) [not null] currency varchar(3) [not null] } ``` Listing relationships in a diagram view. A diagram view has no `Edges` or `Refs` category: a relationship or an Edge appears when both of its ends are members. ```xdbml Entity customers { id int [pk] } Entity orders { id int [pk] customer_id int [not null, ref: > customers.id] } // Wrong (parse-error): Edges is not a DiagramView category DiagramView ordering { Entities { customers orders } Edges { * } } // Right DiagramView ordering { Entities { customers orders } } ``` Writing `$defs` for internal definitions. xDBML writes the block `definitions`, and `$` is not a character of the language. ```xdbml // Wrong (lex-error): $defs is JSON Schema syntax Entity customers { billing Address $defs { Address { street string } } } // Right Entity customers { billing Address definitions { Address { street string } } } ``` Internal definitions for a relational target. A relational database reuses a shape as a user-defined type of the schema, which a `Type` at the top level declares. ```xdbml Project erp { targets: PostgreSQL } // Wrong (definitions-unsupported-target): a relational target takes no internal definitions Table customers { id int [pk] billing Address definitions { Address { street varchar(100) } } } // Right Type Address { street varchar(100) } Table customers { id int [pk] billing Address } ``` Naming an internal definition outside its entity. Another entity does not see it: the name passes through as a target-native type, with no shape, and a qualified name such as `customers.Address` does the same. ```xdbml Entity customers { billing Address definitions { Address { street string } } } // Wrong (accepted silently): suppliers.address has no shape Entity suppliers { address customers.Address } // Right Entity suppliers { address Address definitions { Address { street string } } } ``` ## Checklist before you answer 1. The first line is `xdbml: 0.7`. 2. Every `[ ]` holding two or more settings has a comma between each two of them, across line breaks too. 3. No comma or semicolon follows an item in `{ }`. 4. In every relationship between attributes, the referenced side -- the right side of `>`, the left side of `<` -- names all the fields of the parent's primary key or of one of its unique keys, and no other field. 5. Relationship settings sit in a `Ref`, not beside an inline `ref:`. Cardinalities are quoted `'min..max'` strings: `source` for the left end, `target` for the right end. 6. `Ref`, `Dep`, `Metadata`, `Type`, `SupertypeGroup`, `EntityGroup`, `EntityPartial` and `DiagramView` declarations sit at the top level. 7. A View body holds `source_query:`, fields and `Note:`, and nothing else. 8. A key sits inline only on one unnamed field, and otherwise in `constraints`; each key is declared once, and primary key fields carry `not null`. 9. Strings use single quotes, with each `'` inside escaped or the string in `'''...'''`; database expressions use backticks; multi-word types use double quotes. 10. Every setting comes from this reference, or starts with `x_` (or `x-` in double quotes). `tags` and `synonyms` are lists. 11. Edge cardinality uses `source_cardinality` and `target_cardinality`. 12. Every entity, field, Enum and Type the document names is declared, qualified with its Container where it sits in one. 13. Internal definitions sit in one `definitions { }` block of the entity that uses them, never for a relational, Cassandra, ScyllaDB or graph target; a shape used by several entities is a top-level `Type`. 14. In a source-to-target mapping, each line names its source fields and one target; its kind is in `transformation`, the statement in `source_query:` in the body of the `Dep`, and its language in `source_database`. To check a schema, run it through an xDBML validator when one is available, or paste it into the playground at https://xdbml.org/playground/: its diagnostics panel lists each error and warning with its line. ## Complete example ```xdbml xdbml: 0.7 Project service_network { targets: PostgreSQL Note: 'Car service network: customers, vehicles, work orders and invoicing' } Enum work_order_status { scheduled [note: 'Appointment booked'] in_progress on_hold [note: 'Awaiting parts'] completed invoiced } Table customers { customer_id serial [pk, not null] full_name varchar(120) [not null, synonyms: ['client name']] email varchar(255) [unique, not null, pattern: '^[^@]+@[^@]+$', tags: ['pii']] created_at timestamptz [not null, default: `now()`] Note: 'One row per registered customer' } Table vehicles { vehicle_id serial [pk, not null] customer_id int [not null] vin varchar(17) [unique, not null, minLength: 17, maxLength: 17] make varchar(60) model varchar(60) model_year smallint [check: 'model_year >= 1900'] } Table service_centers { center_id serial [pk, not null] name varchar(80) [not null] city varchar(80) } Table work_orders { order_id serial [pk, not null] vehicle_id int [not null] center_id int [not null] status work_order_status [not null, default: 'scheduled'] opened_on date [not null] closed_on date constraints { 'closed_on IS NULL OR closed_on >= opened_on' [name: 'chk_work_orders_dates'] } } Table work_order_lines { order_id int [not null] line_no int [not null] description varchar(200) [not null] labour_hrs decimal(5,2) [minimum: 0] parts_cost decimal(12,2) [minimum: 0] constraints { (order_id, line_no) [pk, name: 'pk_work_order_lines'] } } Table invoices { invoice_id serial [pk, not null] order_id int [unique, not null] issued_on date [not null, granularity: day] total decimal(12,2) [not null, business_term: 'Invoice Total'] } Table payments { payment_id serial [pk, not null] invoice_id int [not null] paid_at timestamptz [not null] amount decimal(12,2) [not null, check: 'amount > 0'] } Ref fk_vehicles_customer: vehicles.customer_id > customers.customer_id [ source: '0..*', target: '1..1', source_role: 'owned vehicle', target_role: 'owner' ] Ref fk_work_orders_vehicle: work_orders.vehicle_id > vehicles.vehicle_id [source: '0..*', target: '1..1'] Ref fk_work_orders_center: work_orders.center_id > service_centers.center_id [source: '0..*', target: '1..1'] Ref fk_work_order_lines_order: work_order_lines.order_id > work_orders.order_id [ source: '1..*', target: '1..1', delete: cascade, constraint_type: identifying ] Ref fk_invoices_order: invoices.order_id - work_orders.order_id [source: '0..1', target: '1..1'] Ref fk_payments_invoice: payments.invoice_id > invoices.invoice_id [source: '0..*', target: '1..1'] View center_monthly_revenue [materialized: true, refresh_schedule: 'monthly'] { source_query: ''' SELECT wo.center_id, date_trunc('month', i.issued_on) AS month, SUM(i.total) AS revenue FROM invoices i JOIN work_orders wo ON wo.order_id = i.order_id GROUP BY wo.center_id, date_trunc('month', i.issued_on) ''' center_id int [not null] month date [not null, granularity: month] revenue decimal(14,2) [tags: ['kpi']] Note: 'One row per service center and month' } ``` ## More - Full specification, current draft: https://xdbml.org/spec/current - 5-minute introduction: https://xdbml.org/learn/ - Live playground: https://xdbml.org/playground/ - Repository: https://github.com/xdbml/xdbml-spec