Schema



Like generators, data models have a schema. They capture the fields, relations, and other information needed to generate types, database tables, and much more.

hof/dm.#Datamodel Schema

hof’s core #Datamodel schema is intentionally minimal. It defines a hiearchy from Datamodel > Model > Fields & Relations. The schema is sparce and open, having just what is needed for hof dm to checkpoint and introspect data models.

The following as the core of the #Datamodel schema.

Core of #Datamodel

package dm

#Datamodel: {
	@datamodel()
	Name: string

	// Models in the data model, ordered
	Models: #Models
	OrderedModels: [ for M in Models {M}]

	...
}

#Models: [name=string]: #Model & {Name: name, ...}
#Model: {
	@dm_model()
	Name: string

	Fields: #Fields
	OrderedFields: [ for F in Fields {F}]

	Relations?: #Relations
	...
}

#Fields: [name=string]: #Field & {Name: name, ...}
#Field: {
	@dm_field()
	Name: string

	Type: string

	...
}

#Relations: [name=string]: #Relation & {Name: name, ...}
#Relation: {
	@dm_relation()

	Name: string

	// Relation to another thing

	// This is the relation type
	Reln: "BelongsTo" | "HasOne" | "HasMany" | "ManyToMany"

	// This is the other type or side of the relation (a Model)
	Type: string

	...
}

See hof datamodel schemas for the full schema.

example/schema.#Datamodel

hof’s core #Datamodel schema is intended to be extended. Since we will be using a Go map for a simple data store, we will add a CUE field to #Model to track which field to use for the index in our types.

We add a new file in our schema directory

example/schema/dm.cue

package schema

import (
	"github.com/hofstadter-io/hof/schema/dm"
)

#Datamodel: dm.#Datamodel & {
	Models: [string]: #Model
	OrderedModels: [ for M in Models {M}]
}

#Model: dm.#Model & {
	// field used for indexing
	Index: string
}

We now have an extended schema we can import to define our data models.

2022 Hofstadter, Inc