Skip to main content

SQL Tables

Basics

You can easily diagram entity-relationship diagrams (ERDs) in D2 by using the sql_table shape. Here's a minimal example:

1my_table: {
2 shape: sql_table
3 # This is defined using the shorthand syntax for labels discussed in the containers section.
4 # But here it's for the type of a constraint.
5 # The id field becomes a map that looks like {type: int; constraint: primary_key}
6 id: int {constraint: primary_key}
7 last_updated: timestamp with time zone
8}
my_tableidintPKlast_updatedtimestamp with time zone

Each key of a SQL Table shape defines a row. The primary value (the thing after the colon) of each row defines its type.

The constraint value of each row defines its SQL constraint. D2 will recognize and shorten:

constraintshort
primary_keyPK
foreign_keyFK
uniqueUNQ

But you can set any constraint you'd like. It just won't be shortened if unrecognized.

info

You can also specify multiple constraints with an array.

1x: int { constraint: [primary_key; unique] }

Foreign Keys

Here's an example of how you'd define a foreign key connection between two tables:

1objects: {
2 shape: sql_table
3 id: int {constraint: primary_key}
4 disk: int {constraint: foreign_key}
5
6 json: jsonb {constraint: unique}
7 last_updated: timestamp with time zone
8}
9
10disks: {
11 shape: sql_table
12 id: int {constraint: primary_key}
13}
14
15objects.disk -> disks.id
objectsidintPKdiskintFKjsonjsonbUNQlast_updatedtimestamp with time zonedisksidintPK
info

When rendered with the TALA layout engine or ELK layout engine, connections point to the exact row.

Example

Like all other shapes, you can nest sql_tables into containers and define edges to them from other shapes. Here's an example:

1cloud: {
2 disks: {
3 shape: sql_table
4 id: int {constraint: primary_key}
5 }
6 blocks: {
7 shape: sql_table
8 id: int {constraint: primary_key}
9 disk: int {constraint: foreign_key}
10 blob: blob
11 }
12 blocks.disk -> disks.id
13
14 AWS S3 Vancouver -> disks
15}
clouddisksidintPKblocksidintPKdiskintFKblobAWS S3 Vancouver