Entity / foldkit-entity

Relations and derived values

ts
import { Schema } from 'effect'
import { Derived, Entity, Relation } from 'foldkit-entity'

const Author = Entity.define('Author', Schema.Struct({ id: Schema.String, name: Schema.String }))
const Comment = Entity.define('Comment', Schema.Struct({ id: Schema.String, body: Schema.String }))
const Post = Entity.define(
  'Post',
  Schema.Struct({ id: Schema.String, title: Schema.String, published: Schema.Boolean }),
).pipe(Entity.derived({ commentCount: Derived.make(Schema.Number) }))

const Blog = Entity.relate(
  { Author, Post, Comment },
  {
    Post: {
      author: Relation.one(Author),
      editor: Relation.one(Author, { optional: true }),
      comments: Relation.many(Comment),
    },
    Comment: { post: Relation.one(Post), author: Relation.one(Author) },
  },
)

Blog.Post.schema // Schema.Struct of id, title, published: relations are not in it
Blog.Post.fields.title.schema // Schema.String
Blog.Post.relations.editor.optional // true
Blog.Post.derived.commentCount.schema // Schema.Number
Blog.Post.relations.comments.target() // Blog.Comment
Blog.Post.relations.comments.target().relations.post.target() // Blog.Post, fully typed
Object.keys(Blog.Post.members) // id, title, published, author, editor, comments, commentCount
  • Entity.define generates one Field per schema property and creates the identity. Calling it twice with the same name makes two different entities.
  • Derived.make states a readable value's schema and nothing about how it is produced. Entity.derived is a pipe step because it concerns one entity. It may also say what a client can foresee of it (below).
  • Derived.count(relation) says what it is: how many rows point at this one through relation, a one relation of the counted Entity. It names another Entity's relation, so it is added after Entity.relate:
    ts
    const CountedPost = Blog.Post.pipe(
      Entity.derived({ commentTotal: Derived.count(Blog.Comment.relations.post) }),
    )
    A count of a many relation, or of rows pointing at another Entity, is refused where it is declared. remote-drizzle compiles it with no binding entry, and Remote predicts it while a write that adds, removes or moves a counted row is pending.
  • Derived.exists(relation, { viewer }) says whether a row points here through relation and at whoever reads it through viewer, another one relation of the same Entity: "did I comment on this post?"
    ts
    const PostWithMyComment = Blog.Post.pipe(
      Entity.derived({
        myComment: Derived.exists(Blog.Comment.relations.post, {
          viewer: Blog.Comment.relations.author,
        }),
      }),
    )
    Its value is that row's id, or none (Option<string>), so the reader can take it back by deleting the row. It depends on who reads it. Each derived member's derives says which kind it is (Supplied, Count, Exists).
  • Entity.relate takes the entities and every relation between them, adds the relations to them, and returns them typed with their relations. Use the returned ones (Blog.Post) for their types; the Post you passed in has the same relations at runtime. It is one step over Entities that already exist because Entities point at each other, and TypeScript cannot infer two constants each typed by the other.
  • Relation.one / Relation.many state what the owner sees. Post.author: one and Author.posts: many together are the familiar one-to-many; neither side names it.
  • target() returns the related entity, so relations can be followed from there, around a cycle too. Entity.relate throws for a relation key that is already a member, an owner that is not in the first argument, and a target that is not in the first argument. The types reject the first two where they are written; a stray target is found when relate runs.

One Entity, several descriptors

Every Entity has one shared identity holding its fields, relations, derived members, sets, and invariants. Entity.relate, Entity.derived, Entity.sets, and Entity.invariant attach to that identity, so descriptors returned before relate, from target(), or captured in a query all read the same members. Metadata is scoped per descriptor: Entity.annotate and Entity.annotateMembers return a fresh descriptor carrying its own labels or options so one view keeps its annotations separate. Compare descriptors with Entity.same(a, b) rather than ===.

A descriptor's type still shows only the steps it came through: read typed members from the descriptor relate returned, or a later one.

What a delete does to the rows pointing at it

A one relation may say what happens to its row when the row it points at is deleted.

  • Relation.one(Post, { onDelete: 'cascade' }) says a row goes when the row it points at is deleted: a comment with its post, a reply with the post it answers. It is declared on the link the row holds, as its foreign key is, and a many declares nothing. Entity.cascading(Post) lists every relation that takes rows with a deleted post ({ relation, owner }), so Remote removes those it holds while the delete is pending, counts and lists with them, and remote-drizzle's writer removes them where it deletes, on a store without foreign keys too.
  • Relation.one(Topic, { onDelete: 'restrict' }) says the row it points at cannot be deleted while it points there: a topic with notes under it. Entity.restricting(Topic) lists those relations; remote-drizzle's writer finds such a delete and RemoteServer.write refuses it as Refusal.referenced (foldkit-remote), naming the relation and none of the rows.
  • Relation.one(Folder, { optional: true, onDelete: 'setNull' }) says the row stays and points nowhere when the row it points at is deleted: a doc whose folder went. Only a link that may point nowhere can say it, and the types refuse it without optional: true. Entity.clearing(Folder) lists those relations; clearing a link is an update of the row, so each is held to its own Update rules, as unlinking it in an update would be.
  • Who may let a cascade take a row is said beside it. By default each row it takes is held to its own Delete rule, for whoever deletes the row it points at: a delete that would take a row they may not delete is refused whole (Guard judges it, the writer holds it). Relation.one(Post, { onDelete: 'cascade', authorizedBy: 'parent' }) says whoever may delete the post may take these rows with it, whoever wrote them: a post's author removing everyone's likes of it. authorizedBy is said only beside onDelete: 'cascade', and reads back as the relation's authorizedBy.
  • A cascade may not reach an Entity whose rows are themselves pointed at through a setNull or restrict relation: RemoteServer.write refuses such a delete where the server is defined.