liveBook · Manning

Primary key

As explained in Functional Design and Architecture: Examples in Haskell

A primary key is a field or combination of fields that uniquely identifies a record in a database.

A primary key identifies a particular stored record. Its choice affects more than the database schema: application code must also pass the right key when it loads an entity. If two entities use interchangeable string IDs, accidentally loading a meteor with a comet ID can look valid to the compiler. section 11.2.2

For a relational meteor table, a tempting natural key combines azimuth, altitude, and timestamp. That design uses floating-point values as keys, which should be avoided; natural keys also need strong justification. A separate integer ID gives the table a dedicated key while keeping database fields distinct from the domain model. section 12.1.1 section 12.2.2

instance Table DBMeteorT where
 
 data PrimaryKey DBMeteorT f = DBMeteorId (Columnar f Int)
   deriving (Generic, Beamable)
 
 primaryKey k = DBMeteorId (_id k)

In beam, the table’s `Table` instance declares its `PrimaryKey` type and extracts it from the `_id` column. `DBMeteorId` wraps that column as the key for `DBMeteorT`. section 12.2.2

Keys for different entities

A key–value model can give meteors `MeteorKey MeteorID` and comets `CometKey GUID Int`. Both are instances of the generic `KeyEntity` design, but their entity tags make them distinct key types. A generic loading operation can accept the appropriately typed key without treating every entity’s identifier as interchangeable. section 11.2.3

Keep the two concerns together: choose a suitable identifier for stored rows, then represent it in code so the intended entity is clear. Relational table types and key–value entity tags take different routes to that goal. section 12.1.1 section 11.2.3

How Functional Design and Architecture: Examples in Haskell covers it

How deep it goes
Works through natural-key drawbacks and typed key declarations, but does not develop a general key-selection procedure.
Examples
Uses a meteor’s composite natural key, a beam integer ID, and distinct meteor and comet key constructors.
What it assumes
Assumes familiarity with Haskell types and introduces the entity-tagged key design through concrete declarations.
What you can do after
Apply it via beam’s Table instance or entity-tagged key types to represent keys that belong to specific records.
How it connects
Connects primary keys to relational tables, key–value databases, algebraic data types, and type-safe entity loading.

Also explained in

Compare how 21 books explain primary key →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Functional Design and Architecture: Examples in Haskell. The section links point to the parts of the book it draws on.