entity

package
v0.1.12 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 9, 2026 License: MIT Imports: 3 Imported by: 0

Documentation

Overview

Package entity defines the entity abstraction layer: configured tables, views, and procedures exposed to MCP tools, with aliases, field projection, masking, descriptions, role permissions, row-level security, and keys.

An Entity is a complete description of a Relation (Codd): attributes with domains and constraints, candidate keys, foreign keys, and role access. Registry holds an immutable set of entities keyed by logical name. RowPolicies attach a relalg.Predicate per role for row-level security, applied by rbac.

Index

Constants

View Source
const (
	KeyPartial    = "partial"    // a partial unique index (WHERE ...)
	KeyExpression = "expression" // an index on expressions, such as lower(email)
	KeyPrefix     = "prefix"     // a MySQL prefix index, such as email(10)
	KeyNullable   = "nullable"   // a nullable column: several rows may hold NULL
)

Reasons a unique key does not identify a row.

View Source
const (
	FKCascade    = "cascade"
	FKSetNull    = "set_null"
	FKSetDefault = "set_default"
)

Referential actions of a foreign key that write the referencing rows.

Variables

View Source
var ErrDuplicateEntity = errors.New("entity: duplicate name")

ErrDuplicateEntity is returned by NewRegistry when two entities share a name.

View Source
var ErrEmptyName = errors.New("entity: empty name")

ErrEmptyName is returned by NewRegistry when an entity has an empty name.

Functions

func ID added in v0.1.12

func ID(datasource, schema, name string) string

ID is the canonical identity of a configured entity, its namespace path: datasource.schema.name, or datasource.name without a schema. Entity names, datasource names and schemas contain no dots.

func ReferencesOf added in v0.1.12

func ReferencesOf(datasource, schema, local string) []string

ReferencesOf lists the ways to refer to the entity named local in a datasource and schema, shortest first, like partially qualified SQL names: local, schema.local, datasource.local and datasource.schema.local, the last being its ID.

func ReferentialWrite added in v0.1.11

func ReferentialWrite(action string) bool

ReferentialWrite reports whether a referential action changes the referencing rows (cascade, set null or set default) rather than only checking them.

Types

type Action

type Action uint8

Action names a DML operation for role permissions.

const (
	// ActionRead selects records.
	ActionRead Action = iota
	// ActionCreate inserts records.
	ActionCreate
	// ActionUpdate updates records.
	ActionUpdate
	// ActionDelete deletes records.
	ActionDelete
	// ActionExecute calls a stored procedure.
	ActionExecute
	// ActionAggregate groups/aggregate-queries records.
	ActionAggregate
)

func ActionsFor added in v0.1.11

func ActionsFor(kind Kind) []Action

ActionsFor lists the actions applicable to an entity kind: execute for a procedure, otherwise the record actions.

func (Action) String

func (a Action) String() string

String returns the action name.

type Attribute

type Attribute struct {
	Name        string
	Alias       string
	Description string
	Domain      Domain
	Excluded    bool   // true removes the column from all responses (field projection)
	Mask        string // optional mask rule name (see mask package)
}

Attribute is one column of a relation, with projection and masking controls.

type Cascade added in v0.1.11

type Cascade struct {
	// Schema and Table name the referencing relation; Relation is its
	// relation key and Entity the entity exposing it ("" when none does),
	// both set at assembly.
	Schema   string
	Table    string
	Relation string
	Entity   string
	// Columns are the referenced columns of this relation; ForeignColumns
	// the referencing columns of the other, in the same order.
	Columns        []string
	ForeignColumns []string
	OnDelete       string
	OnUpdate       string
}

Cascade is a foreign key of another relation that writes its rows when rows of the referenced relation change.

type Domain

type Domain struct {
	Type     string
	Nullable bool
	// Default reports that the database supplies a value when an insert
	// omits the column (a default expression, a sequence, an identity BY
	// DEFAULT or auto_increment).
	Default bool
	// Generated reports that the database computes the value (a generated
	// column or an identity ALWAYS): the column cannot be written.
	Generated bool
	// AutoIncrement reports a value taken from a sequence on insert.
	AutoIncrement bool
}

Domain is a column's value domain as introspected from the database.

func (Domain) Required added in v0.1.11

func (d Domain) Required() bool

Required reports whether a create must supply the column.

func (Domain) Writable added in v0.1.11

func (d Domain) Writable() bool

Writable reports whether creates and updates may set the column.

type Entity

type Entity struct {
	// Name identifies the entity: its canonical ID (see ID) when Local is
	// set, which every reference inside the gateway uses.
	Name string
	// Local is the configured name, unique within its datasource and schema;
	// empty when Name is not namespaced.
	Local       string
	Source      string
	DataSource  string
	Schema      string
	Description string
	Kind        Kind
	Attributes  []Attribute
	Keys        []Key
	ForeignKeys []ForeignKey
	// Indexes are the table's indexes as introspection reports them, for
	// administrators to see; the database plans access paths, not the
	// gateway. The unique ones are also Keys.
	Indexes     []Index
	Role        RoleAccess
	FieldAccess FieldAccess
	MCP         MCPFlags
	RowPolicies RowPolicies
	// TenantPolicy is ANDed for every principal and never merged across
	// grants; nil means the entity has no tenant boundary.
	TenantPolicy relalg.Predicate
	Relations    []Relationship
	// Derived marks a relation whose data comes from other relations (a view,
	// a materialized view or a foreign table): a write to any table of its
	// datasource may change it.
	Derived bool
	// Relation identifies the physical relation (set at assembly, see
	// RelationKey); at most one entity exposes a relation.
	Relation string
	// Affects lists the entities a procedure writes; empty means unknown.
	Affects []string
	// Cascades are the foreign keys of other relations whose referential
	// actions write their rows when this entity's rows are deleted or their
	// referenced columns updated (I-6).
	Cascades []Cascade
	// AllowCascade admits such writes without checking the caller's
	// permissions on the cascaded entities.
	AllowCascade bool
	// SideEffects reports triggers or rules on the relation: a write may
	// change other relations of the datasource.
	SideEffects bool
	// Params is the ordered list of formal parameter names for a KindProcedure
	// entity. execute_entity binds a caller's named args to positional CALL
	// placeholders in this exact order; a stored procedure whose params are not
	// declared cannot be executed (fail-closed) since positional binding would
	// otherwise be guesswork.
	Params []string
}

Entity is a complete description of an exposed relation.

func (Entity) AttributeByName

func (e Entity) AttributeByName(name string) (Attribute, bool)

AttributeByName returns the attribute with the given logical name and a found flag. It matches Name or Alias.

func (Entity) CursorKey added in v0.1.11

func (e Entity) CursorKey() []string

CursorKey returns the key keyset pagination orders by: the primary key, otherwise the first identity key; nil when the entity has none.

func (Entity) DatasourceName added in v0.1.11

func (e Entity) DatasourceName() string

DatasourceName is the entity's datasource, "default" when unset.

func (Entity) IdentityKeys added in v0.1.11

func (e Entity) IdentityKeys(enforced, inTransaction bool) [][]string

IdentityKeys returns the column sets that identify at most one row, primary key first. enforced drops declared keys, as a write needs; inTransaction drops deferrable keys.

func (Entity) OrderedNames added in v0.1.11

func (e Entity) OrderedNames(set map[string]bool) []string

OrderedNames returns the attribute names in set, in attribute order.

func (Entity) PrimaryKey

func (e Entity) PrimaryKey() []string

PrimaryKey returns the columns of the primary key, or nil if none is declared.

func (Entity) References added in v0.1.12

func (e Entity) References() []string

References lists the ways to refer to the entity, shortest first (see ReferencesOf); an entity without a local name is referred to by Name only.

func (Entity) RelationKey added in v0.1.11

func (e Entity) RelationKey() string

RelationKey identifies the physical relation the entity exposes: Relation when assembly resolved it, otherwise its configured datasource, schema and source.

type FieldAccess

type FieldAccess map[string]FieldPermissions

FieldAccess maps role names to field-level permissions. Absence of a role preserves entity-level authorization behavior for backwards compatibility.

type FieldPermissions

type FieldPermissions struct {
	Read  []string
	Write []string
}

FieldPermissions is one role's field-level access. Read applies to projections, filters, grouping, and aggregate inputs; Write applies to create values and update assignments.

type ForeignKey

type ForeignKey struct {
	Name    string
	Columns []string
	// RefSchema is the referenced relation's schema; it may differ from the
	// referencing table's.
	RefSchema   string
	RefRelation string
	RefColumns  []string
	// OnDelete and OnUpdate are the referential actions: one of the FK*
	// constants, empty when the database reports none.
	OnDelete string
	OnUpdate string
}

ForeignKey declares referential integrity to another relation.

type Index added in v0.1.12

type Index struct {
	Name string
	// Method is the database's name for the index structure, lower-cased:
	// for example btree, hash, gin, gist, brin or spgist on PostgreSQL, and
	// btree, hash, fulltext or spatial on MySQL and OceanBase.
	Method string
	// Parts are the key parts in order: a column, a column prefix such as
	// title(20), or an expression as the database prints it. Parts the
	// database does not report (OceanBase's full-text and spatial indexes)
	// are left out.
	Parts   []string
	Unique  bool
	Primary bool
	// Where is the predicate of a partial index.
	Where string
}

Index is an index of a table in the database's own terms: databases support different structures and forms of index.

type Key

type Key struct {
	Name    string
	Columns []string
	Primary bool
	// Declared marks a key the database does not guarantee, configured on a
	// view or foreign table: it serves reads, never the write-safety check.
	Declared bool
	// Deferrable reports a constraint checked at commit: inside a
	// transaction it may be violated, so it identifies no row there.
	Deferrable bool
	// Reason is empty for a key that identifies at most one row.
	Reason string
}

Key is a primary or unique key. A unique key that cannot identify a row is kept for display, with Reason saying why.

type Kind

type Kind uint8

Kind classifies a database object backing an entity.

const (
	// KindTable is a base table.
	KindTable Kind = iota
	// KindView is a view.
	KindView
	// KindProcedure is a stored procedure.
	KindProcedure
)

type MCPFlags

type MCPFlags struct {
	DMLTools         bool // expose the seven DML tools for this entity
	CustomTool       bool // register a stored procedure as a named tool
	TrustedProcedure bool // procedure passed explicit DBA cost/safety review
}

MCPFlags controls how an entity participates in MCP.

type Registry

type Registry struct {
	// contains filtered or unexported fields
}

Registry is an immutable set of entities keyed by Name, also found by any of their References. It holds no per-request state and is safe for concurrent use (invariant I9).

func NewRegistry

func NewRegistry(entities []Entity) (*Registry, error)

NewRegistry builds a Registry from entities, rejecting empty names and duplicates. It copies the slice so callers cannot mutate the registry.

func (*Registry) Entities

func (r *Registry) Entities() []Entity

Entities returns all registered entities.

func (*Registry) Match added in v0.1.12

func (r *Registry) Match(ref string) []Entity

Match returns the entities ref may name: the entity whose Name it is, else every entity it is a reference of, like a partially qualified SQL name.

func (*Registry) Resolve

func (r *Registry) Resolve(ref string) (Resolved, bool)

Resolve returns the entity a reference names (see Match) with field projection applied (excluded attributes removed). The found flag is false if no entity, or more than one, matches.

func (*Registry) ShortName added in v0.1.12

func (r *Registry) ShortName(e Entity, visible func(Entity) bool) string

ShortName is the shortest reference naming e alone among the entities visible accepts (all when nil); e itself is assumed visible.

type Relationship

type Relationship struct {
	Name        string
	Target      string
	Cardinality string
	JoinOn      map[string]string // this field -> target field
}

Relationship describes a link to another entity for nested expansion.

type Resolved

type Resolved struct {
	Entity     Entity
	Attributes []Attribute
}

Resolved is a request-time view of an entity with field projection applied (excluded attributes removed). RBAC further restricts Attributes per role.

type RoleAccess

type RoleAccess map[Action][]string

RoleAccess maps each action to the roles allowed to perform it.

type RowPolicies

type RowPolicies map[string]relalg.Predicate

RowPolicies maps a role name to a row-level filter predicate. The rbac package ANDs the role's predicate with the request predicate.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL