Documentation
¶
Overview ¶
Package sqlapi tells the tools that call the public SQL functions for a relation the user names (melange explain and expand, studio) whether the database answers for it, from the exposure recorded by its last migration, so they can say why instead of surfacing a raw M2003 or 42883.
When the recorded exposure has the explain or expand family off, the tools still explain and expand: Trace compiles the family's functions from the recorded model and creates them in pg_temp for one transaction that is always rolled back (see ondemand.go).
It depends on the published runtime only through symbols every release has: a raised M2003 is recognized by its SQLSTATE.
Index ¶
Constants ¶
This section is empty.
Variables ¶
var ( Check = Family{"check", "check_permission", "", nil, sqlgen.PublicAPI.Check, false} ListObjects = Family{ "list objects", "list_accessible_objects", "list_objects", func(f sqlgen.FunctionFamilies) *bool { return f.ListObjects }, sqlgen.PublicAPI.ListObjects, false, } ListSubjects = Family{ "list subjects", "list_accessible_subjects", "list_subjects", func(f sqlgen.FunctionFamilies) *bool { return f.ListSubjects }, sqlgen.PublicAPI.ListSubjects, false, } Explain = Family{ "explain", "explain_permission", "explain", func(f sqlgen.FunctionFamilies) *bool { return f.Explain }, sqlgen.PublicAPI.Explain, true, } Expand = Family{ "expand", "expand_permission", "expand", func(f sqlgen.FunctionFamilies) *bool { return f.Expand }, sqlgen.PublicAPI.Expand, true, } )
var ErrNoRecordedModel = errors.New("no recorded model")
ErrNoRecordedModel is returned by Deployed for a database whose last migration recorded no model, when there is no fallback to describe.
Functions ¶
This section is empty.
Types ¶
type API ¶
type API struct {
// contains filtered or unexported fields
}
API is what a database's public functions answer for. The zero value answers for everything, as a database with no recorded migration does.
func FromModel ¶
func FromModel(model *migrator.DeployedModel) *API
FromModel is New for a deployed model, which also carries what compiling explain and expand on demand needs. A nil model answers for everything.
func Load ¶
Load reads the exposure and model recorded by the database's last migration. A database never migrated, or migrated before the exposure was recorded, has the default exposure. Load never fails: when the record cannot be read, the API answers for everything and the calls themselves report what is wrong.
func New ¶
func New(exposure sqlgen.Exposure, types []schema.TypeDefinition) *API
New resolves the recorded exposure against the deployed model's types. types may be nil when no model is recorded; then only a family that is off can be told apart, relations are assumed exposed, and explain and expand cannot be compiled on demand.
func (*API) OnDemand ¶
OnDemand reports whether Trace compiles family's functions for each call: explain or expand with the family off in the recorded exposure, a recorded model, and the codegen version that generated the installed functions.
func (*API) Trace ¶
func (a *API) Trace(ctx context.Context, db DB, databaseSchema string, f Family, setup func(context.Context, *sql.Tx) error, fn func(*melange.Checker) error) error
Trace runs fn with a Checker whose Explain, Expand and ExpandRecursive answer for family f (Explain or Expand) against databaseSchema.
With the family installed, the Checker runs on db. With the family off and OnDemand true, it runs in a transaction that holds the functions compiled into pg_temp, is read-only while fn runs, and is always rolled back, so fn must not keep the Checker. When db is a *sql.DB, that transaction runs on a connection taken from the pool and closed afterwards, never returned to it. With the family off and no way to compile it, Trace returns the *Unavailable that Unavailable reports.
setup, when not nil, runs in that transaction before it turns read-only, after the on-demand functions exist, and is followed by DISCARD PLANS so cached plans resolve melange_tuples again (studio's what-if view). It puts the call in a transaction even when the family is installed.
func (*API) Unavailable ¶
func (a *API) Unavailable(f Family, objectType, relation string) *Unavailable
Unavailable returns why family's public function does not answer for the relation, or nil when it does, installed or on demand. A relation the model does not define is answered (with the unknown-pair result), as it always was, even with the family off: the public dispatchers are always generated.
type CheckOptions ¶
type CheckOptions struct {
// Bodies compares each installed body with the one this melange
// generates, which compiles the model (most of a second for a large
// one, cached per process).
Bodies bool
}
CheckOptions configures Check.
type ClientFinding ¶
type ClientFinding struct {
Code string `json:"code"`
Severity ClientSeverity `json:"severity"`
Type string `json:"type,omitempty"`
Relation string `json:"relation,omitempty"`
Link string `json:"link,omitempty"`
Function string `json:"function,omitempty"`
Message string `json:"message"`
Fix string `json:"fix,omitempty"`
Remedy Remedy `json:"-"`
}
ClientFinding is one name of the client that the database does not answer for as the client expects.
type ClientNames ¶
type ClientNames struct {
Pairs []clientgen.RelationRef
Functions []sqlgen.AccessibleFunction
// Types is the model the client is generated from, and SchemaContent
// the schema text it was parsed from. A caller comparing with a database
// that records no model describes the database with Types, and predicts
// what migrate does with the client's configuration from both.
Types []schema.TypeDefinition
SchemaContent string
}
ClientNames are the names a generated client emits: the relations it selects, in model order, and the accessible functions it names.
func NewClientNames ¶
func NewClientNames(m *clientgen.Model, types []schema.TypeDefinition, schemaContent string) ClientNames
NewClientNames returns the names a client resolved as m emits, with the model it was resolved from and that model's schema text (nil and "" when the caller has none).
type ClientReport ¶
type ClientReport struct {
Findings []ClientFinding `json:"findings"`
Errors int `json:"errors"`
Warnings int `json:"warnings"`
FunctionsChecked int `json:"functions_checked"`
PairsChecked int `json:"relations_checked"`
Notes []string `json:"notes,omitempty"`
}
ClientReport is the result of CompareClient.
func CompareClient ¶
func CompareClient(r *Report, rec *migrator.MigrationRecord, names ClientNames, local sqlgen.Exposure) *ClientReport
CompareClient checks the names a client emits against r, a checked report of the database (Deployed), and rec, its last migration record or nil. local is the exposure the client was generated under (melange.yaml's sql section), which says whether a migrate would install what is missing.
type ClientSeverity ¶
type ClientSeverity string
ClientSeverity is how much a client finding matters.
const ( // SeverityError: the client names something the database does not // answer for, so the call fails. SeverityError ClientSeverity = "error" // SeverityWarning: the database answers today, but a later migration // or the application's own objects may change that. SeverityWarning ClientSeverity = "warning" // SeverityInfo: a difference that breaks nothing; not counted. SeverityInfo ClientSeverity = "info" )
type DB ¶
type DB interface {
melange.Querier
BeginTx(ctx context.Context, opts *sql.TxOptions) (*sql.Tx, error)
}
DB is the database handle Trace runs on, such as *sql.DB.
type Fallback ¶
type Fallback struct {
// Types are the local schema file's.
Types []schema.TypeDefinition
// Exposure is the local one (melange.yaml's sql section), used when no
// migration is recorded at all, as for a database built from melange
// generate migration files, which write no record.
Exposure sqlgen.Exposure
}
Fallback is the local model Deployed describes for a database that records none.
type Family ¶
type Family struct {
// contains filtered or unexported fields
}
Family is a public function family a tool calls.
type Function ¶
type Function struct {
sqlgen.CatalogFunction
Status Status `json:"status"`
Detail string `json:"detail,omitempty"`
// StaleOverloads are other functions of the same name, by their
// arguments, left by an earlier signature.
StaleOverloads []string `json:"stale_overloads,omitempty"`
}
Function is a catalog function and its status.
type InstalledFunction ¶
InstalledFunction is a function found in pg_proc.
type Relation ¶
type Relation struct {
Type string `json:"type"`
Relation string `json:"relation"`
Exposed bool `json:"exposed"`
Dispatchers []string `json:"dispatchers"`
Examples []sqlgen.DispatcherCall `json:"examples,omitempty"`
DependsOn []string `json:"depends_on,omitempty"`
Functions []Function `json:"functions"`
NotInstalled []sqlgen.NotInstalled `json:"not_installed,omitempty"`
}
Relation is a relation of the model and its functions.
func (Relation) MarshalJSON ¶
MarshalJSON writes the dispatchers and functions as arrays, [] when empty.
type Remedy ¶
type Remedy string
Remedy is what a finding's fix does, for a caller that words fixes with what it knows about the next migrate (doctor).
const ( // RemedyMigrate: a migrate with melange.yaml's schema and sql section // applies it. RemedyMigrate Remedy = "migrate" // RemedyReinstall: the last migration installed the function and it is // gone from the database. RemedyReinstall Remedy = "reinstall" // RemedyRegenerate: the client names more than melange.yaml installs. RemedyRegenerate Remedy = "regenerate" )
type Report ¶
type Report struct {
// Source is "database" (the deployed model, checked against pg_proc) or
// "file" (a schema file and the local exposure, not checked).
Source string `json:"source"`
// SchemaFile is the schema file the model was read from, when it was.
SchemaFile string `json:"schema_file,omitempty"`
DatabaseSchema string `json:"database_schema"`
// MelangeVersion is this melange's codegen version, which the names,
// signatures and bodies are computed with.
MelangeVersion string `json:"melange_version"`
// DeployedCodegenVersion is the codegen version of the last migration;
// CodegenSkew is set when it differs from MelangeVersion, and
// CodegenAhead when it is newer, so this melange's migrate refuses to
// replace or drop anything.
DeployedCodegenVersion string `json:"deployed_codegen_version,omitempty"`
CodegenSkew bool `json:"codegen_skew"`
CodegenAhead bool `json:"codegen_ahead"`
// Checked reports whether statuses come from the database.
Checked bool `json:"checked"`
// BodiesChecked reports whether bodies were compared too.
BodiesChecked bool `json:"bodies_checked"`
Exposure sqlgen.Exposure `json:"exposure"`
Summary Summary `json:"summary"`
// Relations are in model order.
Relations []Relation `json:"relations"`
Dispatchers []Function `json:"dispatchers"`
// Orphans are installed functions the last migration recorded that this
// melange does not generate for the model; migrate drops them. When
// CodegenAhead is set they are the newer melange's functions, which this
// melange's migrate leaves alone.
Orphans []InstalledFunction `json:"orphans,omitempty"`
// Unmanaged are installed functions named like generated ones that no
// migration recorded, such as an application's own explain_invoice.
// Migrate never drops them.
Unmanaged []InstalledFunction `json:"unmanaged,omitempty"`
Collisions []sqlgen.NameCollision `json:"collisions,omitempty"`
Notes []string `json:"notes,omitempty"`
// contains filtered or unexported fields
}
Report is a model's SQL API and, when checked, its state in a database.
func Deployed ¶
func Deployed(ctx context.Context, db migrator.Execer, databaseSchema string, fallback *Fallback, opts CheckOptions) (*Report, *migrator.MigrationRecord, error)
Deployed returns the report for the model a database's last migration recorded, under its recorded exposure, checked against pg_proc. With no recorded model it describes fallback: under the recorded exposure when a migration is recorded without its model (an older melange, which installed the default), else under fallback's exposure, as doctor does. With no fallback either it fails.
func Describe ¶
func Describe(types []schema.TypeDefinition, exposure sqlgen.Exposure, databaseSchema string) (*Report, error)
Describe returns the SQL API a migration of types under exposure into databaseSchema installs, unchecked.
func (*Report) Check ¶
func (r *Report) Check(ctx context.Context, db melange.Querier, rec *migrator.MigrationRecord, opts CheckOptions) error
Check reads the functions installed in the report's database schema and sets every status. rec is the last migration record, or nil.
func (Report) MarshalJSON ¶
MarshalJSON writes the relations and dispatchers as arrays, [] when empty, as the CLI reference documents them.
type Status ¶
type Status string
Status is how an expected function compares with the database.
const ( // StatusNotChecked: the report was built without a database. StatusNotChecked Status = "not_checked" // StatusInstalled: installed with the expected arguments and, when // bodies are compared, the body this melange generates. StatusInstalled Status = "installed" // StatusMissing: no function of that name in the schema. StatusMissing Status = "missing" // StatusSignatureDiffers: installed, but none with the expected // arguments. StatusSignatureDiffers Status = "signature_differs" // StatusBodyChanged: the installed body differs from the one migrate // generated and recorded, so it was changed in the database. StatusBodyChanged Status = "body_changed" // StatusCodegenDiffers: the installed body is the one the last // migration generated, and this melange generates another: the next // migrate replaces it. StatusCodegenDiffers Status = "codegen_differs" )
type Summary ¶
type Summary struct {
Relations int `json:"relations"`
Exposed int `json:"exposed"`
Functions int `json:"functions"`
Installed int `json:"installed"`
Missing int `json:"missing"`
SignatureDiffers int `json:"signature_differs"`
BodyChanged int `json:"body_changed"`
CodegenDiffers int `json:"codegen_differs"`
StaleOverloads int `json:"stale_overloads"`
Orphans int `json:"orphans"`
Unmanaged int `json:"unmanaged"`
}
Summary counts the report's functions.
type Unavailable ¶
type Unavailable struct {
Unavailable says why a public function does not answer for a relation. It is an error, worded for the user, with how to change it.
func FromError ¶
func FromError(f Family, objectType, relation string, err error) *Unavailable
FromError recognizes a public function call that failed because the relation is not exposed (M2003) or the family's public function is missing (42883 naming it), and returns it as an *Unavailable; it returns nil for any other error, including a 42883 for another function the call reached.
M2003 is recognized by its SQLSTATE on the driver error, which the published runtime returns wrapped, and by the ValidationError that later runtimes map it to. A missing function is recognized by the database's message, since the runtime prefixes the error with the public function's name and maps some 42883s to ErrMissingFunction without the driver error.
func (*Unavailable) ByDesign ¶
func (u *Unavailable) ByDesign() bool
ByDesign reports whether the function does not answer because of how the database was migrated: the relation is not exposed, or its family is off. Anything else (an unreadable or invalid recorded model, a codegen skew, a failed on-demand compile, a missing function) is a fault to fix.
func (*Unavailable) Error ¶
func (u *Unavailable) Error() string
func (*Unavailable) Label ¶
func (u *Unavailable) Label() string
Label is a short status for a relation the tool skips: "not exposed" or "not installed" (the family is off or its function is missing).
func (*Unavailable) Unwrap ¶
func (u *Unavailable) Unwrap() error
Unwrap returns the database error FromError recognized, or the one that made compiling the functions on demand fail, or nil.