analysis

package
v0.0.0-...-cdc0bb7 Latest Latest
Warning

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

Go to latest
Published: Dec 2, 2026 License: MIT Imports: 23 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 analysis is CockroachDB's statement judgment: the statement types a script changes, the tables it writes, its system catalogs, and the editor's splitting, diagnostics, read-only check, result limit and EXPLAIN. The wire protocol is PostgreSQL's, but CockroachDB's grammar is not: UPSERT, statement sources, AS OF SYSTEM TIME, index hints, regional DDL, zone configuration and IMPORT INTO have no PostgreSQL node, so the judgment walks CockroachDB's own AST.

Index

Constants

View Source
const (
	AlterDatabase   = analysis.AlterDatabase
	AlterIndex      = analysis.AlterIndex
	AlterSequence   = analysis.AlterSequence
	AlterTable      = analysis.AlterTable
	AlterType       = analysis.AlterType
	AlterView       = analysis.AlterView
	Comment         = analysis.Comment
	CreateDatabase  = analysis.CreateDatabase
	CreateExtension = analysis.CreateExtension
	CreateFunction  = analysis.CreateFunction
	CreateIndex     = analysis.CreateIndex
	CreateSchema    = analysis.CreateSchema
	CreateSequence  = analysis.CreateSequence
	CreateTable     = analysis.CreateTable
	CreateTrigger   = analysis.CreateTrigger
	CreateType      = analysis.CreateType
	CreateView      = analysis.CreateView
	Delete          = analysis.Delete
	DropDatabase    = analysis.DropDatabase
	DropFunction    = analysis.DropFunction
	DropIndex       = analysis.DropIndex
	DropSchema      = analysis.DropSchema
	DropSequence    = analysis.DropSequence
	DropTable       = analysis.DropTable
	DropTrigger     = analysis.DropTrigger
	DropType        = analysis.DropType
	DropView        = analysis.DropView
	Execute         = analysis.Execute
	Insert          = analysis.Insert
	RenameIndex     = analysis.RenameIndex
	RenameSchema    = analysis.RenameSchema
	RenameSequence  = analysis.RenameSequence
	Truncate        = analysis.Truncate
	Update          = analysis.Update
)
View Source
const StatementTypeUnspecified = analysis.StatementTypeUnspecified

StatementTypeUnspecified is a statement the classifier does not name.

Variables

View Source
var Engine engine

Engine is CockroachDB's implementation of the omni/analysis capability interfaces.

View Source
var ErrExplainAnalyzeExecutes = analysis.ErrExplainAnalyzeExecutes

ErrExplainAnalyzeExecutes is ExplainStatement's error for EXPLAIN ANALYZE, matching pg/analysis and the other analysis packages.

View Source
var ErrMixUserSystemTables = analysis.ErrMixUserSystemTables

ErrMixUserSystemTables reports a statement that reads user and system tables together.

View Source
var (

	// SystemSchemaWhereClause lists systemSchemas as SQL string literals, in
	// name order so that a query built from it is the same text every run.
	SystemSchemaWhereClause = func() string {
		var schemas []string
		for _, schema := range slices.Sorted(maps.Keys(systemSchemas)) {
			schemas = append(schemas, fmt.Sprintf("'%s'", schema))
		}
		return strings.Join(schemas, ",")
	}()
)

Functions

func CreateDatabaseName

func CreateDatabaseName(script string) (string, error)

CreateDatabaseName parses script and returns the target database name from the first CREATE DATABASE statement it contains.

func DescribeExplain

func DescribeExplain(statement string) (format string, executed bool, ok bool)

DescribeExplain reports a directly submitted EXPLAIN statement's format ("JSON" or "TEXT") and whether it executes the statement it plans (EXPLAIN ANALYZE). ok is false when statement is not a single EXPLAIN.

func ExplainStatement

func ExplainStatement(statement string, json bool) (string, error)

ExplainStatement builds the EXPLAIN statement for statement in CockroachDB's grammar, unwrapping an existing EXPLAIN so a plan never plans another plan. EXPLAIN ANALYZE returns ErrExplainAnalyzeExecutes.

func IsDoBlock

func IsDoBlock(stmt string) bool

IsDoBlock reports whether stmt parses as a single PL/pgSQL anonymous code block (DO statement).

func IsSelectStatement

func IsSelectStatement(statement string) bool

IsSelectStatement reports whether statement parses as a single SELECT (including parenthesized SELECT) statement.

func IsSystemDatabase

func IsSystemDatabase(database string) bool

IsSystemDatabase reports whether database is one CockroachDB manages.

func IsSystemSchema

func IsSystemSchema(schema string) bool

IsSystemSchema reports whether schema is one CockroachDB manages.

func Parse

func Parse(script string) (statements.Statements, error)

Parse parses script, the whole script or one statement, into statements carrying the AST and the text CockroachDB's parser read. A trailing semicolon is written so a script without one parses as CockroachDB's parser expects.

func ParseRaw

func ParseRaw(sql string) ([]ParsedStatement, *ParseErrorInfo, error)

ParseRaw parses sql unmodified into opaque ParsedStatement values. On a parse failure it returns normalized error details with the byte offset into sql.

func ResolveQuerySpan

func ResolveQuerySpan(_ context.Context, statement string, opts ResolveOptions) (*analysis.ResolvedSpan, error)

ResolveQuerySpan returns the column lineage of one CockroachDB statement, resolved against the synced metadata on CockroachDB's own AST. A column read through a view names the view's column and the columns behind it, as CockroachDB's result-set metadata follows a view to its table.

A statement that does not parse returns a *SyntaxError, one that reads user and system tables together ErrMixUserSystemTables, and a query that names a column its relations lack or name ambiguously CockroachDB's error for it, with its SQLSTATE (pgerror.GetPGCode). A relation missing from the metadata sets the span's NotFoundError. Statements other than a SELECT of user tables return their QueryType and the relations they read, with no Results.

func ReturnsRows

func ReturnsRows(statement string) (bool, error)

ReturnsRows parses statement and reports whether any statement in it returns result rows according to CockroachDB's parser.

func RewriteResultLimit

func RewriteResultLimit(statement string, limitCount int) (string, error)

RewriteResultLimit rewrites one SELECT so it returns at most limitCount rows. A statement that is not a SELECT, VALUES or TABLE is returned unchanged, and so is one whose integer LIMIT is at most limitCount.

  • Another integer, ALL or NULL after LIMIT or FETCH FIRST/NEXT is replaced in the text by limitCount.
  • With no LIMIT, "LIMIT <limitCount>" goes before a FOR UPDATE/SHARE clause, or after the statement's last token.
  • Any other LIMIT, an expression or placeholder, becomes least(<it>, limitCount), rendered from the AST.

The rewrite never wraps the statement, which CockroachDB refuses for a query with AS OF SYSTEM TIME. An error means empty input, a parse error or more than one statement.

func Split

func Split(script string) []string

Split returns each statement of script with its terminating semicolon, lexically, so a script the parser rejects still splits. A segment that holds no statement, such as a lone ";", is "" so a caller can account for every boundary; trailing text holding no statement is dropped.

func SplitScript

func SplitScript(script string) []string

SplitScript splits script lexically into statement segments, preserving empty segments as "" so callers can account for every semicolon boundary.

func ValidateQuery

func ValidateQuery(script string) (readOnly bool, returnsData bool, err error)

ValidateQuery reports whether a script may run in the SQL editor's read-only mode, and whether every statement returns data rather than set session state. A script that does not parse returns the parser's error.

SELECT, VALUES and TABLE are allowed unless a CTE, statement source or subquery writes, through an EXPLAIN ANALYZE inside one too; EXPLAIN is allowed, and EXPLAIN ANALYZE only of such a read; SHOW is allowed; SET and RESET are allowed but return no data. Everything else, DDL and DML included, is refused.

Types

type Catalog

type Catalog struct {
	// GetDatabase returns a database's metadata, or a nil Database when the
	// database has not been synced.
	GetDatabase func(name string) (Database, error)
}

Catalog is the synced metadata of the instance a statement runs on.

type ChangeMetadata

type ChangeMetadata interface {
	// RelationSchema returns the first schema in searchPath that has a table,
	// view or materialized view named name, or "".
	RelationSchema(searchPath []string, name string) string
	// IndexTable returns the schema of the first index named name in
	// searchPath's schemas and the table it indexes; ok is false when there
	// is no such index or it names no table.
	IndexTable(searchPath []string, name string) (schema, table string, ok bool)
}

ChangeMetadata is the synced metadata of the database a script changes. Its lookups follow the metadata's own name matching.

type ChangedResource

type ChangedResource = analysis.ChangedResource

ChangedResource is a table a statement writes.

type Changes

type Changes struct {
	// Resources holds the tables the statements write, in the order they name
	// them, duplicates included.
	Resources []ChangedResource
	// Databases holds the databases a statement changes without naming a
	// table, such as an index of another database.
	Databases []string
	// DMLStatements holds the DML statements to estimate, in order.
	DMLStatements []DMLStatement
	// DMLCount counts the DML statements DMLStatements holds.
	DMLCount int
	// InsertCount counts the rows of INSERT ... VALUES and INSERT ... DEFAULT VALUES.
	InsertCount int
}

Changes is what a script changes.

func ExtractChangedResources

func ExtractChangedResources(stmts statements.Statements, database string, searchPath []string, metadata ChangeMetadata) Changes

ExtractChangedResources returns the tables a script writes and the DML statements to estimate, replaying the search path changes it makes: SET, RESET, DISCARD ALL and the transactions that scope SET LOCAL. database is the current database and searchPath the initial search path; an empty one means public. Like PostgreSQL's extractor, an existing table resolves to the first schema that has it in metadata, and a new table to the first schema. EXPLAIN ANALYZE counts as the statement it runs.

func ExtractChangedResourcesFromParsed

func ExtractChangedResourcesFromParsed(stmts []ParsedStatement, database string, searchPath []string, metadata ChangeMetadata) Changes

ExtractChangedResourcesFromParsed returns the changed resources and DML statements of opaque ParsedStatement values, keeping cockroachdb-parser types out of callers.

type DMLStatement

type DMLStatement struct {
	// Text is the statement, as CockroachDB's parser reports it and without a
	// trailing semicolon.
	Text string
	// SearchPath is the search path the statement runs under when an earlier
	// statement changed it, and nil when it runs under the initial one.
	SearchPath []string
}

DMLStatement is a DML statement whose affected rows Bytebase estimates.

type Database

type Database interface {
	// Metadata is the whole snapshot, which holds the views' definitions.
	Metadata() *metadata.DatabaseSchemaMetadata
	// GetTable returns the table named table in schema, or nil.
	GetTable(schema, table string) *metadata.TableMetadata
	// SearchRelation returns the schema and name of the first table, view or
	// materialized view named name in searchPath's schemas, or two empty
	// strings.
	SearchRelation(searchPath []string, name string) (schema string, relation string)
}

Database is one database's synced metadata. The lookups follow the metadata's own name matching, so the caller decides case sensitivity.

type DiagnoseError

type DiagnoseError struct {
	// Offset is the error's byte offset in the script, the start of the
	// failing statement when CockroachDB's parser did not locate it.
	Offset  int
	Message string
}

DiagnoseError is the first syntax error Diagnose finds.

func Diagnose

func Diagnose(script string) *DiagnoseError

Diagnose parses a script for an editor with CockroachDB's grammar and returns its first syntax error, or nil.

type ExecutionFlags

type ExecutionFlags struct {
	// NonTransactional is true for statements that cannot run inside an
	// explicit transaction block (DROP DATABASE, CREATE/DROP INDEX CONCURRENTLY,
	// and VACUUM).
	NonTransactional bool
	// SessionRole is true for non-local SET ROLE statements that must be
	// replayed at session scope.
	SessionRole bool
	// Superuser is true for statements that require superuser privileges
	// (GRANT, GRANT ROLE, and CREATE EXTENSION).
	Superuser bool
}

ExecutionFlags describes how a driver must execute a single statement.

func ClassifyExecution

func ClassifyExecution(stmt string) ExecutionFlags

ClassifyExecution reports execution flags for a single CockroachDB statement. CockroachDB's own AST decides, so keywords inside string literals or comments do not affect classification. Unparseable or multi-statement input returns zero flags.

type IndexDefinition

type IndexDefinition struct {
	Expressions []string
	Descending  []bool
	Unique      bool
}

IndexDefinition holds the parsed structure of a CockroachDB CREATE INDEX statement.

func ParseIndexDefinition

func ParseIndexDefinition(statement string) (*IndexDefinition, error)

ParseIndexDefinition parses a single CREATE INDEX statement (such as pg_indexes.indexdef) and extracts its key expressions, sort directions, and uniqueness.

type ParseErrorInfo

type ParseErrorInfo struct {
	Message  string
	Position int
	Code     string
}

ParseErrorInfo holds normalized error fields extracted from a CockroachDB parser error so callers outside this package do not depend on vendor error types. Position is the byte offset into the parsed SQL; when the parser reports no source location it is the start of the statement that failed.

type ParsedStatement

type ParsedStatement struct {
	// contains filtered or unexported fields
}

ParsedStatement is an opaque parsed CockroachDB statement that keeps cockroachdb-parser AST types encapsulated inside this package.

func ParseScript

func ParseScript(script string) ([]ParsedStatement, error)

ParseScript parses script, the whole script or one statement, into opaque ParsedStatement values.

func (ParsedStatement) Text

func (s ParsedStatement) Text() string

Text returns the statement SQL as CockroachDB's parser read it.

type ResolveOptions

type ResolveOptions struct {
	// DefaultDatabase is the database the statement runs in.
	DefaultDatabase string
	// SearchPath resolves unqualified names. Empty means public.
	SearchPath []string
	// Catalog reads the instance's synced metadata. GetDatabase must be set.
	Catalog Catalog
}

ResolveOptions configures ResolveQuerySpan.

type Segment

type Segment struct {
	Text      string
	ByteStart int
	ByteEnd   int
	// contains filtered or unexported fields
}

Segment is one statement's span of a script: the text from the end of the previous segment through its terminating semicolon.

func SplitSegments

func SplitSegments(script string) []Segment

SplitSegments splits script lexically into segments that tile it, as CockroachDB's parser bounds statements: a semicolon inside a BEGIN ATOMIC body does not end its CREATE FUNCTION. After a lexical error, such as an unterminated string, the rest of the script is one segment.

func (Segment) Empty

func (s Segment) Empty() bool

Empty reports whether the segment holds no statement: only whitespace, comments and semicolons.

type StatementType

type StatementType = analysis.StatementType

StatementType is the kind of change a statement makes.

func StatementTypes

func StatementTypes(stmts statements.Statements) []StatementType

StatementTypes returns the type of each statement that has one, in order, each followed by the types of the mutations in its CTEs and statement sources, each type once per statement. EXPLAIN ANALYZE takes the types of the statement it runs. A statement the classifier does not name adds none.

func StatementTypesFromParsed

func StatementTypesFromParsed(stmts []ParsedStatement) []StatementType

StatementTypesFromParsed returns the StatementTypes of opaque ParsedStatement values, keeping cockroachdb-parser types out of callers.

type SyntaxError

type SyntaxError struct {
	Err error
	// Position is the byte offset of the failure in the statement.
	Position int
}

SyntaxError reports a statement CockroachDB's parser rejects.

func (*SyntaxError) Error

func (e *SyntaxError) Error() string

func (*SyntaxError) Unwrap

func (e *SyntaxError) Unwrap() error

Jump to

Keyboard shortcuts

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