dbschema

package
v0.102.4 Latest Latest
Warning

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

Go to latest
Published: Nov 12, 2026 License: MIT Imports: 6 Imported by: 16

Documentation

Overview

Package dbschema provides a portable schema-description vocabulary and read-side (introspection) capability for DALgo.

The package contains Tier-1 engine-neutral types — FieldDef, CollectionDef, IndexDef, Type, Precision, DefaultExpr and concretes — designed for three-tier composition: engine-specific extensions in each driver repo (Tier 2) embed Tier 1; application-specific wrappers in consumer repos (Tier 3) embed Tier 2.

The package also defines the SchemaReader capability interface for schema introspection (the read-side mirror of [ddl.SchemaModifier]) and the shared NotSupportedError typed error used by both the read and write sides. Optional capabilities sit beside it: SourceViewReader, SourceRowsReader, SourceConstraintChecker and NativeAccessReader (which engine principals can reach a collection natively, and why).

dbschema does NOT contain operations. CREATE / DROP / ALTER live in the sibling [ddl] sub-package, which imports dbschema for the types it operates on.

Index

Constants

View Source
const (
	// BlindSpotConnectionRules is the engine's rules on who may connect from
	// where and how (for example pg_hba.conf).
	BlindSpotConnectionRules = "connection-rules"
	// BlindSpotExternalIdentity is logins mapped from an external identity
	// provider, such as cloud IAM.
	BlindSpotExternalIdentity = "external-identity-logins"
	// BlindSpotReplicasBackups is copies of the data outside this database.
	BlindSpotReplicasBackups = "replicas-and-backups"
	// BlindSpotSharedCredential is people sharing one principal's credential.
	BlindSpotSharedCredential = "shared-credentials"
	// BlindSpotDefinerCode is code that runs with its owner's rights, such as
	// definer-rights functions and views owned by other principals.
	BlindSpotDefinerCode = "definer-rights-code"
	// BlindSpotRowPredicates is the row-security rules themselves, which the
	// answer does not read.
	BlindSpotRowPredicates = "row-security-predicates"
)

Blind spots shared by engines. Adapters may add their own codes.

Variables

This section is empty.

Functions

func ListCollections

func ListCollections(ctx context.Context, db dal.DB, parent *record.Key) ([]dal.CollectionRef, error)

ListCollections resolves db to a SchemaReader (see dal.As) and delegates; returns *NotSupportedError if the assertion fails.

Types

type CollectionDef

type CollectionDef struct {
	// SourceDefinition optionally retains the backing provider's native DDL
	// and catalog details that portable Fields/Indexes cannot represent.
	// It is descriptive metadata, not an instruction to execute source SQL.
	SourceDefinition *SourceDefinition `json:"sourceDefinition,omitempty"`

	// SourceRights optionally describes effective data terms for this table/view.
	// Providers that do not know source terms may omit it. This is metadata only.
	SourceRights []datarights.SourceRight `json:"sourceRights,omitempty"`

	// Name is the collection / table name.
	Name string
	// Fields lists the fields (columns) in declared order.
	Fields []FieldDef
	// PrimaryKey lists the names of fields composing the primary key.
	// Empty = no PK declared (driver-specific behavior applies).
	PrimaryKey []dal.FieldName
	// Indexes lists the secondary indexes declared inline with this
	// collection definition.
	Indexes []IndexDef
	// ForeignKeys are the outgoing foreign keys declared by the backing database.
	// They are metadata; CreateCollection does not create these constraints.
	ForeignKeys []ForeignKeyDef
}

CollectionDef is the portable description of one collection (a.k.a. table) — its name, ordered fields, primary key, and inline declared secondary indexes.

PrimaryKey is a slice of dal.FieldName. A single-field PK is a one-element slice; a composite PK has multiple entries; an empty slice means "no primary key declared" and driver-specific behavior applies (SQLite may auto-assign ROWID, PostgreSQL may reject, etc.).

Indexes declared inline with CollectionDef are created together with the collection in a CreateCollection call. Indexes added or removed AFTER the collection exists are passed as ddl.AddIndex / ddl.DropIndex AlterOps to ddl.AlterCollection.

The package does NOT validate that PrimaryKey or Indexes reference fields actually present in Fields. That's a driver concern — drivers MUST return a driver-specific error (or *NotSupportedError if the operation itself isn't supported) when validating against the engine.

func DescribeCollection

func DescribeCollection(ctx context.Context, db dal.DB, ref *dal.CollectionRef) (*CollectionDef, error)

DescribeCollection resolves db to a SchemaReader (see dal.As) and delegates.

type ConstraintDef

type ConstraintDef struct {
	// Name is the constraint name.
	Name string
	// Type is the engine-neutral kind:
	// "check", "unique", "primary-key", "foreign-key".
	Type string
}

ConstraintDef is the portable description of one constraint on a collection. Tier-1 keeps this minimal — Name and Type only. The richer shape required for specific constraint kinds (check expression, unique field list, foreign-key target + cascade actions, etc.) is intentionally deferred. Engine-specific reader extensions (Tier 2) MAY define richer constraint types in their own packages without waiting for Tier 1 to grow.

func ListConstraints

func ListConstraints(ctx context.Context, db dal.DB, ref *dal.CollectionRef) ([]ConstraintDef, error)

ListConstraints resolves db to a SchemaReader (see dal.As) and delegates.

type DefaultCurrentTimestamp

type DefaultCurrentTimestamp struct{}

DefaultCurrentTimestamp signals "use the engine's current-timestamp default at insertion time." Drivers translate to engine-specific SQL (CURRENT_TIMESTAMP on SQLite, now() or CURRENT_TIMESTAMP on PostgreSQL) or the equivalent.

Cross-engine precision: SQLite returns timestamps at second resolution by default; PostgreSQL at microsecond. The Feature does not pin precision — drivers translate as their engine allows.

type DefaultExpr

type DefaultExpr interface {
	// contains filtered or unexported methods
}

DefaultExpr is the sealed interface for column default value expressions. The interface is sealed via an unexported marker method (defaultExpr) so the set of valid DefaultExpr cases is closed at the package boundary — drivers know which cases exist and translate accordingly. New cases require adding to this package.

MVP concretes:

type DefaultLiteral

type DefaultLiteral struct {
	Value any
}

DefaultLiteral is a column default that uses a literal Go value. Drivers MUST handle at minimum: int, int64, float64, string, bool, []byte, and nil. Drivers MAY return a driver-specific error if the underlying Go type cannot be serialized to the target engine.

type FieldDef

type FieldDef struct {
	// Name is the field's identifier.
	Name dal.FieldName
	// Type is the portable column type.
	Type Type
	// Length is an optional length hint for String / Bytes types.
	// nil means "driver default."
	Length *int
	// Precision is an optional precision hint for Decimal types.
	// nil means "driver default."
	Precision *Precision
	// Nullable is true if the field permits NULL values. Default
	// (zero value) is false = NOT NULL.
	Nullable bool
	// Default is an optional default expression. nil means "no
	// default."
	Default DefaultExpr
	// AutoIncrement is true if the field should auto-generate values.
	// Typically restricted by drivers to integer primary-key fields.
	AutoIncrement bool
}

FieldDef is the portable description of one field (a.k.a. column) of a CollectionDef.

FieldDef is the schema-DEFINITION shape. It is distinct from the unrelated runtime types in the dal package: dal.Column (a SELECT-clause expression+alias), dal.FieldRef (a query field reference), record.FieldVal (a runtime name+value pair). Those exist for query and runtime concerns; FieldDef exists to describe a column's structure in a portable way.

AutoIncrement is advisory: drivers MAY restrict it to integer types in the primary key and return *NotSupportedError if a caller passes AutoIncrement on a non-integer field or a field not in the primary key. dbschema itself does NOT enforce the restriction.

type ForeignKeyDef added in v0.88.0

type ForeignKeyDef struct {
	Name                 string
	Fields               []dal.FieldName
	ReferencedCollection string
	// ReferencedNamespace is set when the target is outside the source
	// collection's default namespace (for example another SQL schema).
	ReferencedNamespace string
	ReferencedFields    []dal.FieldName
	Enforcement         ForeignKeyEnforcement
	// OnUpdate and OnDelete are database referential actions (for example
	// CASCADE, RESTRICT, SET NULL). Empty means the provider did not report them.
	OnUpdate string
	OnDelete string
}

ForeignKeyDef is one outgoing database foreign key. Fields and ReferencedFields are ordered in matching positions, including for composite keys. ReferencedFields may be empty when the database does not expose the implicit primary-key target columns.

type ForeignKeyEnforcement added in v0.88.0

type ForeignKeyEnforcement string

ForeignKeyEnforcement describes whether a database foreign key is enforced for the connection used to inspect it. Unknown means the provider cannot establish the effective state; it must not be interpreted as enabled.

const (
	// ForeignKeyEnforcementUnknown means the provider cannot establish the
	// effective state. It must not be interpreted as enabled.
	ForeignKeyEnforcementUnknown ForeignKeyEnforcement = "unknown"
	// ForeignKeyEnforcementEnabled means the foreign key is enforced for the
	// connection used to inspect it.
	ForeignKeyEnforcementEnabled ForeignKeyEnforcement = "enabled"
	// ForeignKeyEnforcementDisabled means the foreign key is not enforced for
	// the connection used to inspect it.
	ForeignKeyEnforcementDisabled ForeignKeyEnforcement = "disabled"
)

type IndexDef

type IndexDef struct {
	// Name is the index name.
	Name string
	// Collection is the simple name of the collection this index belongs to.
	Collection string
	// Fields is the ordered list of fields the index covers.
	Fields []dal.FieldName
	// Unique is true if the index enforces uniqueness.
	Unique bool
}

IndexDef is the portable description of one index on a CollectionDef. The Fields slice is ordered — order matters for composite indexes (field ordinality affects which queries the index can serve).

Collection is the simple name of the collection the index belongs to. Richer collection addressing (catalog/schema/parent-key) lives in dal.CollectionRef and is the argument type passed to reader and writer methods; this stored value is a plain name. Tier-2 engine extensions MAY add a richer reference field if needed.

func ListIndexes

func ListIndexes(ctx context.Context, db dal.DB, ref *dal.CollectionRef) ([]IndexDef, error)

ListIndexes resolves db to a SchemaReader (see dal.As) and delegates.

type NativeAccess added in v0.100.0

type NativeAccess struct {
	// Collection is the collection the answer is about.
	Collection dal.CollectionRef
	// AsOf is the time the engine's catalog was read, on the engine's clock.
	AsOf time.Time
	// Principals are the principals that can reach the collection, in a
	// deterministic order. When the engine records an owner of the
	// collection, the owner is always listed.
	Principals []NativePrincipal
	// RowSecurity states whether the engine filters the collection's rows per
	// principal.
	RowSecurity NativeRowSecurity
	// Coverage states what the answer covers and what it cannot see.
	Coverage NativeAccessCoverage
}

NativeAccess is the native access to one collection as the engine's catalog shows it.

type NativeAccessCoverage added in v0.100.0

type NativeAccessCoverage struct {
	Level NativeCoverageLevel
	// Covered names the catalog facts the answer read.
	Covered []string
	// BlindSpots names access the engine's catalog cannot show at all.
	BlindSpots []string
	// Gaps are inputs that could not be read or did not resolve; each makes
	// some privileges unknown.
	Gaps []NativeAccessGap
}

NativeAccessCoverage states what an answer covers and what it cannot see.

type NativeAccessGap added in v0.100.0

type NativeAccessGap struct {
	Code   string
	Detail string
}

NativeAccessGap is one input that could not be read or resolved.

type NativeAccessReader added in v0.100.0

type NativeAccessReader interface {
	// ReadNativeAccess returns the native access to ref as the engine's catalog shows it.
	ReadNativeAccess(ctx context.Context, ref *dal.CollectionRef) (*NativeAccess, error)
}

NativeAccessReader is an optional schema-introspection capability. It answers "which database principals can reach this collection natively, with which privileges, and why": access through the engine's own accounts and roles, outside any DALgo access policy. It is separate from SchemaReader so existing drivers need no API changes; a driver that cannot read its engine's authorization catalog, or whose engine has no principals (SQLite, for example), simply does not implement it. Callers resolve it with dal.As[NativeAccessReader](db) and MUST read its absence, or a *NotSupportedError from it, as "native access unknown", never as "nobody".

An implementation MUST NOT report "nobody" when it cannot know. It either returns an error, or a *NativeAccess whose Coverage names every input it could not read and every kind of access its catalog cannot show. An answer with no principal MUST have Coverage.Level NativeCoverageUnknown. A collection that does not exist is an error, never an empty answer.

The answer describes the catalog at NativeAccess.AsOf. It is an inventory, not an authorization decision: it never grants, widens or narrows DALgo access.

The Native* types carry no serialization tags: a consumer that sends an answer over the wire maps it to its own format.

type NativeConfidence added in v0.100.0

type NativeConfidence string

NativeConfidence states how a privilege is known. From strongest to weakest: NativeVerified, NativeInferred, NativeUnknown.

const (
	// NativeVerified is read directly from an explicit catalog entry.
	NativeVerified NativeConfidence = "verified"
	// NativeInferred is derived by the adapter, for example through a
	// membership chain.
	NativeInferred NativeConfidence = "inferred"
	// NativeUnknown means an input needed to decide was missing.
	NativeUnknown NativeConfidence = "unknown"
)

type NativeCoverageLevel added in v0.100.0

type NativeCoverageLevel string

NativeCoverageLevel is how complete a native answer is.

const (
	// NativeCoveragePartial means the catalog was read; access it cannot show
	// is named in BlindSpots. A native answer is never complete.
	NativeCoveragePartial NativeCoverageLevel = "partial"
	// NativeCoverageUnknown means an input the answer depends on could not be
	// read or resolved.
	NativeCoverageUnknown NativeCoverageLevel = "unknown"
)

type NativeGrant added in v0.100.0

type NativeGrant struct {
	Source NativeGrantSource
	Route  NativeRoute
	// Via is the chain of role names from the principal (excluded) to the role
	// holding the privilege (included). Empty for the principal's own.
	Via        []string
	Confidence NativeConfidence
}

NativeGrant is one reason a principal holds a privilege.

type NativeGrantSource added in v0.100.0

type NativeGrantSource string

NativeGrantSource is the kind of catalog fact a privilege comes from.

const (
	// NativeFromDirect is a privilege granted to the principal itself.
	NativeFromDirect NativeGrantSource = "direct"
	// NativeFromMembership is a privilege granted to a role the principal is a
	// member of, possibly through a chain (see NativeGrant.Via).
	NativeFromMembership NativeGrantSource = "membership"
	// NativeFromEveryone is a privilege granted to every principal.
	NativeFromEveryone NativeGrantSource = "everyone"
	// NativeFromOwnership is a privilege the collection's owner holds.
	NativeFromOwnership NativeGrantSource = "ownership"
	// NativeFromSuperuser is a privilege a superuser holds on everything.
	NativeFromSuperuser NativeGrantSource = "superuser"
	// NativeFromBuiltinRole is a privilege an engine-defined role holds on
	// every collection.
	NativeFromBuiltinRole NativeGrantSource = "builtin-role"
)

type NativeNamespaceAccess added in v0.100.0

type NativeNamespaceAccess string

NativeNamespaceAccess is whether a principal can reach the collection's namespace.

const (
	// NativeNamespaceGranted means the principal can reach the namespace.
	NativeNamespaceGranted NativeNamespaceAccess = "granted"
	// NativeNamespaceMissing means the principal holds privileges on the
	// collection but cannot use them, because it cannot reach the namespace.
	NativeNamespaceMissing NativeNamespaceAccess = "missing"
	// NativeNamespaceUnknown means the namespace's access could not be read.
	NativeNamespaceUnknown NativeNamespaceAccess = "unknown"
	// NativeNamespaceNotApplicable means the engine has no separate gate on
	// reaching a namespace (a namespace grant, where one exists, is reported
	// as a grant instead).
	NativeNamespaceNotApplicable NativeNamespaceAccess = "not-applicable"
)

type NativeOperation added in v0.100.0

type NativeOperation string

NativeOperation is a data operation a native privilege allows.

const (
	// NativeRead reads rows (SELECT).
	NativeRead NativeOperation = "read"
	// NativeInsert adds rows.
	NativeInsert NativeOperation = "insert"
	// NativeUpdate changes rows.
	NativeUpdate NativeOperation = "update"
	// NativeDelete removes rows.
	NativeDelete NativeOperation = "delete"
	// NativeTruncate removes every row at once.
	NativeTruncate NativeOperation = "truncate"
)

type NativePrincipal added in v0.100.0

type NativePrincipal struct {
	// Name is the engine's name of the principal. Mapping it to a person is the
	// caller's business.
	Name string
	// Kind classifies the principal, including whether it can log in.
	Kind NativePrincipalKind
	// Superuser is true when the principal bypasses every privilege check.
	Superuser bool
	// Owner is true when the principal owns the collection.
	Owner bool
	// Privileges are the privileges the principal can exercise, each with why.
	Privileges []NativePrivilege
	// RowSecurity states whether row security filters this principal's rows.
	RowSecurity NativeRowSecurityEffect
	// NamespaceAccess states whether the principal can reach the namespace
	// (schema) holding the collection, without which its privileges cannot be
	// used.
	NamespaceAccess NativeNamespaceAccess
	// Confidence is the weakest confidence of the principal's privileges.
	Confidence NativeConfidence
}

NativePrincipal is one principal and the privileges it can exercise on the collection.

type NativePrincipalKind added in v0.100.0

type NativePrincipalKind string

NativePrincipalKind classifies a principal. The kind also says whether the principal can open a session itself: only NativeLogin can.

const (
	// NativeLogin is an account or role that can open a session itself.
	NativeLogin NativePrincipalKind = "login"
	// NativeGroup is a role that cannot open a session; it is reached only
	// through membership.
	NativeGroup NativePrincipalKind = "group"
	// NativeEveryone is the pseudo-principal every account belongs to,
	// including accounts created later.
	NativeEveryone NativePrincipalKind = "everyone"
)

type NativePrivilege added in v0.100.0

type NativePrivilege struct {
	Operation NativeOperation
	// Fields is empty for the whole collection; otherwise the privilege covers
	// only these fields (columns).
	Fields []string
	// Confidence is the strongest confidence among Grants.
	Confidence NativeConfidence
	// Grants are every reason the principal holds the privilege.
	Grants []NativeGrant
}

NativePrivilege is one operation a principal can exercise.

type NativeRoute added in v0.100.0

type NativeRoute string

NativeRoute is how a principal exercises a privilege held by another role.

const (
	// NativeRouteSelf is the principal's own privilege.
	NativeRouteSelf NativeRoute = "self"
	// NativeRouteInherited is used automatically through membership.
	NativeRouteInherited NativeRoute = "inherited"
	// NativeRouteSwitchRole is usable after the principal switches its session
	// to another role it is a member of.
	NativeRouteSwitchRole NativeRoute = "switch-role"
	// NativeRouteSelfGrant is usable after the principal grants itself
	// membership it administers. A potential, not a current, privilege.
	NativeRouteSelfGrant NativeRoute = "self-grant"
)

type NativeRowSecurity added in v0.100.0

type NativeRowSecurity struct {
	// Enabled is true when rows are filtered per principal.
	Enabled bool
	// AppliesToOwner is true when the owner is filtered too; false where the
	// engine makes no such distinction.
	AppliesToOwner bool
}

NativeRowSecurity is the collection's row-security state.

type NativeRowSecurityEffect added in v0.100.0

type NativeRowSecurityEffect string

NativeRowSecurityEffect is how row security affects one principal.

const (
	// NativeRowSecurityOff means the collection has no row security.
	NativeRowSecurityOff NativeRowSecurityEffect = "off"
	// NativeRowSecurityApplies means the principal sees only the rows the
	// engine's row-security rules let it see.
	NativeRowSecurityApplies NativeRowSecurityEffect = "applies"
	// NativeRowSecurityBypassed means the principal sees every row.
	NativeRowSecurityBypassed NativeRowSecurityEffect = "bypassed"
)

type NotSupportedError

type NotSupportedError struct {
	// Op names the operation that was not supported (e.g.
	// "CreateCollection", "DescribeCollection", "DropIndex").
	Op string
	// Backend optionally identifies the driver (e.g.
	// "dalgo2sql/sqlite"). When the helper function constructs the
	// error after a failed type assertion, it sets Backend from
	// db.Adapter().Name() if Adapter() returns a non-nil dal.Adapter;
	// otherwise Backend is left empty.
	Backend string
	// Reason is an optional human-readable explanation.
	Reason string
}

NotSupportedError is the typed error returned by dbschema and ddl helper functions when a driver does not support a given operation (either because the driver does not implement the relevant capability interface at all, or because the specific operation is unsupported).

NotSupportedError.Unwrap returns the existing dal.ErrNotSupported sentinel so callers can do a coarse errors.Is(err, dal.ErrNotSupported) check or extract detail via errors.As(err, &ue) with ue of type *dbschema.NotSupportedError.

The same error type is used by both the read side (this package's helpers) and the write side ([ddl] package helpers) so consumers have a single typed error to handle across the whole DDL surface.

func (*NotSupportedError) Error

func (e *NotSupportedError) Error() string

Error returns a readable single-line message.

func (*NotSupportedError) Unwrap

func (e *NotSupportedError) Unwrap() error

Unwrap returns the dal.ErrNotSupported sentinel so callers can use errors.Is(err, dal.ErrNotSupported) for a coarse check.

type Precision

type Precision struct {
	Total int
	Scale int
}

Precision describes decimal precision. Total is the total number of significant digits; Scale is the number of digits to the right of the decimal point. Both are non-negative; the package does NOT enforce Scale <= Total.

type Referrer

type Referrer struct {
	// Collection identifies the referencing collection.
	Collection dal.CollectionRef
	// Fields lists the fields in Collection that reference back to
	// the queried collection.
	Fields []dal.FieldName
}

Referrer describes one collection that references the queried collection via a foreign key.

func ListReferrers

func ListReferrers(ctx context.Context, db dal.DB, ref *dal.CollectionRef) ([]Referrer, error)

ListReferrers resolves db to a SchemaReader (see dal.As) and delegates.

type SchemaReader

type SchemaReader interface {
	// ListCollections returns the collections (tables) accessible to
	// db. The optional parent key narrows scope when the backend
	// supports hierarchical addressing (e.g. SQL catalog/schema).
	// Pass nil for "everything visible."
	ListCollections(ctx context.Context, parent *record.Key) ([]dal.CollectionRef, error)

	// DescribeCollection returns the structural definition of one
	// collection, including its fields, primary key, inline indexes,
	// and any outgoing foreign keys the provider can discover.
	DescribeCollection(ctx context.Context, ref *dal.CollectionRef) (*CollectionDef, error)

	// ListIndexes returns the indexes on a collection. The returned
	// slice MAY include indexes already reported inline via
	// DescribeCollection's Indexes field.
	ListIndexes(ctx context.Context, ref *dal.CollectionRef) ([]IndexDef, error)

	// ListConstraints is OPTIONAL. Drivers that do not support
	// constraint introspection MUST return *NotSupportedError.
	ListConstraints(ctx context.Context, ref *dal.CollectionRef) ([]ConstraintDef, error)

	// ListReferrers is OPTIONAL. Drivers MAY return
	// *NotSupportedError. Returns the collections that reference ref
	// via foreign keys.
	ListReferrers(ctx context.Context, ref *dal.CollectionRef) ([]Referrer, error)
}

SchemaReader is the capability interface for schema introspection. Drivers that support introspection (SQL backends via information_schema / SQLite pragmas, Firestore via the admin API, etc.) opt in by implementing SchemaReader on their dal.DB value or a related type reachable via type assertion. Drivers that don't implement SchemaReader simply don't satisfy it; the top-level helper functions return *NotSupportedError on the failed assertion.

ListCollections, DescribeCollection, and ListIndexes are REQUIRED for drivers that implement SchemaReader at all. ListConstraints and ListReferrers are OPTIONAL: drivers whose backend lacks the concept (e.g. Firestore has no SQL-style constraints) MUST return *NotSupportedError from those methods. The interface satisfaction is structural — all five methods must be present for a driver to satisfy SchemaReader; runtime behavior decides which methods actually do work.

type SourceColumnDef added in v0.93.0

type SourceColumnDef struct {
	Name               string  `json:"name"`
	DeclaredType       string  `json:"declaredType"`
	NotNull            bool    `json:"notNull"`
	DefaultSQL         *string `json:"defaultSql,omitempty"`
	PrimaryKeyPosition int     `json:"primaryKeyPosition,omitempty"`
}

SourceColumnDef is one source column in declared order. NotNull records the source catalog flag, which may differ from effective primary-key null semantics. A nil DefaultSQL means no DEFAULT clause; a pointer to "NULL" means an explicit DEFAULT NULL.

type SourceConstraintChecker added in v0.93.0

type SourceConstraintChecker interface {
	// CheckSourceConstraints asks the source provider to verify its stored data
	// with its native constraint semantics.
	CheckSourceConstraints(ctx context.Context) error
}

SourceConstraintChecker is an optional pre-export capability. It asks the source provider to verify its own stored data with its native constraint semantics, including affinity and collation where applicable. A nil error means only that the source snapshot passed that provider's checks; it does not claim that an export destination enforces equivalent constraints.

type SourceDefinition added in v0.93.0

type SourceDefinition struct {
	Dialect   string            `json:"dialect"`
	CreateSQL string            `json:"createSql,omitempty"`
	Columns   []SourceColumnDef `json:"columns,omitempty"`
	Indexes   []SourceIndexDef  `json:"indexes,omitempty"`
}

SourceDefinition preserves provider-native schema facts for an export. Dialect identifies the SQL dialect of CreateSQL and index statements. These statements are provenance only: consumers must not execute them without their own trust and dialect checks. Providers may omit this field when they cannot inspect native schema.

type SourceIndexColumnDef added in v0.93.0

type SourceIndexColumnDef struct {
	Position   int     `json:"position"`
	Name       *string `json:"name,omitempty"`
	Key        bool    `json:"key"`
	Descending bool    `json:"descending,omitempty"`
	Collation  string  `json:"collation,omitempty"`
}

SourceIndexColumnDef is one index term in storage order. Name is nil for expression terms and rowid. Position records the provider's term ordinal; Key distinguishes key terms from included or auxiliary terms.

type SourceIndexDef added in v0.93.0

type SourceIndexDef struct {
	Name      string                 `json:"name"`
	Unique    bool                   `json:"unique"`
	Origin    string                 `json:"origin,omitempty"`
	Partial   bool                   `json:"partial,omitempty"`
	CreateSQL string                 `json:"createSql,omitempty"`
	Columns   []SourceIndexColumnDef `json:"columns,omitempty"`
}

SourceIndexDef retains the catalog shape of an index, including expression and partial indexes that portable IndexDef cannot fully describe. CreateSQL is empty for engine-generated indexes such as SQLite autoindexes.

type SourceRow added in v0.93.0

type SourceRow struct {
	Values         map[string]any    `json:"values"`
	StorageClasses map[string]string `json:"storageClasses,omitempty"`
}

SourceRow is one source record with its original storage classes. Values may use a lossless transport representation (for example, a canonical decimal string for a SQLite REAL stored in a declared NUMERIC column), while StorageClasses retains the original source storage class per field.

type SourceRowCursor added in v0.93.0

type SourceRowCursor interface {
	// Next returns the next source row, or io.EOF after the last row.
	Next() (SourceRow, error)
	// Close closes the cursor.
	Close() error
}

SourceRowCursor streams source rows without buffering the collection. Next returns io.EOF after the last row. The caller must Close the cursor.

type SourceRowsReader added in v0.93.0

type SourceRowsReader interface {
	// OpenSourceRows opens a cursor over the source rows of ref.
	OpenSourceRows(ctx context.Context, ref *dal.CollectionRef) (SourceRowCursor, error)
}

SourceRowsReader is an optional export capability for drivers that can preserve source storage classes more faithfully than a general query. Generic exporters may fall back to dal.QueryExecutor when it is absent.

type SourceViewDef added in v0.93.0

type SourceViewDef struct {
	Name      string   `json:"name"`
	Columns   []string `json:"columns,omitempty"`
	CreateSQL string   `json:"createSql,omitempty"`
}

SourceViewDef retains a provider's view definition as metadata only. A view is not a collection and need not have materialized rows in an export.

type SourceViewReader added in v0.93.0

type SourceViewReader interface {
	// ListSourceViews returns the provider's view definitions.
	ListSourceViews(ctx context.Context) ([]SourceViewDef, error)
}

SourceViewReader is an optional schema-introspection capability. It is separate from SchemaReader so existing drivers need no API changes.

type Type

type Type int8

Type is the portable column-type enumeration. Drivers translate these to engine-specific column types when emitting DDL.

The zero value is Null so an unset FieldDef.Type is meaningful rather than silently Bool.

const (
	// Null indicates an unset or null-typed field. Also the zero value of Type.
	Null Type = iota
	// Bool is a boolean column.
	Bool
	// Int is an integer column. Drivers pick an appropriate width
	// (e.g. INT, BIGINT) based on optional Length hints.
	Int
	// Float is a floating-point column.
	Float
	// String is a textual column. Drivers honor optional Length
	// hints (e.g. VARCHAR(N) on PostgreSQL).
	String
	// Bytes is a binary blob column.
	Bytes
	// Time is a date-time column.
	Time
	// Decimal is a fixed-point numeric column. Drivers honor optional
	// Precision hints (e.g. NUMERIC(total, scale) on PostgreSQL).
	Decimal
)

func (Type) String

func (t Type) String() string

String returns a non-empty lowercase identifier suitable for diagnostic output. The returned strings are pairwise distinct.

Jump to

Keyboard shortcuts

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