scripts

package
v1.3.2 Latest Latest
Warning

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

Go to latest
Published: Nov 22, 2026 License: Apache-2.0 Imports: 15 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package scripts owns migration source identity, dependencies and consumed fingerprints.

Index

Constants

View Source
const (
	KindResult     = "function-result"
	KindDefinition = "function-definition"
	KindSchema     = "schema-dependency"
	// KindBuiltin is a call of server built-ins alone, such as
	// SUBSTRING(DB_NAME(), 5, 3), tracked by value.
	KindBuiltin = "builtin"
)

The kinds of observed input.

View Source
const AnalysisVersion = "7"

AnalysisVersion versions every cached analysis. Bump it whenever the analyser, the batch splitter or canonicalisation changes what it produces.

View Source
const ReadChanged = "read-changed"

ReadChanged selects a script whose read queries answer differently than when it last ran.

View Source
const SchemaWriter = "(schema)"

SchemaWriter is the writer the schema step is planned as.

Variables

This section is empty.

Functions

func AnalysisKey added in v1.3.0

func AnalysisKey(sql string, invokedModule bool) string

AnalysisKey is the content-addressed cache key of a body's analysis.

func Digest

func Digest(fields ...string) string

func InputHash

func InputHash(inputs map[string]string) string

func QuoteName

func QuoteName(name string) (string, error)

func SourceHash

func SourceHash(content string) string

func StateHash added in v1.3.0

func StateHash(s State) string

StateHash is the ledger hash of a state: its source, policy and inputs.

Types

type AfterApplyInput added in v1.3.0

type AfterApplyInput struct {
	Key     string   `json:"key"`
	Writers []string `json:"writers"`
}

AfterApplyInput is an input whose value is known only after Writers, the earlier selected scripts writing what it observes, have run: apply re-observes it after them instead of holding it to its planned value.

type Analysis

type Analysis struct {
	Calls              []string                  `json:"calls"`
	Builtins           []sqlglot.BuiltinFunction `json:"builtins,omitempty"`
	Blocked            []string                  `json:"blocked,omitempty"`
	Unresolved         []string                  `json:"unresolved,omitempty"`
	TransactionControl bool                      `json:"transactionControl,omitempty"`
	// Dynamic reports SQL known only at run time, whose calls analysis cannot list.
	Dynamic bool `json:"dynamic,omitempty"`
	// Environment are the calls whose value depends only on the target, as SQL:
	// what is tracked is their value, not that of the built-in inside.
	Environment []string `json:"environment,omitempty"`
	// Reads are the queries answering what running the body reads, and
	// UntrackedReads the tables it reads in no such query (see analyzeReads).
	Reads          []Read       `json:"reads,omitempty"`
	UntrackedReads []ObjectName `json:"untrackedReads,omitempty"`
	// Effects is what running the body does (see analyzeEffects); Defines
	// holds the body effects of each routine a script creates or alters.
	Effects Effects                `json:"effects"`
	Defines map[ObjectName]Effects `json:"defines,omitempty"`
	// Tails is what may follow each batch of a script body in its request.
	Tails []sqlglot.BatchTail `json:"tails,omitempty"`
}

func Analyze

func Analyze(opts AnalysisOptions) Analysis

Analyze visits executable expressions, leaving stored module bodies for catalog analysis, and reads the body's effects.

type AnalysisOptions

type AnalysisOptions struct {
	SQL           string
	InvokedModule bool
}

type CachedAnalysis added in v1.3.0

type CachedAnalysis struct {
	Analysis   Analysis `json:"analysis"`
	Canonical  string   `json:"canonical,omitempty"`
	BatchError string   `json:"batchError,omitempty"`
}

CachedAnalysis is what a backend stores for one body: its analysis, the canonical text of a module definition, and the batch error of a script body that does not split.

type Dependency

type Dependency struct {
	Kind string `json:"kind"`
	Name string `json:"name"`
}

type Effects added in v1.3.0

type Effects struct {
	Reads   []ObjectName `json:"reads,omitempty"`
	Writes  []ObjectName `json:"writes,omitempty"`
	Calls   []ObjectName `json:"calls,omitempty"`
	Unknown []string     `json:"unknown,omitempty"`
}

Effects is what a script, or a routine it reaches, does to the database: the objects it reads, writes (including routines it creates or alters) and calls. Unknown lists the statements whose effects could not be determined, as "line N: reason". Analyze reads them from a body with the sqlglot access package. A nil Effects means no inferred dependencies.

func (Effects) Normalized added in v1.3.0

func (e Effects) Normalized() Effects

Normalized returns e with each list sorted and de-duplicated, so equal effects encode, and hash, identically.

type FunctionInput added in v1.3.2

type FunctionInput struct {
	Name string `json:"name"`
	// Builtin is a call of server built-ins, such as SUBSTRING(DB_NAME(), 5, 3).
	Builtin bool `json:"builtin,omitempty"`
	// Sampled is set when the plan observed a value, nil for NULL.
	Sampled bool    `json:"sampled,omitempty"`
	Value   *string `json:"value,omitempty"`
	// Writers are the scripts whose writes may change the value during apply.
	Writers []string      `json:"writers,omitempty"`
	Uses    []FunctionUse `json:"uses"`
}

FunctionInput is a function or built-in whose value or definition selects scripts of a plan.

func FunctionInputs added in v1.3.2

func FunctionInputs(actions []Pending, recorded map[string]State) []FunctionInput

FunctionInputs lists the functions and built-ins the actions track, by name with built-ins first, against the states recorded of them.

func (FunctionInput) Display added in v1.3.2

func (f FunctionInput) Display() string

Display is the function as it is called.

type FunctionUse added in v1.3.2

type FunctionUse struct {
	Script string `json:"script"`
	// Recorded is set when the last run recorded the value, Previous.
	Recorded          bool    `json:"recorded,omitempty"`
	Previous          *string `json:"previous,omitempty"`
	ValueChanged      bool    `json:"valueChanged,omitempty"`
	DefinitionChanged bool    `json:"definitionChanged,omitempty"`
}

FunctionUse is one script tracking a function, against what its last run recorded.

type LoadOptions

type LoadOptions struct {
	FS   fs.FS
	Dir  string
	Skip []string
}

type ObjectName added in v1.3.0

type ObjectName string

ObjectName is a schema-qualified database object a script reads, writes or calls: lower-cased "schema.name", with no kind, so a table, view, function or procedure of the same name is one object.

func NewObjectName added in v1.3.0

func NewObjectName(schema, name string) ObjectName

NewObjectName builds the canonical name of schema.name.

type Observation

type Observation struct {
	Kind  string `json:"kind"`
	Hash  string `json:"hash"`
	Error string `json:"error,omitempty"`
	// Value is the observed value of a result or built-in, nil for NULL.
	Value *string `json:"value,omitempty"`
}

type Pending

type Pending struct {
	Script   Script   `json:"script"`
	State    State    `json:"state"`
	Selected bool     `json:"selected"`
	Reasons  []string `json:"reasons,omitempty"`
	Blocked  []string `json:"blocked,omitempty"`
	// Reads are the queries answering what the script reads; one whose answer
	// changed since its last run selects it. UntrackedReads are the tables it
	// reads in no query of its own, or through a routine: they never select it.
	Reads          []PlannedRead     `json:"reads,omitempty"`
	UntrackedReads []ObjectName      `json:"untrackedReads,omitempty"`
	AfterApply     []AfterApplyInput `json:"afterApply,omitempty"`
	// SelfWritten lists the input keys whose observed objects the script's
	// own writes reach: apply observes exactly these again after the script
	// runs, since a script must not change its own inputs.
	SelfWritten []string `json:"selfWritten,omitempty"`
	// EffectsUnknown lists the statements of the script, or of a routine it
	// reaches, whose effects could not be determined. Apply re-inspects the
	// plan after such a script runs.
	EffectsUnknown []string `json:"effectsUnknown,omitempty"`
}

func (Pending) AfterApplyKey added in v1.3.0

func (p Pending) AfterApplyKey(key string) bool

AfterApplyKey reports whether key is known only after apply.

type Phase

type Phase string
const (
	Pre  Phase = "pre"
	Post Phase = "post"
	// Version is the ledger state version this package records. Version 2
	// states (no EffectsHash) read as current; version 1 is the legacy
	// content-only ledger.
	Version = 3
)

type Plan

type Plan struct {
	Target   string    `json:"target"`
	Phase    Phase     `json:"phase"`
	Hash     string    `json:"hash"`
	Scripts  []Pending `json:"scripts"`
	Warnings []string  `json:"warnings,omitempty"`
}

func Build

func Build(opts PlanOptions) (Plan, error)

Build plans the bundle in Ordered order. With an empty phase it plans both phases in one pass; a phase filters the plan to that phase while still propagating every earlier script's writes.

type PlanOptions

type PlanOptions struct {
	Target string
	// Phase filters the plan to one phase; empty plans the whole bundle in
	// one pass, pre scripts first.
	Phase        Phase
	Scripts      []Script
	Recorded     map[string]State
	Observations map[string]map[string]Observation
	// Modules holds the effects of catalog routines, by name, so a call into
	// the catalog reaches what that routine reads and calls.
	Modules map[ObjectName]Effects
	// SchemaWrites are the declared objects the schema step between the pre
	// and post scripts changes.
	SchemaWrites []ObjectName
	// Reads and UntrackedReads are what each script reads, by script ID, and
	// Answers what the reads with a recorded answer answer now, by SQL.
	Reads          map[string][]Read
	UntrackedReads map[string][]ObjectName
	Answers        map[string]ReadAnswer
}

type PlannedRead added in v1.3.2

type PlannedRead struct {
	Read
	Recorded *ReadAnswer `json:"recorded,omitempty"`
	Answer   *ReadAnswer `json:"answer,omitempty"`
	Changed  bool        `json:"changed,omitempty"`
}

PlannedRead is a read of a script: what it answered when the script last ran, and now. A read with no recorded answer is not run.

func (PlannedRead) Change added in v1.3.2

func (r PlannedRead) Change() string

Change is a changed read's answer when the script ran, and now.

type Read added in v1.3.2

type Read struct {
	SQL     string       `json:"sql"`
	Objects []ObjectName `json:"objects"`
}

Read is a query answering what a statement of a script reads, so two runs of it tell whether the statement would read different values. It runs on its own: the constant variables it names are declared in it.

func (Read) Key added in v1.3.2

func (r Read) Key() string

Key identifies the read in the ledger.

type ReadAnswer added in v1.3.2

type ReadAnswer struct {
	Digest string  `json:"digest,omitempty"`
	Rows   int     `json:"rows"`
	Value  *string `json:"value,omitempty"`
	Error  string  `json:"error,omitempty"`
}

ReadAnswer is what a read query answered: Digest identifies its columns and rows in any order, and Value is the value when there is only one.

func (ReadAnswer) String added in v1.3.2

func (a ReadAnswer) String() string

type Scalar

type Scalar struct {
	Type      string `json:"type"`
	Length    int64  `json:"length"`
	Precision int64  `json:"precision"`
	Scale     int64  `json:"scale"`
	Null      bool   `json:"null"`
	Value     string `json:"value"`
}

func (Scalar) Fingerprint

func (s Scalar) Fingerprint(invocation string) (string, error)

type Script

type Script struct {
	ID                   string       `json:"id"`
	Path                 string       `json:"path"`
	Name                 string       `json:"name"`
	SQL                  string       `json:"sql"`
	Phase                Phase        `json:"phase"`
	HeaderPhase          Phase        `json:"-"`
	Always               bool         `json:"always,omitempty"`
	NonTransactional     bool         `json:"nonTransactional,omitempty"`
	DependsOn            []string     `json:"dependsOn,omitempty"`
	Dependencies         []Dependency `json:"dependencies,omitempty"`
	ExplicitDependencies bool         `json:"explicitDependencies,omitempty"`
	ContextPolicy        string       `json:"contextPolicy,omitempty"`
	Effects              *Effects     `json:"effects,omitempty"`
	// Defines holds the body effects of each routine the script creates or
	// alters (each also listed in Effects.Writes). A script calling one of
	// them later in the bundle reaches these effects instead of the catalog's.
	Defines map[ObjectName]Effects `json:"defines,omitempty"`
}

func Load

func Load(opts LoadOptions) ([]Script, error)

func Ordered

func Ordered(items []Script) ([]Script, error)

func Parse

func Parse(name, content string) (Script, error)

type State

type State struct {
	Version    int    `json:"version"`
	SourceHash string `json:"sourceHash"`
	PolicyHash string `json:"policyHash"`
	// EffectsHash identifies the effects the script was planned with. It is
	// audit evidence only: Hash excludes it, so a changed analysis never
	// selects a script by itself.
	EffectsHash string            `json:"effectsHash,omitempty"`
	Hash        string            `json:"hash"`
	Inputs      map[string]string `json:"inputs"`
	// Values are the values of the function inputs: those of Inputs with a
	// sampled result, and the built-ins, which only Values tracks. Hash excludes
	// them, so a row that predates a built-in's tracking never runs again for it.
	// A script:<id> value identifies the built-ins of that prerequisite.
	Values map[string]*string `json:"values,omitempty"`
	// Reads are the answers of the script's reads right after it ran, by
	// Read.Key. Hash excludes them, as it does Values.
	Reads       map[string]ReadAnswer `json:"reads,omitempty"`
	Outcome     string                `json:"outcome,omitempty"`
	LastSuccess *State                `json:"lastSuccess,omitempty"`
}

Directories

Path Synopsis
Package sqlserver plans and applies dependency-aware scripts on SQL Server through a self-contained plan file: Plan observes the target once and writes what apply will do, and Apply runs exactly that plan, refusing it as stale when the target moved since.
Package sqlserver plans and applies dependency-aware scripts on SQL Server through a self-contained plan file: Plan observes the target once and writes what apply will do, and Apply runs exactly that plan, refusing it as stale when the target moved since.

Jump to

Keyboard shortcuts

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