dataplane

package
v0.2.10 Latest Latest
Warning

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

Go to latest
Published: Nov 8, 2026 License: MIT Imports: 14 Imported by: 0

Documentation

Overview

Package dataplane defines the narrow machine-readable contracts consumed by the controller. It deliberately does not import the full Ptah module.

Index

Constants

View Source
const (
	PlanFormatVersion     = 1
	SchemaArtifactType    = "application/vnd.stokaro.ptah.schema.v1"
	MigrationArtifactType = "application/vnd.stokaro.ptah.migrations.v1"

	// DriftFindingVocabularyVersion identifies the closed category vocabulary
	// accepted from native drift reports. Extending this vocabulary is a runner
	// protocol change: an older controller must reject, rather than publish, a
	// category whose disclosure contract it does not understand.
	//
	// Nothing reads this number. The refusal it describes is delivered by the
	// vocabulary itself, at both ends: a controller decoding a report and a
	// controller parsing a result frame each ask IsKnownDriftFindingCategory,
	// and an unknown category is refused there rather than compared here.
	//
	// Version 2 is Ptah v0.14.0's: the feature categories, which may carry a
	// kind, replace the per-object categories of extensions and YDB objects.
	// Version 3 is Ptah v0.16.0's, which compares more kinds of object and
	// adds their categories: comments, grants and grant options, index
	// visibility and renames, materialized views, role memberships,
	// sequences, triggers, views and validated constraints.
	// Version 4 is Ptah v0.23.0's: a column whose type narrows and a column
	// that loses its identity get categories of their own beside
	// columns_modified.
	DriftFindingVocabularyVersion = 4

	// SupportedDriftContract is the version of the document `ptah schema
	// drift --format json` prints that this operator reads, and DriftCommand
	// the command that document names. Ptah gave the report a version in
	// stokaro/ptah#5173, together with the failure document the command now
	// prints in its place. A report without one comes from an earlier Ptah and
	// is refused.
	SupportedDriftContract = 1
	DriftCommand           = "schema drift"

	// MaxDriftFindingKindBytes bounds the kind a qualified category carries.
	// The longest qualified category is 25 bytes before the kind, so a category
	// the vocabulary admits is at most 153 bytes.
	MaxDriftFindingKindBytes = 128
)
View Source
const (
	// SupportedMigrationStatusContract and SupportedMigrationRunContract are the
	// Ptah machine-contract versions this operator reads.
	//
	// A document announcing another version is refused rather than read: the
	// fields this operator knows may still be present and may already mean
	// something else, and a history read under the wrong contract is a history
	// nobody checked.
	//
	// Version 2 of both is stokaro/ptah#5173's. A status run that cannot read
	// the history now prints a failure document in the status contract's
	// version, which a version 1 reader would take for a database with nothing
	// applied; a run document carries error as an object with a kind, and a
	// run that stopped before it selected anything is failed with nothing
	// planned and no status.
	SupportedMigrationStatusContract = 2
	SupportedMigrationRunContract    = 2

	// MigrationStatusCommand and MigrationRunCommand are the commands the two
	// documents name. A status embedded in a run document names none.
	MigrationStatusCommand = "migrations status"
	MigrationRunCommand    = "migrations up"

	// Migration states a status document reports per migration.
	MigrationStateApplied           = "applied"
	MigrationStateModified          = "modified"
	MigrationStateDirty             = "dirty"
	MigrationStatePending           = "pending"
	MigrationStateOutOfOrder        = "out-of-order"
	MigrationStateCheckpointCovered = "checkpoint-covered"
)
View Source
const (
	MigrationOutcomeUpToDate = "up-to-date"
	MigrationOutcomeApplied  = "applied"
	MigrationOutcomeDryRun   = "dry-run"
	MigrationOutcomeFailed   = "failed"
	MigrationOutcomePartial  = "partial"
	MigrationOutcomeUnknown  = "unknown"
)

Outcomes a run document reports.

View Source
const (
	MaxMigrationDescriptionBytes = 255
	MaxMigrationChecksumBytes    = 128
)

Bounds on what a record names. A description is the rest of a file name, which no file system lets exceed 255 bytes, and a checksum is a digest spelled out; anything longer did not come from a migration file.

View Source
const (
	// PrivilegeGrant is a privilege granted on an object, default privileges
	// included.
	PrivilegeGrant = "Grant"
	// PrivilegeRevoke is a privilege revoked from an object.
	PrivilegeRevoke = "Revoke"
	// PrivilegeRoleMembership is a role granted to, or revoked from, another
	// role or user.
	PrivilegeRoleMembership = "RoleMembership"
	// PrivilegeRole is a role, user or group created, altered or dropped -- its
	// attributes, its settings, its existence -- or assumed for the rest of the
	// session with SET ROLE or SET SESSION AUTHORIZATION.
	PrivilegeRole = "Role"
	// PrivilegeOwnership is an object given to another owner.
	PrivilegeOwnership = "Ownership"
	// PrivilegeRowSecurityPolicy is a row-security policy created, altered or
	// dropped, or row security switched off or unforced on a table.
	PrivilegeRowSecurityPolicy = "RowSecurityPolicy"
	// PrivilegeSecurityDefiner is code set to run with its owner's rights
	// rather than its caller's. A MySQL or MariaDB routine does that unless it
	// says SQL SECURITY INVOKER, so a routine that names no mode counts.
	PrivilegeSecurityDefiner = "SecurityDefiner"
	// PrivilegeDefiner is a MySQL DEFINER clause, which names the account a
	// view, routine, trigger or event runs as.
	PrivilegeDefiner = "Definer"
	// PrivilegeFunctionReplacement is CREATE OR REPLACE of a function or a
	// procedure, which can rewrite code that policies, triggers and other
	// roles already call.
	PrivilegeFunctionReplacement = "FunctionReplacement"
)

The kinds of authority a plan statement can change. Each names a kind of change and never its object, its grantee or its text: the kinds are copied into the plan and into status, where a role name or a function body does not belong.

Extending this list is an API change: the CRD enumerates the same values, and a stored plan that names a kind the schema does not list stops validating.

View Source
const (
	// SupportedSchemaPlanContract and SupportedSchemaApplyContract are the
	// versions of the documents `ptah schema plan --json` and `ptah schema
	// apply --json` print that this operator reads.
	//
	// Ptah raises a version when a field changes meaning or leaves, and when an
	// outcome gains a value. A document announcing another version is refused
	// rather than read for the fields this operator recognizes, because those
	// fields may already mean something else.
	//
	// Plan version 3 and apply version 4 are stokaro/ptah#5173's. Each carries
	// error as an object, the kind of a failure to open the target and Ptah's
	// message, where the versions before carried the message alone, and names
	// its command. Every outcome, the plan digest, the units an apply lists and
	// the refusal mean what they meant in plan version 2 and apply version 3.
	SupportedSchemaPlanContract  = 3
	SupportedSchemaApplyContract = 4

	// SchemaPlanCommand and SchemaApplyCommand are the commands the two
	// documents name. A document naming another is refused.
	SchemaPlanCommand  = "schema plan"
	SchemaApplyCommand = "schema apply"
)
View Source
const (
	SchemaPlanOutcomeChanges   = "changes"
	SchemaPlanOutcomeNoChanges = "no-changes"
	SchemaPlanOutcomeRefused   = "refused"
	SchemaPlanOutcomeFailed    = "failed"
)

Outcomes a plan document reports.

View Source
const (
	SchemaApplyOutcomeApplied   = "applied"
	SchemaApplyOutcomeNoChanges = "no-changes"
	SchemaApplyOutcomeDryRun    = "dry-run"
	SchemaApplyOutcomeCanceled  = "canceled"
	SchemaApplyOutcomeRefused   = "refused"
	SchemaApplyOutcomeFailed    = "failed"
	SchemaApplyOutcomeUnknown   = "unknown"
)

Outcomes an apply document reports. Refused and failed say that nothing reached the target; unknown says the statements were sent and the run returned an error.

View Source
const (
	SchemaRefusalStalePlan      = "stale-plan"
	SchemaRefusalProtectedTable = "protected-table"
	// SchemaRefusalDeclarationRefused is Ptah v0.23.0's refusal of a desired
	// schema whose declarations contradict each other, such as a foreign key
	// that references an unknown table. Ptah v0.22.0 reported the same fault
	// as a failed plan, with the same error message.
	SchemaRefusalDeclarationRefused = "declaration-refused"
)

Refusal codes this operator acts on. Ptah may add codes without raising the contract version, since every refusal means nothing reached the target, so a code outside this list is read as a refusal of no particular kind rather than refused as a document.

View Source
const (
	UnseenTables      = "tables"
	UnseenViews       = "views"
	UnseenConstraints = "constraints"
	UnseenTriggers    = "triggers"
	UnseenRoutines    = "routines"
)

The kinds of object a missing_privileges entry names, in the order the runner's sentence lists them. Ptah's tables entry covers the list of views as well; its views entry is about their definitions.

View Source
const DriftFindingKindPattern = `[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)+(/[A-Za-z0-9_-][A-Za-z0-9._-]*)+`

DriftFindingKindPattern is the unanchored form of driftFindingKindPattern, which the PtahSchema status patterns for a finding's category and an inventory entry's kind repeat.

View Source
const MaxDriftInventoryEntries = 128

MaxDriftInventoryEntries bounds a report's inventory, as status.target.inventory bounds it: each kind once, stem or feature kind, and every kind the vocabulary pairs fits under it.

Variables

View Source
var ErrNativeApplyUnit = errors.New("schema apply lists an operation that is not SQL")

ErrNativeApplyUnit is a listed operation that is not SQL. This operator plans and reviews SQL statements, so it cannot account for one.

Functions

func DialectMatches

func DialectMatches(engine, dialect string) bool

DialectMatches reports whether a Ptah report dialect belongs to the explicitly configured database engine.

func DriftFindingCategories

func DriftFindingCategories() []string

DriftFindingCategories returns a copy of the closed machine vocabulary's fixed categories.

It is the list the pinned Ptah can emit. support/ptah-drift-categories.json records that list, and hack/ptahdriftcategories holds the record to the pinned source and this list to the record. An unknown category is refused rather than published or dropped. The status pattern could not store it, and leaving it out would understate the report's count and its highest severity.

Changing the list moves DriftFindingVocabularyVersion, the PtahSchema status pattern and the CRD schema version together. The frame version stays: a controller that predates a category refuses a frame carrying it, which is the refusal a version mismatch would give.

func DriftFindingQualifiedCategories added in v0.2.6

func DriftFindingQualifiedCategories() []string

DriftFindingQualifiedCategories returns a copy of the categories a report writes either bare or followed by ":<kind>".

func DriftReportDigest

func DriftReportDigest(report DriftReport) (string, error)

DriftReportDigest identifies the exact comparison result emitted by one drift read. It is deliberately not a database-schema fingerprint: only a native plan's from_fingerprint may authorize an Apply. The digest is useful for audit and change detection without inventing a second schema identity.

func IsKnownDriftFindingCategory

func IsKnownDriftFindingCategory(category string) bool

IsKnownDriftFindingCategory reports whether category belongs to the closed machine vocabulary: a fixed category, or a qualified one, bare or with a kind of the expected form and length.

func IsKnownDriftInventoryKind added in v0.2.8

func IsKnownDriftInventoryKind(kind string) bool

IsKnownDriftInventoryKind reports whether kind is one an inventory counts: the stem of a pair of fixed finding categories, an addition and a removal, or the kind a feature owner's qualified categories carry, such as ptah.run/pgextension/extension-change (stokaro/ptah#5149).

func IsKnownMigrationOutcome

func IsKnownMigrationOutcome(outcome string) bool

IsKnownMigrationOutcome reports whether outcome is one a run document may carry. The runner's termination summary repeats a run's outcome, and it is held to the same set the document was.

func IsKnownPrivilegeChange

func IsKnownPrivilegeChange(kind string) bool

IsKnownPrivilegeChange reports whether kind belongs to the vocabulary.

func MigrationFilesProblem added in v0.2.10

func MigrationFilesProblem(stdout []byte) (string, bool)

MigrationFilesProblem reads the failure document `migrations status --json` printed about a migration directory it could not load. Any other failure, including one that names a target failure kind, is not about the files.

func PrivilegeChangeKinds

func PrivilegeChangeKinds() []string

PrivilegeChangeKinds returns a copy of the closed vocabulary, in the order a plan lists its kinds.

func SchemaSourceProblem added in v0.2.10

func SchemaSourceProblem(stdout []byte, engine string) (string, bool)

SchemaSourceProblem reads what `schema validate` printed about a desired schema it could not load: `<dialect>: source: <reason>`, in the dialect the engine names. The reason is as Ptah printed it, across lines if it spans them: what leaves the runner is the runner's to make, after it has redacted the words.

Only that shape is read. Validate also reports structural problems, a `schema` or an `index` line, and `schema drift` and `schema plan` do not refuse all of those, so such a line does not say why a command failed. A load failure does: both commands load the same file before they compare anything.

func SchemaStructuralProblem added in v0.2.10

func SchemaStructuralProblem(stdout []byte, engine, failed string) (string, bool)

SchemaStructuralProblem reads what `schema validate` printed about a schema as a whole, such as a foreign key into a table it does not declare, when that fault is the one the command that failed stopped on: a `<dialect>: schema: <fault>` line, in the dialect the engine names, whose words end failed, the sentence the failed command's own document holds. Validate prints an index line first for each index it refuses, and the fault runs to the end of its output.

Validate reports a fault of the file whether or not it stopped anything, and the command that failed may have stopped on the database or on another fault validate does not know. Comparing the words is what ties the two: drift and plan run the validator that wrote this line, and wrap its sentence and nothing else around it. An index line has no such tie, so it is not read: drift accepts an index on a column no table declares, and on a table none declares it fails in other words.

failed is compared and never returned. Its command had a connection, so it could quote the database. What is returned comes from a run that had none.

func StatementsSQL

func StatementsSQL(plan PlanFile) string

StatementsSQL renders a plan's statements as they were stored.

One statement per entry, in the order the plan holds them, each terminated once. Nothing is re-split on a semicolon: a statement may carry one inside a string, a comment or a function body, and splitting there would hand a reader SQL the plan never held.

func UnseenObjectsDescription added in v0.2.10

func UnseenObjectsDescription(objects []string) string

UnseenObjectsDescription is the runner's sentence for a permission_denied failure that names what the account cannot see. Like every description it is fixed text: the kinds come from the vocabulary, and no database, object or privilege Ptah named is in it. It is empty for a list ValidateUnseenObjects refuses.

func ValidateUnseenObjects added in v0.2.10

func ValidateUnseenObjects(objects []string) error

ValidateUnseenObjects refuses a list UnseenObjects could not have returned: empty, a kind outside the vocabulary, a repeated kind, or one out of order.

func VerifyRefusalDiagnostics added in v0.2.10

func VerifyRefusalDiagnostics(report VerifyReport) string

VerifyRefusalDiagnostics is what `ptah oci verify` writes to standard error when the policy refuses an artifact: the report's own findings, as one sentence and a line for each, after the report on standard output and before exit status 2. The harness row schema-verify-refused/verify-other-type holds this text to the pinned image.

The runner compares a verification's standard error with this and nothing looser, so a line the report does not hold is not read as a refusal.

Types

type CommandError added in v0.2.10

type CommandError struct {
	// Kind is from the vocabulary above, or a kind a later Ptah added, or
	// absent when the failure has none.
	Kind string `json:"kind,omitempty"`
	// Message is Ptah's sentence for a person. It can quote what the database
	// said, so nothing but a protected-table refusal's tables is copied from
	// it. SchemaStructuralProblem compares it with words from a run that had no
	// database, and copies none of it.
	Message string `json:"message"`
	// MissingPrivileges is what a MySQL or MariaDB account could not see when
	// Ptah reports permission_denied for a read of the target, one entry for
	// each kind of object. Ptah v0.23.0 adds it.
	MissingPrivileges []MissingPrivilege `json:"missing_privileges,omitempty"`
}

CommandError is the error object a Ptah document carries for a run that failed.

func DecodeDriftFailure added in v0.2.10

func DecodeDriftFailure(data []byte) (*CommandError, error)

DecodeDriftFailure reads the document `schema drift --format json` prints on standard output when it fails: its contract version, its command and the error, in place of the report.

func DecodeMigrationStatusFailure added in v0.2.10

func DecodeMigrationStatusFailure(data []byte) (*CommandError, error)

DecodeMigrationStatusFailure reads the document `migrations status --json` prints on standard output when it cannot read the history.

func (*CommandError) TargetFailure added in v0.2.10

func (e *CommandError) TargetFailure() (TargetFailureKind, bool)

TargetFailure is the kind of the error, when it is one of the vocabulary. A nil error has none.

func (*CommandError) UnseenObjects added in v0.2.10

func (e *CommandError) UnseenObjects() ([]string, bool)

UnseenObjects is the kinds of object a permission_denied failure says the account cannot see, in vocabulary order and each once. It is false when the failure is not permission_denied, names no kind, or names one outside the vocabulary: a list without that kind would understate what is missing, so the failure then reads as the plain permission_denied.

type DriftFinding

type DriftFinding struct {
	Category string `json:"category"`
	Count    int32  `json:"count"`
	Severity string `json:"severity"`
}

type DriftInventoryEntry added in v0.2.8

type DriftInventoryEntry struct {
	Kind     string `json:"kind"`
	Desired  int32  `json:"desired"`
	Observed int32  `json:"observed"`
}

DriftInventoryEntry counts one kind of object on both sides of the comparison the drift report made: how many the desired schema declares and how many the database holds, within the compared scope. Kind joins the inventory to the findings: "tables" is the stem of tables_added and tables_removed, and "ptah.run/pgextension/extension-change" is the kind feature_changes:ptah.run/pgextension/extension-change carries. It names no object.

The counts are int32, as status stores them: a count past that fails to decode, and the report with it.

type DriftReport

type DriftReport struct {
	ContractVersion  int             `json:"contract_version"`
	Command          string          `json:"command"`
	Drift            bool            `json:"drift"`
	Failed           bool            `json:"failed"`
	FailureThreshold string          `json:"failure_threshold"`
	HighestSeverity  string          `json:"highest_severity"`
	Dialect          string          `json:"dialect,omitempty"`
	Sources          string          `json:"sources,omitempty"`
	DatabaseURL      string          `json:"database_url,omitempty"`
	IgnoredTables    []string        `json:"ignored_tables,omitempty"`
	Findings         []DriftFinding  `json:"findings,omitempty"`
	Diff             json.RawMessage `json:"diff,omitempty"`
	// Inventory is absent from a Ptah that does not count, which the
	// operator reads as a report with no inventory rather than an empty one.
	Inventory []DriftInventoryEntry `json:"inventory,omitempty"`
	// Error is present only on the failure document the command prints in
	// place of a report, which DecodeDrift refuses and DecodeDriftFailure
	// reads.
	Error *CommandError `json:"error,omitempty"`
}

func DecodeDrift

func DecodeDrift(data []byte, exitCode int) (DriftReport, error)

DecodeDrift maps the CLI's configured failure threshold into a domain result. Drift may be reported without failing the command.

type GitPullReport added in v0.2.7

type GitPullReport struct {
	Source        string          `json:"source"`
	Reference     string          `json:"reference"`
	Commit        string          `json:"commit"`
	Path          string          `json:"path"`
	ContentDigest string          `json:"content_digest"`
	Files         []GitPulledFile `json:"files"`
	Written       []string        `json:"written"`
}

GitPullReport is the document `ptah schema pull` and `ptah migrations pull` print with --json for a git+https:// or git+ssh:// reference.

func DecodeGitPull added in v0.2.7

func DecodeGitPull(data []byte, reference, selected string) (GitPullReport, error)

DecodeGitPull reads a Git pull's report and holds it to the pull it answers: the reference and the path asked for, a full commit id, and a content digest the listed files give. A report that names a digest its own file list does not give is refused, so the digest bound to a plan is the one the files on disk were written from.

type GitPulledFile added in v0.2.7

type GitPulledFile struct {
	Path   string `json:"path"`
	Size   int64  `json:"size"`
	SHA256 string `json:"sha256"`
}

GitPulledFile is one file a Git pull read.

type InspectReport

type InspectReport struct {
	Reference       string `json:"reference"`
	PinnedReference string `json:"pinned_reference"`
	Digest          string `json:"digest"`
	MediaType       string `json:"media_type"`
	Size            int64  `json:"size"`
	ArtifactType    string `json:"artifact_type"`
}

func DecodeInspect

func DecodeInspect(data []byte) (InspectReport, error)

type MigrationDirty

type MigrationDirty struct {
	Version int64  `json:"version"`
	Applied int    `json:"applied"`
	Total   int    `json:"total"`
	Error   string `json:"error,omitempty"`
}

MigrationDirty is the revision row a failed or interrupted run left behind.

type MigrationRecord

type MigrationRecord struct {
	Version         int64  `json:"version"`
	VersionKey      string `json:"version_key,omitempty"`
	Description     string `json:"description,omitempty"`
	Checksum        string `json:"checksum,omitempty"`
	AppliedChecksum string `json:"applied_checksum,omitempty"`
	Checkpoint      bool   `json:"checkpoint,omitempty"`
	TransactionMode string `json:"transaction_mode,omitempty"`
	// AppliedAt is when the migration's revision row was written, and
	// ExecutionMs how long it ran in whole milliseconds, as the row recorded
	// them. Ptah reports both only for a row that exists, and no duration for
	// a revision table too old to record one. Neither is part of the history
	// fingerprint: a plan's premise is which migrations are applied, not when.
	AppliedAt   *time.Time `json:"applied_at,omitempty"`
	ExecutionMs *int64     `json:"execution_time_ms,omitempty"`
	State       string     `json:"state"`
}

MigrationRecord is one migration of the artifact as the database accounts for it.

func (MigrationRecord) HasRevisionRow added in v0.2.7

func (m MigrationRecord) HasRevisionRow() bool

HasRevisionRow reports whether the database holds a revision row for the record: an applied migration, a modified one, or the dirty one a failed run left behind.

type MigrationRunFailure added in v0.2.6

type MigrationRunFailure struct {
	Version    int64 `json:"version"`
	Statement  int   `json:"statement"`
	Statements int   `json:"statements"`
	// Commit is true when every statement ran and the commit that ends them
	// failed, as a deferred constraint does. No statement is to blame then,
	// and Statement is 0: that is Ptah's documented contract (docs/
	// exit_codes.md, "Where a Run Stopped", introduced in stokaro/ptah#5562).
	// Under --tx-mode all the one commit ends every selected migration, and
	// Version names the last of them.
	Commit bool `json:"commit,omitempty"`
	// SQLState is empty when the server gave no answer, and ErrorNumber is
	// zero on every protocol but MySQL's.
	SQLState    string `json:"sqlstate,omitempty"`
	ErrorNumber int    `json:"error_number,omitempty"`
}

MigrationRunFailure is the statement a run stopped at and the code the database answered with. Ptah writes it when a statement reached the database and failed, and since v0.23.0 also when the statements ran and the commit that ends them failed. Unlike Error's message it carries no text, so it names no row and may reach status and Events (#69, #678).

type MigrationRunReport

type MigrationRunReport struct {
	ContractVersion int     `json:"contract_version"`
	Direction       string  `json:"direction"`
	Outcome         string  `json:"outcome"`
	Planned         []int64 `json:"planned,omitempty"`
	Applied         []int64 `json:"applied,omitempty"`
	// Error is why the run failed. Its message can quote a row, so the runner
	// reads its kind and drops the object before the report reaches a frame.
	Error   *CommandError          `json:"error,omitempty"`
	Failure *MigrationRunFailure   `json:"failure,omitempty"`
	Status  *MigrationStatusReport `json:"status,omitempty"`
}

MigrationRunReport is Ptah's `migrations up --json` document.

func DecodeMigrationRun

func DecodeMigrationRun(data []byte) (MigrationRunReport, error)

DecodeMigrationRun reads a run document, including the status it carries.

func (MigrationRunReport) StoppedBeforeSelecting added in v0.2.10

func (r MigrationRunReport) StoppedBeforeSelecting() bool

StoppedBeforeSelecting reports a run that failed before Ptah selected any migration: it read no history, planned and applied nothing, and sent no migration statement. A target that could not be opened ends a run this way.

type MigrationStatusReport

type MigrationStatusReport struct {
	ContractVersion   int   `json:"contract_version"`
	CurrentVersion    int64 `json:"current_version"`
	CheckpointVersion int64 `json:"checkpoint_version,omitempty"`
	TotalMigrations   int   `json:"total_migrations"`
	HasPendingChanges bool  `json:"has_pending_changes"`
	// PendingMigrations is the selection Ptah itself made: the versions its
	// next run would execute, in the order it would execute them. It is not
	// the same question the per-migration states answer, and after a
	// checkpoint bootstrap the two disagree on purpose -- a version the
	// checkpoint replaced is reported pending once the bootstrap is no longer
	// what the database is doing, and Ptah's own floor still skips it.
	//
	// Carried without omitempty, because this report is decoded from Ptah and
	// encoded again into the runner's result frame, and an empty selection is
	// the answer that matters: it says the next run would execute nothing.
	// Dropped from the frame, it reaches the controller as an absent field,
	// which [MigrationStatusReport.Pending] reads as a build that reports no
	// selection at all and answers by recounting the states. Ptah declares the
	// field the same way for the same reason.
	PendingMigrations []int64           `json:"pending_migrations"`
	Migrations        []MigrationRecord `json:"migrations,omitempty"`
	DirtyRevision     *MigrationDirty   `json:"dirty_revision,omitempty"`
}

MigrationStatusReport is Ptah's `migrations status --json` document.

func DecodeMigrationStatus

func DecodeMigrationStatus(data []byte) (MigrationStatusReport, error)

DecodeMigrationStatus reads a status document and refuses everything it cannot fully account for.

The failure document `migrations status` prints when it cannot read the history is refused here, before anything reads it as a status: it carries the status contract version and none of the status fields, so it would otherwise read as a database with nothing applied. DecodeMigrationStatusFailure reads it.

func (MigrationStatusReport) LastVersion

func (r MigrationStatusReport) LastVersion() int64

LastVersion is the highest version the artifact carries, and zero for an artifact that carries none. It is the artifact's own extent: the document lists the artifact's migrations with what the database did about each, so a revision beyond this number is one the artifact cannot account for at all.

func (MigrationStatusReport) Modified

func (r MigrationStatusReport) Modified() []int64

Modified names the applied migrations whose files no longer account for them. Nothing may execute while one exists, and the controller never resolves it.

func (MigrationStatusReport) OutOfOrder

func (r MigrationStatusReport) OutOfOrder() []int64

OutOfOrder names the pending migrations that sort below a version the database has already applied. Ptah's linear execution order refuses a run while one exists, so a plan that carried them would be a decision nobody could execute.

func (MigrationStatusReport) Pending

func (r MigrationStatusReport) Pending() []int64

Pending names the versions the next run would execute, in the order Ptah would execute them.

The list is Ptah's, because deriving a second one from the per-migration states gets a database that bootstrapped from a checkpoint wrong: the versions the checkpoint replaced report themselves pending afterwards, while Ptah's own floor skips them and its selection is empty. A controller that recounted would publish a plan for migrations that cannot run, and publish it again after every run that correctly did nothing.

A document that carries no selection at all is read the old way, so a build that reports only states still resolves to a list rather than to silence.

type MissingPrivilege added in v0.2.10

type MissingPrivilege struct {
	Objects string `json:"objects"`
}

MissingPrivilege is one entry of missing_privileges. Only the kind of object is read. The entry also names the database, the objects the account could list and not read, and the privilege spelled with the database's name, and none of those may leave the Pod.

type PlanFile

type PlanFile struct {
	FormatVersion   int      `json:"format_version"`
	Name            string   `json:"name"`
	Dialect         string   `json:"dialect"`
	FromFingerprint string   `json:"from_fingerprint"`
	ToFingerprint   string   `json:"to_fingerprint"`
	Exclude         []string `json:"exclude,omitempty"`
	// SchemasBeyondURL names the schemas the source fingerprint covers that the
	// connection URL's own scope does not: a desired state that names a schema
	// other than the one a schema-scoped URL connects to. Ptah reads the same
	// set again when it verifies the plan before applying it. The operator
	// carries the plan bytes as they are and reads nothing from this field; it
	// is declared so the strict decoder accepts a plan that has it.
	SchemasBeyondURL []string `json:"schemas_beyond_url,omitempty"`
	// Scope is what the connection URL covered when Ptah computed the plan. Ptah
	// v0.19.0 records it so that a stale plan's refusal can name both scopes
	// (stokaro/ptah#5239), and it decides nothing else. The operator reads
	// nothing from it either; it is declared so the strict decoder accepts every
	// plan Ptah saves since then.
	Scope *PlanScope `json:"scope,omitempty"`
	// ManagedRows and RowsFingerprint describe the declared row sets this plan
	// read, and the state it read them in. A plan that changes declared rows
	// carries both, and a plan that changes only structure carries neither.
	//
	// They are names and a digest: a table, its key columns and the columns the
	// declaration owns, plus one fingerprint over the rows as they were. No row
	// value appears here, which is what lets the operator read them, publish
	// them and report on them while no declared value reaches status, an Event
	// or an ordinary log.
	ManagedRows     []PlanRowSet    `json:"managed_rows,omitempty"`
	RowsFingerprint string          `json:"rows_fingerprint,omitempty"`
	Destructive     bool            `json:"destructive"`
	Statements      []PlanStatement `json:"statements"`

	// PrivilegeChanges are the kinds of authority the statements change, read
	// by the operator from the SQL: grants, role membership, ownership,
	// row-security policies and definer rights. Ptah's document has no such
	// field and cannot supply one, since a plan is decoded strictly; the list
	// is the operator's own, in the order PrivilegeChangeKinds gives.
	PrivilegeChanges []string `json:"-"`
}

PlanFile is the plan document `schema plan --output` saves. It is decoded strictly: a field it does not declare refuses the plan.

A plan's annotations and a statement's inputs, which Ptah v0.17.0 writes only for an engine an executable provider serves, stay undeclared on purpose. An input names an environment variable that Ptah reads with os.LookupEnv in its own process at Apply and hands to the provider, and in an Apply Pod that environment holds the database credential, so an approved plan could name it. The operator runs PostgreSQL and MySQL, which Ptah plans without a provider, and refuses a plan that carries either field.

func DecodePlan

func DecodePlan(data []byte, expectedDialect string) (PlanFile, error)

type PlanRowSet

type PlanRowSet struct {
	Schema  string   `json:"schema,omitempty"`
	Table   string   `json:"table"`
	Keys    []string `json:"keys"`
	Columns []string `json:"columns"`
}

PlanRowSet is one declared row set a plan read: the table it owns, the columns that identify a row in it, and the columns the declaration writes.

type PlanScope added in v0.2.10

type PlanScope struct {
	Kind string `json:"kind"`
	Name string `json:"name,omitempty"`
}

PlanScope is what the URL of a saved plan covered: "realm" for every schema of a PostgreSQL database, or "schema" with the name of the one schema or MySQL database it pins.

type PlanStatement

type PlanStatement struct {
	SQL      string `json:"sql"`
	Severity string `json:"severity"`
	Reason   string `json:"reason"`
	// Transactions, Owned, Access and AccessReason are what Ptah v0.14.0
	// records on a statement a feature owner rendered: CREATE EXTENSION, or a
	// row-security policy. The strict decoder refused every such plan until
	// they were declared. The operator reads none of them and carries the plan
	// bytes as they are. Ptah folds the access assessment into Severity, and
	// refuses a plan whose severity is lower than its assessment requires each
	// time it reads one, so the plan Job's dry run checks the plan before the
	// operator publishes it. The privilege kinds are still read from the SQL.
	Transactions []string `json:"transactions,omitempty"`
	Owned        bool     `json:"owned,omitempty"`
	Access       string   `json:"access,omitempty"`
	AccessReason string   `json:"access_reason,omitempty"`
}

type ResolveReport

type ResolveReport struct {
	Reference       string `json:"reference"`
	PinnedReference string `json:"pinned_reference"`
	Digest          string `json:"digest"`
	MediaType       string `json:"media_type"`
	Size            int64  `json:"size"`
}

func DecodeResolve

func DecodeResolve(data []byte) (ResolveReport, error)

type SchemaApplyReport

type SchemaApplyReport struct {
	ContractVersion int               `json:"contract_version"`
	Command         string            `json:"command"`
	Outcome         string            `json:"outcome"`
	PlanName        string            `json:"plan_name,omitempty"`
	PlanDigest      string            `json:"plan_digest,omitempty"`
	Units           []SchemaApplyUnit `json:"units,omitempty"`
	Refusal         *SchemaRefusal    `json:"refusal,omitempty"`
	// Error is why the run failed, refused or ended unknown. Only its kind is
	// read.
	Error *CommandError `json:"error,omitempty"`
}

SchemaApplyReport is Ptah's `schema apply --json` document.

func DecodeSchemaApply

func DecodeSchemaApply(data []byte) (SchemaApplyReport, error)

DecodeSchemaApply reads one apply document under the rules DecodeSchemaPlan states.

func (SchemaApplyReport) SQLStatements added in v0.2.7

func (r SchemaApplyReport) SQLStatements() ([]string, error)

SQLStatements is the SQL of each listed unit, in order. A unit that is a native operation, or that has no SQL, is refused rather than skipped.

type SchemaApplyUnit added in v0.2.7

type SchemaApplyUnit struct {
	SQL    string          `json:"sql,omitempty"`
	Native json.RawMessage `json:"native,omitempty"`
}

SchemaApplyUnit is one planned operation an apply document lists: its SQL, or a summary of a native provider operation that has none.

type SchemaPlanReport

type SchemaPlanReport struct {
	ContractVersion int            `json:"contract_version"`
	Command         string         `json:"command"`
	Outcome         string         `json:"outcome"`
	PlanDigest      string         `json:"plan_digest,omitempty"`
	PlanPath        string         `json:"plan_path,omitempty"`
	Refusal         *SchemaRefusal `json:"refusal,omitempty"`
	// Error is why the run failed or refused. Its message is the sentence
	// Ptah printed on standard error and may quote a statement, so it is for a
	// fence refusal's tables and nothing else; its kind names a target that
	// could not be opened.
	Error *CommandError `json:"error,omitempty"`
}

SchemaPlanReport is Ptah's `schema plan --json` document.

The plan document it embeds is not declared, so it is not read: the file --output wrote is the plan, and PlanDigest is what binds the report to it.

func DecodeSchemaPlan

func DecodeSchemaPlan(data []byte) (SchemaPlanReport, error)

DecodeSchemaPlan reads one plan document and refuses anything it cannot account for: another contract version, an outcome it does not know, a second JSON value, and an outcome whose fields contradict it.

Fields it does not declare are ignored, because Ptah adds fields without raising the version.

type SchemaRefusal

type SchemaRefusal struct {
	Code string `json:"code"`
	// Tables are the fenced tables a protected-table refusal names.
	Tables []string `json:"tables,omitempty"`
	// Changed is what moved under a stale-plan refusal: "schema" or "rows".
	Changed             string `json:"changed,omitempty"`
	PlanFingerprint     string `json:"plan_fingerprint,omitempty"`
	DatabaseFingerprint string `json:"database_fingerprint,omitempty"`
}

SchemaRefusal is why a plan or an apply refused. Only the fields its code describes are set.

type TargetFailureKind added in v0.2.10

type TargetFailureKind string

TargetFailureKind names why a Ptah command could not open its connection to the target database. It is the closed vocabulary Ptah writes in the kind of a document's error object (stokaro/ptah#5173), and the only part of that object the operator reads.

The message beside it is the sentence Ptah wrote for a person, and it can quote what the database answered: a role, a host, a database name, a row. Nothing here returns it, and the runner and the controller describe a kind in sentences of their own.

const (
	// TargetDatabaseUnreachable is a server that never answered: the host did
	// not resolve, the address refused the connection, or the connection
	// timed out before the server completed it.
	TargetDatabaseUnreachable TargetFailureKind = "database_unreachable"
	// TargetAuthenticationFailed is a server that did not accept the
	// connection's credentials.
	TargetAuthenticationFailed TargetFailureKind = "authentication_failed"
	// TargetDatabaseNotFound is a server that has no database by the name
	// the connection gives.
	TargetDatabaseNotFound TargetFailureKind = "database_not_found"
	// TargetPermissionDenied is a server that accepted the credentials and
	// refused the role access to the database.
	TargetPermissionDenied TargetFailureKind = "permission_denied"
	// TargetTLSFailed is a TLS handshake that did not complete.
	TargetTLSFailed TargetFailureKind = "tls_failed"
)

The vocabulary. Ptah classifies only the failure to open the target connection, from the driver's typed errors, and leaves every other failure without a kind.

func ParseTargetFailureKind added in v0.2.10

func ParseTargetFailureKind(kind string) (TargetFailureKind, bool)

ParseTargetFailureKind returns the kind a document named, when it is one of the vocabulary. Anything else is no kind: Ptah may add a kind without raising a contract version, and a kind this operator has no sentence for is read as the failure having none, never repeated.

func TargetFailureKinds added in v0.2.10

func TargetFailureKinds() []TargetFailureKind

TargetFailureKinds returns the vocabulary in a fixed order.

func (TargetFailureKind) Description added in v0.2.10

func (k TargetFailureKind) Description() string

Description is the runner's sentence for the kind, and empty for a value outside the vocabulary.

type VerificationFinding

type VerificationFinding struct {
	Requirement string `json:"requirement"`
	Detail      string `json:"detail"`
}

type VerifyReport

type VerifyReport struct {
	Reference string                `json:"reference"`
	Digest    string                `json:"digest"`
	Satisfied []string              `json:"satisfied"`
	Findings  []VerificationFinding `json:"findings"`
}

func DecodeVerify

func DecodeVerify(data []byte) (VerifyReport, error)

Jump to

Keyboard shortcuts

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