Help us shape the future of Go! Take the 2026 Go Developer Survey

codec

package
v0.6.0 Latest Latest
Warning

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

Go to latest
Published: Nov 3, 2026 License: MIT Imports: 20 Imported by: 0

Documentation

Overview

Package codec preserves concrete Go types through the SQL value boundary. Generated model code uses these codecs for bound values and fresh hydration. Constructors describe codecs, not physical table schemas.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func CloneOptional added in v0.3.0

func CloneOptional[T any](c Codec[T], v value.Optional[T]) value.Optional[T]

CloneOptional preserves omission while applying the codec's ownership policy.

Types

type Codec

type Codec[T any] struct {
	// contains filtered or unexported fields
}

Codec binds and decodes one concrete type. Its zero value is invalid. Decode receives a driver-owned runtime value; ordinary model code retains T instead.

func Adapt

func Adapt[V, U any](base Codec[U], to func(V) U, from func(U) V) Codec[V]

Adapt changes a codec's Go representation while preserving validation, ownership, equality and sensitivity. The conversions must be lossless.

func Bool

func Bool[T ~bool]() Codec[T]

Bool accepts native driver booleans, with no truthiness or numeric conversion.

func Bytes

func Bytes[T ~[]byte]() Codec[T]

Bytes preserves a concrete []byte or named byte-slice type through PostgreSQL bytea. A non-nil empty slice is a present empty value; nil is invalid. Use Nullable(Bytes[T]()) for SQL NULL. Binding and decoding own their buffers.

func Date

func Date() Codec[temporal.Date]

Date maps a calendar date without inferring a timezone or truncating a time.

func DateTime

func DateTime() Codec[temporal.DateTime]

DateTime maps Foundry's UTC instant to PostgreSQL timestamptz.

func Decimal

func Decimal() Codec[decimal.Decimal]

Decimal uses exact text/integer driver representations. A floating-point source is never converted into an apparently exact decimal.

func Float

func Float[T floating]() Codec[T]

Float preserves the chosen approximate IEEE type. Non-finite values and narrowing overflow/underflow fail; ordinary float32 rounding is permitted.

func FoundryID added in v0.2.0

func FoundryID[M any, K comparable](seal sqlowner.MetadataSeal) Codec[K]

FoundryID adapts the shared UUID codec after validating the exact model owner. Example: FoundryID[User, model.ID[User]](sqlowner.Metadata()).

func FoundryPrimitive

func FoundryPrimitive[V any](seal sqlowner.MetadataSeal) Codec[V]

FoundryPrimitive supplies the native ORM representation adapter. Each concrete primitive encoder is shared. These representation conversions call no methods on the named application value and can use the private framework capability.

func ID

func ID[M any]() Codec[model.ID[M]]

ID retains a model owner through UUID binding and decoding. Nil UUIDs remain values, not SQL NULL. Existence and required-primary rules belong to the ORM.

func Interval

func Interval() Codec[temporal.Interval]

Interval preserves signed months, days and elapsed microseconds independently. It accepts PostgreSQL output styles without relying on session IntervalStyle. Elapsed components must fit time.Duration; unsupported values never normalize elapsed hours into calendar days merely to fit that bound.

func JSON

func JSON[T any]() Codec[value.JSON[T]]

JSON persists an immutable typed JSON snapshot as PostgreSQL JSONB. SQL NULL remains separate from an explicitly nullable JSON payload.

func LocalDateTime

func LocalDateTime() Codec[temporal.LocalDateTime]

LocalDateTime maps wall date-time components to timestamp without time zone. Driver time.Time locations are not converted: this value has no instant/zone.

func New

func New[T any](encode func(T) (driver.Value, error), decode func(any) (T, error)) Codec[T]

New is an explicit custom-codec boundary. Callbacks must be safe for concurrent use, leave inputs unchanged, and return owned values without driver byte aliases. A custom codec owns its NULL semantics; built-ins reject NULL except Nullable.

func Nullable

func Nullable[T any](base Codec[T]) Codec[value.Nullable[T]]

Nullable adds explicit SQL NULL without conflating it with T's zero value. Omitted mutation fields are handled by drafts, not by a column codec.

func Signed

func Signed[T signed]() Codec[T]

Signed checks destination width on scan. Fractional/float sources are rejected.

func String

func String[T ~string]() Codec[T]

String binds text without implicit conversions from numbers or booleans. Invalid UTF-8 and NUL fail before PostgreSQL execution.

func Time

func Time() Codec[time.Time]

Time maps time.Time to an instant (timestamptz), normalizing UTC and discarding its process-local monotonic reading. Precision below a microsecond is rejected rather than silently truncated. Supported years match Foundry temporal types.

func Unsigned

func Unsigned[T unsigned]() Codec[T]

Unsigned requires values to fit PostgreSQL's signed bigint range as well as the concrete Go destination. Use Decimal for larger exact nonnegative values.

func WallTime

func WallTime() Codec[temporal.Time]

WallTime maps a time-of-day to PostgreSQL time without time zone. Offset time, 24:00, leap seconds and sub-microsecond values are outside this contract.

func (Codec[T]) Bind

func (c Codec[T]) Bind(value T) (driver.Value, error)

Bind validates the concrete value and returns a supported SQL driver value. Nil byte slices become SQL NULL. Non-nil byte buffers returned by custom encoders are copied before publication, including non-null empty buffers. Encoder and validator failures retain their causes behind a safe diagnostic.

func (Codec[T]) Clone

func (c Codec[T]) Clone(v T) T

Clone copies a persistence value without binding, decoding or validation. Built-in binary codecs copy their buffers; immutable values are returned by value. Custom codecs retain ordinary Go value semantics: their owners must treat any referenced data as read-only. Nullable and Validated preserve this ownership policy.

func (Codec[T]) ComparesValues

func (c Codec[T]) ComparesValues() bool

ComparesValues reports whether the codec defines WithEquality.

func (Codec[T]) Decode

func (c Codec[T]) Decode(source any) (T, error)

Decode converts a driver value into an owned T. A failure returns a zero T.

func (Codec[T]) Equal

func (c Codec[T]) Equal(left, right T) (same, defined bool)

Equal reports whether two values are the same stored value under the codec's WithEquality comparison. defined is false when the codec compares bound values.

func (Codec[T]) ParameterType

func (c Codec[T]) ParameterType() ParameterType

ParameterType reports the codec's standalone SQL representation. Nullable and validated adapters preserve it; binding and decoding retain their own checks.

func (Codec[T]) Scan

func (c Codec[T]) Scan(destination *T) sql.Scanner

Scan creates a standard SQL scanner. It changes the destination only after a successful decode; a NULL or malformed value cannot partially replace it.

func (Codec[T]) SensitiveValues

func (c Codec[T]) SensitiveValues() bool

SensitiveValues reports immutable disclosure metadata without calling a codec.

func (Codec[T]) Validate

func (c Codec[T]) Validate() error

Validate checks that both codec directions are defined without invoking them. Metadata constructors use this before accepting a custom codec.

func (Codec[T]) Validated

func (c Codec[T]) Validated(validate func(T) error) Codec[T]

Validated applies one typed rule at both persistence boundaries. Generated enums use their own Validate method as the single source of membership rules.

func (Codec[T]) WithEquality

func (c Codec[T]) WithEquality(equal func(T, T) bool) Codec[T]

WithEquality compares decoded values directly for model change detection, instead of comparing their bound driver values. Use it only for a type whose binding is not deterministic, such as a randomized encryption envelope; the function must be safe for concurrent use and must not retain its inputs.

func (Codec[T]) WithParameterType

func (c Codec[T]) WithParameterType(kind ParameterType) Codec[T]

WithParameterType declares the SQL representation used by a custom codec. The caller owns compatibility between this representation and both callbacks. Invalid/unspecified kinds are rejected when compiling parameter expressions.

func (Codec[T]) WithSensitiveValues

func (c Codec[T]) WithSensitiveValues() Codec[T]

WithSensitiveValues marks persistence values that automatic disclosure paths must not export. Binding still returns the actual SQL value for deliberate database work; audit capture redacts it and cursor/identity capture rejects it. Nullable, Validated and parameter-type adapters preserve this metadata.

type ParameterType

type ParameterType uint8

ParameterType identifies the SQL representation of a standalone bound value. It does not declare a column schema. The zero value is unspecified; custom codecs must opt in before they can create typed SQL parameter expressions.

const (
	TypeBoolean ParameterType = iota + 1
	TypeInteger
	TypeFloat
	TypeText
	TypeUUID
	TypeDecimal
	TypeDate
	TypeTime
	TypeLocalDateTime
	TypeDateTime
	TypeBytes
	TypeInterval
	TypeJSON
)

Jump to

Keyboard shortcuts

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