Documentation
¶
Overview ¶
Copyright 2020 Google LLC
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
Copyright 2020 Google LLC ¶
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
System Variables Naming Convention: - Variables that correspond to java-spanner JDBC properties use the same names - Variables that are spanner-mycli specific MUST use CLI_ prefix - This ensures compatibility with existing JDBC tooling while clearly identifying custom extensions
This file contains the registry-based implementation of system variables ¶
InterceptorLogger adapts zap logger to interceptor logger.
Index ¶
- Constants
- Variables
- func FeatureState[T any](ctx context.Context, s *Session, key string, ...) (T, error)
- func GetExitCode(err error) int
- func GetTerminalSize(w io.Writer) (int, error)
- func InterceptorLogger(l *zap.Logger) logging.Logger
- func IsMetaCommand(line string) bool
- func LinkTypePred(typ string) func(cl *sppb.PlanNode_ChildLink) bool
- func ListAvailableSamples() string
- func Main(version, installFrom string, features ...Feature)
- func NewExitCodeError(exitCode int) error
- func PS1PS2FuncToPromptFunc(ps1F func() string, ps2F func(ps1 string) string) func(w io.Writer, lnum int) (int, error)
- func ParseStatements(content []byte, filename string) ([]string, error)
- func SetLogLevel(logLevel string) (slog.Level, error)
- func UnquoteString(s string) string
- func ValidateSpannerOptions(opts *spannerOptions) error
- type AbortBatchStatement
- type AddSplitPointsStatement
- type BatchDMLStatement
- type BatchInfo
- type BatchManager
- func (b *BatchManager) Abort()
- func (b *BatchManager) Current() Statement
- func (b *BatchManager) Info() *BatchInfo
- func (b *BatchManager) IsActive() bool
- func (b *BatchManager) SetCurrent(stmt Statement)
- func (b *BatchManager) Start(mode batchMode) error
- func (b *BatchManager) TakeForExecution() (Statement, error)
- type BeginRoStatement
- type BeginRwStatement
- type BeginStatement
- type BulkDdlStatement
- type Cli
- func (c *Cli) ExitOnError(err error) int
- func (c *Cli) GetErrStream() io.Writer
- func (c *Cli) GetInStream() io.ReadCloser
- func (c *Cli) GetTerminalSizeWithTty(w io.Writer) (int, error)
- func (c *Cli) GetTtyStream() *os.File
- func (c *Cli) GetWriter() io.Writer
- func (c *Cli) PrintBatchError(err error)
- func (c *Cli) PrintInteractiveError(err error)
- func (c *Cli) PrintProgressingMark(w io.Writer) func()
- func (c *Cli) PrintResult(screenWidth int, result *Result, interactive bool, input string, w io.Writer) error
- func (c *Cli) RunBatch(ctx context.Context, input string) error
- func (c *Cli) RunInteractive(ctx context.Context) error
- func (c *Cli) RunMCP(ctx context.Context) error
- type CommitStatement
- type ConditionallyMutatingStatement
- type ConnectionVars
- type CreateDatabaseStatement
- type CustomVar
- type DMLResult
- type DdlStatement
- type DependencyResolver
- func (dr *DependencyResolver) BuildDependencyGraphWithTxn(ctx context.Context, txn *spanner.ReadOnlyTransaction) error
- func (dr *DependencyResolver) GetDependencyInfo(tableName string) (*TableDependency, error)
- func (dr *DependencyResolver) GetOrderForTables(tablesToExport []string) ([]string, error)
- func (dr *DependencyResolver) GetTableOrder() ([]string, error)
- type DescribeStatement
- type DetachStatement
- type DetachedCompatible
- type DisableOutputRedirectMetaCommand
- type DisableTeeMetaCommand
- type DisplayVars
- type DmlStatement
- type DropDatabaseStatement
- type DumpDatabaseStatement
- type DumpSchemaStatement
- type DumpTablesStatement
- type EndpointVar
- type EnumVar
- func AutocommitDMLModeVar(ptr *enums.AutocommitDMLMode) *EnumVar[enums.AutocommitDMLMode]
- func DisplayModeVar(ptr *enums.DisplayMode) *EnumVar[enums.DisplayMode]
- func ExplainFormatVar(ptr *enums.ExplainFormat) *EnumVar[enums.ExplainFormat]
- func ParseModeVar(ptr *enums.ParseMode) *EnumVar[enums.ParseMode]
- func StreamingModeVar(ptr *enums.StreamingMode) *EnumVar[enums.StreamingMode]
- func StyledModeVar(ptr *enums.StyledMode) *EnumVar[enums.StyledMode]
- func WidthStrategyVar(ptr *enums.WidthStrategy) *EnumVar[enums.WidthStrategy]
- type ErrAddNotSupported
- type ErrUnknownVariable
- type ExecuteStatementArgs
- type ExitCodeError
- type ExitStatement
- type ExplainAnalyzeDmlStatement
- type ExplainAnalyzeStatement
- type ExplainLastQueryStatement
- type ExplainStatement
- type FKReference
- type Feature
- type FeatureVar
- type FeatureVars
- type HelpStatement
- type HelpVariablesStatement
- type History
- type IntGetterVar
- type InternalVars
- type LastQueryCache
- type LastResult
- type LogLevelVar
- type MarksDetachedCompatible
- type MarksMutation
- type MetaCommandStatement
- type MultiValueVar
- type MutateStatement
- type MutationClassifier
- type MutationStatement
- type NopStatement
- type OutputContext
- type OutputRedirectMetaCommand
- type PartitionStatement
- type PartitionedDmlStatement
- type PromptMetaCommand
- type ProtoDescriptorVar
- type ProtoEnumVar
- func DatabaseDialectVar(ptr *databasepb.DatabaseDialect) *ProtoEnumVar[databasepb.DatabaseDialect]
- func IsolationLevelVar(ptr *sppb.TransactionOptions_IsolationLevel) *ProtoEnumVar[sppb.TransactionOptions_IsolationLevel]
- func QueryModeVar(ptr *sppb.ExecuteSqlRequest_QueryMode) *ProtoEnumVar[sppb.ExecuteSqlRequest_QueryMode]
- func RPCPriorityVar(ptr *sppb.RequestOptions_Priority) *ProtoEnumVar[sppb.RequestOptions_Priority]
- func ReadLockModeVar(ptr *sppb.TransactionOptions_ReadWrite_ReadLockMode) *ProtoEnumVar[sppb.TransactionOptions_ReadWrite_ReadLockMode]
- type QueryIndexAdvice
- type QueryResult
- type QueryStats
- type QueryVars
- type ReadOnlyVar
- type Result
- type ResultAppendix
- type RollbackStatement
- type Row
- type RowProcessor
- type RunBatchStatement
- type RunPartitionStatement
- type RunPartitionedQueryStatement
- type SampleDatabase
- type SelectStatement
- type Session
- func (s *Session) AuthOptions(ctx context.Context, credential []byte, allowWithoutAuthentication bool) ([]option.ClientOption, error)
- func (s *Session) Close()
- func (s *Session) CredentialBytes() []byte
- func (s *Session) DatabaseExists(ctx context.Context) (bool, error)
- func (s *Session) DatabasePath() string
- func (s *Session) ExecuteStatement(ctx context.Context, stmt Statement) (result *Result, err error)
- func (s *Session) ExecuteStatementWithOutput(ctx context.Context, stmt Statement, out outputContext) (*Result, error)
- func (s *Session) GetDatabaseDdlCached(ctx context.Context) (*adminpb.GetDatabaseDdlResponse, error)
- func (s *Session) GetDatabaseSchema(ctx context.Context) ([]string, *descriptorpb.FileDescriptorSet, error)
- func (s *Session) IncrementSchemaGeneration()
- func (s *Session) InstanceExists(ctx context.Context) (bool, error)
- func (s *Session) InstancePath() string
- func (s *Session) IsDetached() bool
- func (s *Session) Mode() SessionMode
- func (s *Session) ProjectID() string
- func (s *Session) RecreateClient(ctx context.Context) error
- func (s *Session) RequiresDatabaseConnection() bool
- func (s *Session) SchemaGeneration() uint64
- func (s *Session) ValidateDatabaseOperation() error
- func (s *Session) ValidateDetachedOperation() error
- func (s *Session) ValidateStatementExecution(stmt Statement) error
- type SessionHandler
- func (h *SessionHandler) Close()
- func (h *SessionHandler) ExecuteStatement(ctx context.Context, stmt Statement) (*Result, error)
- func (h *SessionHandler) ExecuteStatementWithOutput(ctx context.Context, stmt Statement, out outputContext) (*Result, error)
- func (h *SessionHandler) GetSession() *Session
- type SessionMode
- type SetAddStatement
- type SetLocalStatement
- type SetParamTypeStatement
- type SetParamValueStatement
- type SetStatement
- type SetTransactionStatement
- type ShellMetaCommand
- type ShowColumnsStatement
- type ShowCreateStatement
- type ShowDatabasesStatement
- type ShowDdlsStatement
- type ShowIndexStatement
- type ShowLocalProtoStatement
- type ShowOperationStatement
- type ShowParamsStatement
- type ShowPlanNodeStatement
- type ShowQueryProfileStatement
- type ShowQueryProfilesStatement
- type ShowRemoteProtoStatement
- type ShowSchemaUpdateOperations
- type ShowSplitPointsStatement
- type ShowTablesStatement
- type ShowVariableStatement
- type ShowVariablesStatement
- type SourceMetaCommand
- type StartBatchStatement
- type StartupConfig
- type Statement
- func BuildCLIStatement(stripped, raw string) (Statement, error)
- func BuildNativeStatementLexical(stripped string, raw string) (Statement, error)
- func BuildNativeStatementMemefish(stripped, raw string) (Statement, error)
- func BuildStatement(input string) (Statement, error)
- func BuildStatementWithComments(stripped, raw string) (Statement, error)
- func BuildStatementWithCommentsWithMode(stripped, raw string, mode enums.ParseMode) (Statement, error)
- func BuildStatementWithDefs(defs []*StatementDef, input string) (Statement, error)
- func ParseMetaCommand(input string) (Statement, error)
- type StatementDef
- type StatementDescription
- type StreamingProcessor
- type SyncProtoStatement
- type TableDependency
- type TableHeader
- type TablePreviewProcessor
- type TeeOutputMetaCommand
- type TemplateVar
- type TimestampBoundVar
- type TimestampVar
- type TransactionManager
- func (tm *TransactionManager) BeginPendingTransaction(ctx context.Context, isolationLevel sppb.TransactionOptions_IsolationLevel, ...) error
- func (tm *TransactionManager) BeginReadOnlyTransaction(ctx context.Context, typ timestampBoundType, staleness time.Duration, ...) (time.Time, error)
- func (tm *TransactionManager) BeginReadOnlyTransactionLocked(ctx context.Context, typ timestampBoundType, staleness time.Duration, ...) (time.Time, error)
- func (tm *TransactionManager) BeginReadWriteTransaction(ctx context.Context, isolationLevel sppb.TransactionOptions_IsolationLevel, ...) error
- func (tm *TransactionManager) BeginReadWriteTransactionLocked(ctx context.Context, isolationLevel sppb.TransactionOptions_IsolationLevel, ...) error
- func (tm *TransactionManager) ClosePendingTransaction() error
- func (tm *TransactionManager) CloseReadOnlyTransaction() error
- func (tm *TransactionManager) CommitReadWriteTransaction(ctx context.Context) (spanner.CommitResponse, error)
- func (tm *TransactionManager) CommitReadWriteTransactionLocked(ctx context.Context) (spanner.CommitResponse, error)
- func (tm *TransactionManager) DetermineTransaction(ctx context.Context) (time.Time, error)
- func (tm *TransactionManager) DetermineTransactionAndState(ctx context.Context) (time.Time, bool, error)
- func (tm *TransactionManager) DetermineTransactionLocked(ctx context.Context) (time.Time, error)
- func (tm *TransactionManager) GetTransactionFlagsWithLock() (inTransaction bool, inReadWriteTransaction bool)
- func (tm *TransactionManager) InPendingTransaction() bool
- func (tm *TransactionManager) InReadOnlyTransaction() bool
- func (tm *TransactionManager) InReadWriteTransaction() bool
- func (tm *TransactionManager) InTransaction() bool
- func (tm *TransactionManager) NewTransactionOptionsBuilder() *TransactionOptionsBuilder
- func (tm *TransactionManager) RollbackReadWriteTransaction(ctx context.Context) error
- func (tm *TransactionManager) RollbackReadWriteTransactionLocked(ctx context.Context) error
- func (tm *TransactionManager) RunAnalyzeQuery(ctx context.Context, stmt spanner.Statement) (*sppb.QueryPlan, *sppb.ResultSetMetadata, error)
- func (tm *TransactionManager) RunInNewOrExistRwTx(ctx context.Context, ...) (*DMLResult, error)
- func (tm *TransactionManager) RunInNewOrExistRwTxLocked(ctx context.Context, ...) (*DMLResult, error)
- func (tm *TransactionManager) RunPartitionQuery(ctx context.Context, stmt spanner.Statement) ([]*spanner.Partition, *spanner.BatchReadOnlyTransaction, error)
- func (tm *TransactionManager) RunQuery(ctx context.Context, stmt spanner.Statement) (*spanner.RowIterator, *spanner.ReadOnlyTransaction, error)
- func (tm *TransactionManager) RunQueryWithStats(ctx context.Context, stmt spanner.Statement, implicit bool, ...) (*spanner.RowIterator, *spanner.ReadOnlyTransaction, error)
- func (tm *TransactionManager) SetClient(client *spanner.Client) error
- func (tm *TransactionManager) TransactionAttrsWithLock() transactionAttributes
- func (tm *TransactionManager) TransactionMode() transactionMode
- func (tm *TransactionManager) TransactionState() (mode transactionMode, isActive bool)
- func (tm *TransactionManager) TransitTransaction(ctx context.Context, ...) error
- func (tm *TransactionManager) ValidateDatabaseOperation() error
- type TransactionOptionsBuilder
- func (b *TransactionOptionsBuilder) Build() spanner.TransactionOptions
- func (b *TransactionOptionsBuilder) BuildIsolationLevel() sppb.TransactionOptions_IsolationLevel
- func (b *TransactionOptionsBuilder) BuildPriority() sppb.RequestOptions_Priority
- func (b *TransactionOptionsBuilder) WithIsolationLevel(level sppb.TransactionOptions_IsolationLevel) *TransactionOptionsBuilder
- func (b *TransactionOptionsBuilder) WithPriority(priority sppb.RequestOptions_Priority) *TransactionOptionsBuilder
- func (b *TransactionOptionsBuilder) WithTag(tag string) *TransactionOptionsBuilder
- type TransactionVars
- type TruncateTableStatement
- type TryPartitionedQueryStatement
- type TypedRows
- type UnimplementedVar
- type UnsetParamStatement
- type UpdateResult
- type UseDatabaseMetaCommand
- type UseStatement
- type ValidValuesEnumerator
- type VarHandler
- type VarRegistry
- func (r *VarRegistry) Add(name, value string) error
- func (r *VarRegistry) Get(name string) (string, error)
- func (r *VarRegistry) GetDescription(name string) (string, error)
- func (r *VarRegistry) GetVariable(name string) Variable
- func (r *VarRegistry) IsReadOnly(name string) (bool, error)
- func (r *VarRegistry) ListMultiValues() map[string]string
- func (r *VarRegistry) ListVariableInfo() map[string]struct{ ... }
- func (r *VarRegistry) ListVariables() map[string]string
- func (r *VarRegistry) Set(name, value string, isGoogleSQL bool) error
- type Variable
Constants ¶
const ( // defaultVertexAIModel / defaultVertexAILocation moved to // internal/mycli/feature/llm (#778); the GEMINI feature supplies them to the // kong parser as help-template vars in the full variant. DefaultAnalyzeColumns = "Rows:{{.Rows.Total}},Exec.:{{.ExecutionSummary.NumExecutions}},Total Latency:{{.Latency}}" )
const DefaultExplainPrintSections = string(planref.PrintPresetBasic)
DefaultExplainPrintSections is the default value of CLI_EXPLAIN_PRINT_SECTIONS.
Variables ¶
var ( ErrNoTransaction = errors.New("no active transaction") ErrNotInReadWriteTransaction = errors.New("not in read-write transaction") ErrNotInReadOnlyTransaction = errors.New("not in read-only transaction") ErrNotInPendingTransaction = errors.New("not in pending transaction") )
Transaction state errors
var DefaultParsedAnalyzeColumns = lo.Must(customListToTableRenderDefs(DefaultAnalyzeColumns))
var DefaultParsedExplainPrintSections = mustParseExplainPrintSections(DefaultExplainPrintSections)
DefaultParsedExplainPrintSections is the parsed form of DefaultExplainPrintSections.
Functions ¶
func FeatureState ¶ added in v0.33.0
func FeatureState[T any](ctx context.Context, s *Session, key string, init func(context.Context, *Session) (T, error)) (T, error)
FeatureState returns the per-Session value stored under key, initializing it via init on first use. A FAILED init is not cached: the error is returned and the next call retries, matching the retry semantics of the lazy per-feature fields this store replaces (BigQuery client, CQL session, doc cache) — a transient build failure must not poison the session. Concurrent calls for the same key serialize (init runs at most once at a time and successful init runs exactly once); different keys initialize independently. A value implementing io.Closer is closed at the end of Session.Close in reverse creation order.
NOTE: the design sketch in issue #778 §4.6 wrote this signature without a context parameter, but init requires one (its real callers, e.g. the lazy BigQuery client and doc cache builds, all have a ctx in hand). ctx is threaded through here so the guarded init receives it.
func GetExitCode ¶
GetExitCode returns the appropriate exit code based on the error type. It checks for ExitCodeError first and returns its exit code if found. Otherwise, it returns exitCodeSuccess for nil errors and exitCodeError for all other errors.
In the future, this function could be further enhanced to return different exit codes based on other error types, such as:
var validationErr *ValidationError
if errors.As(err, &validationErr) {
return exitCodeValidationError // e.g., 2
}
This would require defining additional exit code constants.
func GetTerminalSize ¶
GetTerminalSize returns the width of the terminal for the given io.Writer. It attempts to type assert the writer to *os.File to get the file descriptor. Returns an error if the terminal size cannot be determined.
func InterceptorLogger ¶
This code is simple enough to be copied and not imported.
func IsMetaCommand ¶
IsMetaCommand checks if a line starts with a backslash (meta command)
func LinkTypePred ¶
func LinkTypePred(typ string) func(cl *sppb.PlanNode_ChildLink) bool
func ListAvailableSamples ¶
func ListAvailableSamples() string
ListAvailableSamples returns a formatted list of available sample databases
func Main ¶
Main is the entry point called from the root main package. version and installFrom are passed from main via ldflags. features are the optional statement families (GEMINI/BIGQUERY/CQL, in All() order) contributed through the registration seam (issue #778); the full binary passes all of them and a slim variant passes none.
func NewExitCodeError ¶
NewExitCodeError creates a new ExitCodeError
func PS1PS2FuncToPromptFunc ¶
func ParseStatements ¶
ParseStatements parses DDL or DML statements from SQL/SDL content using memefish
func UnquoteString ¶ added in v0.33.0
UnquoteString trims surrounding single or double quotes from a def handler argument. Exported wrapper over unquoteString for feature packages.
func ValidateSpannerOptions ¶
func ValidateSpannerOptions(opts *spannerOptions) error
ValidateSpannerOptions validates the spannerOptions struct.
Types ¶
type AbortBatchStatement ¶
type AbortBatchStatement struct{}
type AddSplitPointsStatement ¶
type AddSplitPointsStatement struct {
SplitPoints []*databasepb.SplitPoints
}
type BatchDMLStatement ¶
type BatchManager ¶ added in v0.28.0
type BatchManager struct {
// contains filtered or unexported fields
}
BatchManager encapsulates batch statement accumulation state. It owns the lifecycle of a batch (start → buffer → run/abort) and provides a single source of truth for "am I in a batch?" checks.
func (*BatchManager) Abort ¶ added in v0.28.0
func (b *BatchManager) Abort()
Abort discards the current batch without executing it.
func (*BatchManager) Current ¶ added in v0.28.0
func (b *BatchManager) Current() Statement
Current returns the current batch statement for type-switching. Returns nil if no batch is active.
func (*BatchManager) Info ¶ added in v0.28.0
func (b *BatchManager) Info() *BatchInfo
Info returns metadata about the current batch, or nil if no batch is active.
func (*BatchManager) IsActive ¶ added in v0.28.0
func (b *BatchManager) IsActive() bool
IsActive reports whether a batch is currently in progress.
func (*BatchManager) SetCurrent ¶ added in v0.28.0
func (b *BatchManager) SetCurrent(stmt Statement)
SetCurrent directly sets the current batch statement. Used by auto-batch-DML to create a batch with an initial statement.
func (*BatchManager) Start ¶ added in v0.28.0
func (b *BatchManager) Start(mode batchMode) error
Start begins a new batch of the given mode. Returns an error if a batch is already active.
func (*BatchManager) TakeForExecution ¶ added in v0.28.0
func (b *BatchManager) TakeForExecution() (Statement, error)
TakeForExecution removes and returns the current batch for execution. Returns an error if no batch is active.
type BeginRoStatement ¶
type BeginRwStatement ¶
type BeginRwStatement struct {
IsolationLevel sppb.TransactionOptions_IsolationLevel
Priority sppb.RequestOptions_Priority
}
type BeginStatement ¶
type BeginStatement struct {
IsolationLevel sppb.TransactionOptions_IsolationLevel
Priority sppb.RequestOptions_Priority
}
type BulkDdlStatement ¶
type BulkDdlStatement struct {
Ddls []string
}
func (*BulkDdlStatement) String ¶
func (s *BulkDdlStatement) String() string
type Cli ¶
type Cli struct {
SessionHandler *SessionHandler
SystemVariables *systemVariables
// contains filtered or unexported fields
}
func (*Cli) ExitOnError ¶
func (*Cli) GetErrStream ¶
GetErrStream returns the error stream
func (*Cli) GetInStream ¶
func (c *Cli) GetInStream() io.ReadCloser
GetInStream returns the input stream
func (*Cli) GetTerminalSizeWithTty ¶
GetTerminalSizeWithTty returns the width of the terminal. It uses the TtyOutStream from StreamManager if available, otherwise falls back to attempting to type assert the writer to *os.File. Returns an error if the terminal size cannot be determined.
func (*Cli) GetTtyStream ¶
GetTtyStream returns the TTY stream for terminal operations
func (*Cli) PrintBatchError ¶
func (*Cli) PrintInteractiveError ¶
func (*Cli) PrintProgressingMark ¶
func (*Cli) PrintResult ¶
func (c *Cli) PrintResult(screenWidth int, result *Result, interactive bool, input string, w io.Writer) error
PrintResult prints a buffered result with the output decorations and the CLI_USE_PAGER pager applied. Statement execution does not go through this method (executeStatement shares one resultSink between streamed rows and the buffered display); it remains for direct callers holding a Result.
type CommitStatement ¶
type CommitStatement struct{}
type ConditionallyMutatingStatement ¶ added in v0.33.0
type ConditionallyMutatingStatement interface {
// contains filtered or unexported methods
}
ConditionallyMutatingStatement is a marker interface for statements whose mutation-ness cannot be decided statically from their Go type but only from their content (e.g. a CQL statement text). The READONLY guard in Session.ExecuteStatement consults isConditionallyMutating at the same single call site as the static MutationStatement marker.
Unlike MutationStatement, implementing this interface does NOT determine a pending Spanner transaction: it only participates in the READONLY guard, because such statements (CQL, BigQuery) do not use the Spanner transaction machinery.
type ConnectionVars ¶ added in v0.28.0
type ConnectionVars struct {
Project string // CLI_PROJECT
Instance string // CLI_INSTANCE
Database string // CLI_DATABASE
Role string // CLI_ROLE
}
ConnectionVars holds the connection identity. Project and Instance are fixed at startup; Database and Role are mutated in place only by USE/DETACH (SessionHandler.switchSession).
type CreateDatabaseStatement ¶
type CreateDatabaseStatement struct {
CreateStatement string
}
func (*CreateDatabaseStatement) String ¶
func (s *CreateDatabaseStatement) String() string
type CustomVar ¶
type CustomVar struct {
// contains filtered or unexported fields
}
CustomVar wraps a variable with custom getter/setter
type DMLResult ¶
type DMLResult struct {
Affected int64 // Total number of rows affected by the DML operation
CommitResponse spanner.CommitResponse // Commit response including timestamp and stats
Plan *sppb.QueryPlan // Query execution plan (when requested)
Metadata *sppb.ResultSetMetadata // Metadata about the result set
}
DMLResult holds the results of a DML operation execution including commit information.
type DdlStatement ¶
type DdlStatement struct {
Ddl string
}
func (*DdlStatement) String ¶
func (s *DdlStatement) String() string
type DependencyResolver ¶
type DependencyResolver struct {
// contains filtered or unexported fields
}
DependencyResolver manages table dependency resolution Note: This implementation works at the table level. For row-level dependency resolution that can handle circular FK relationships, see issue #438.
func NewDependencyResolver ¶
func NewDependencyResolver() *DependencyResolver
NewDependencyResolver creates a new dependency resolver
func (*DependencyResolver) BuildDependencyGraphWithTxn ¶
func (dr *DependencyResolver) BuildDependencyGraphWithTxn(ctx context.Context, txn *spanner.ReadOnlyTransaction) error
BuildDependencyGraphWithTxn queries the database and builds the complete dependency graph using a transaction
func (*DependencyResolver) GetDependencyInfo ¶
func (dr *DependencyResolver) GetDependencyInfo(tableName string) (*TableDependency, error)
GetDependencyInfo returns detailed dependency information for a table
func (*DependencyResolver) GetOrderForTables ¶
func (dr *DependencyResolver) GetOrderForTables(tablesToExport []string) ([]string, error)
GetOrderForTables returns specific tables in safe execution order
func (*DependencyResolver) GetTableOrder ¶
func (dr *DependencyResolver) GetTableOrder() ([]string, error)
GetTableOrder returns all tables in safe execution order. It assumes that BuildDependencyGraph has already been called.
type DescribeStatement ¶
type DescribeStatement struct {
Statement string
IsDML bool // Whether the statement being described is a DML
}
func (*DescribeStatement) String ¶
func (s *DescribeStatement) String() string
type DetachStatement ¶
type DetachStatement struct {
NopStatement
}
DetachStatement is actually implemented in cli.go because it needs to replace Session pointer in Cli.
type DetachedCompatible ¶
type DetachedCompatible interface {
// contains filtered or unexported methods
}
DetachedCompatible is a marker interface for statements that can run in Detached session mode (admin operation only mode). Statements implementing this interface can execute when session.IsDetached() is true.
type DisableOutputRedirectMetaCommand ¶
type DisableOutputRedirectMetaCommand struct{}
DisableOutputRedirectMetaCommand disables output redirect using \o (with no args) syntax
type DisableTeeMetaCommand ¶
type DisableTeeMetaCommand struct{}
DisableTeeMetaCommand disables output tee using \t syntax
type DisplayVars ¶ added in v0.28.0
type DisplayVars struct {
CLIFormat enums.DisplayMode // CLI_FORMAT
Verbose bool // CLI_VERBOSE
Prompt string // CLI_PROMPT
Prompt2 string // CLI_PROMPT2
HistoryFile string // CLI_HISTORY_FILE
TabWidth int64 // CLI_TAB_WIDTH
TabVisualize bool // CLI_TAB_VISUALIZE
EnableHighlight bool // CLI_ENABLE_HIGHLIGHT
UsePager bool // CLI_USE_PAGER
AutoWrap bool // CLI_AUTOWRAP
FixedWidth *int64 // CLI_FIXED_WIDTH
MultilineProtoText bool // CLI_PROTOTEXT_MULTILINE
MarkdownCodeblock bool // CLI_MARKDOWN_CODEBLOCK
SkipColumnNames bool // CLI_SKIP_COLUMN_NAMES
SuppressResultLines bool // CLI_SUPPRESS_RESULT_LINES
ExplainFormat enums.ExplainFormat // CLI_EXPLAIN_FORMAT
ExplainWrapWidth int64 // CLI_EXPLAIN_WRAP_WIDTH
ExplainHangingIndent bool // CLI_EXPLAIN_HANGING_INDENT
ExplainPrintSections string // CLI_EXPLAIN_PRINT_SECTIONS
ParsedExplainPrintSections planref.PrintSections
OutputTemplateFile string // CLI_OUTPUT_TEMPLATE_FILE (computed getter/setter)
OutputTemplate *template.Template
AnalyzeColumns string // CLI_ANALYZE_COLUMNS
ParsedAnalyzeColumns []columnRenderDef
InlineStats string // CLI_INLINE_STATS
ParsedInlineStats []inlineStatsDef
SQLTableName string // CLI_SQL_TABLE_NAME
SQLBatchSize int64 // CLI_SQL_BATCH_SIZE
EnableProgressBar bool // CLI_ENABLE_PROGRESS_BAR
StyledOutput enums.StyledMode // CLI_STYLED_OUTPUT
WidthStrategy enums.WidthStrategy // CLI_WIDTH_STRATEGY
TypeStylesRaw string // CLI_TYPE_STYLES (raw string, parsed into systemVariables.typeStyles/nullStyle)
}
DisplayVars holds display and output formatting configuration.
type DmlStatement ¶
type DmlStatement struct {
Dml string
}
func (*DmlStatement) String ¶
func (s *DmlStatement) String() string
type DropDatabaseStatement ¶
type DropDatabaseStatement struct {
DatabaseId string
}
type DumpDatabaseStatement ¶
type DumpDatabaseStatement struct{}
DumpDatabaseStatement represents DUMP DATABASE statement It exports both DDL and data for all tables in the database
type DumpSchemaStatement ¶
type DumpSchemaStatement struct{}
DumpSchemaStatement represents DUMP SCHEMA statement It exports only DDL statements without any data
type DumpTablesStatement ¶
type DumpTablesStatement struct {
Tables []string
}
DumpTablesStatement represents DUMP TABLES statement It exports data only for specified tables (no DDL)
type EndpointVar ¶
type EndpointVar struct {
// contains filtered or unexported fields
}
EndpointVar handles CLI_ENDPOINT (host:port). Read-only, like CLI_HOST and CLI_PORT which it is derived from: the endpoint is part of the immutable StartupConfig, and changing it after startup would not reconnect the live session.
func (*EndpointVar) Get ¶
func (e *EndpointVar) Get() (string, error)
func (*EndpointVar) Set ¶
func (e *EndpointVar) Set(value string) error
type EnumVar ¶
type EnumVar[T comparable] struct { // contains filtered or unexported fields }
EnumVar handles enum-like variables
func AutocommitDMLModeVar ¶
func AutocommitDMLModeVar(ptr *enums.AutocommitDMLMode) *EnumVar[enums.AutocommitDMLMode]
AutocommitDMLModeVar handles AUTOCOMMIT_DML_MODE using enumer-generated methods
func DisplayModeVar ¶
func DisplayModeVar(ptr *enums.DisplayMode) *EnumVar[enums.DisplayMode]
DisplayModeVar creates an enum handler for DisplayMode
func ExplainFormatVar ¶
func ExplainFormatVar(ptr *enums.ExplainFormat) *EnumVar[enums.ExplainFormat]
ExplainFormatVar creates an enum handler for ExplainFormat
func ParseModeVar ¶
ParseModeVar creates an enum handler for ParseMode
func StreamingModeVar ¶
func StreamingModeVar(ptr *enums.StreamingMode) *EnumVar[enums.StreamingMode]
StreamingModeVar creates an enum handler for StreamingMode
func StyledModeVar ¶ added in v0.28.0
func StyledModeVar(ptr *enums.StyledMode) *EnumVar[enums.StyledMode]
func WidthStrategyVar ¶ added in v0.29.0
func WidthStrategyVar(ptr *enums.WidthStrategy) *EnumVar[enums.WidthStrategy]
WidthStrategyVar creates an enum handler for WidthStrategy
func (*EnumVar[T]) ValidValues ¶
ValidValues returns sorted valid values as GoogleSQL string literals.
type ErrAddNotSupported ¶
type ErrAddNotSupported struct {
Name string
}
ErrAddNotSupported is returned when ADD operation is not supported for a variable
func (*ErrAddNotSupported) Error ¶
func (e *ErrAddNotSupported) Error() string
type ErrUnknownVariable ¶
type ErrUnknownVariable struct {
Name string
}
ErrUnknownVariable is returned when a variable name is not recognized
func (*ErrUnknownVariable) Error ¶
func (e *ErrUnknownVariable) Error() string
type ExecuteStatementArgs ¶
type ExecuteStatementArgs struct {
Statement string `json:"statement" jsonschema:"Valid spanner-mycli statement to execute"`
}
ExecuteStatementArgs represents the arguments for the execute_statement tool
type ExitCodeError ¶
type ExitCodeError struct {
// contains filtered or unexported fields
}
ExitCodeError represents an error that only carries an exit code without a message
func (*ExitCodeError) Error ¶
func (e *ExitCodeError) Error() string
Error implements the error interface
type ExitStatement ¶
type ExitStatement struct {
NopStatement
}
type ExplainAnalyzeDmlStatement ¶
type ExplainAnalyzeDmlStatement struct {
Dml string
Format enums.ExplainFormat
Width int64
PrintSections *planref.PrintSections
}
type ExplainAnalyzeStatement ¶
type ExplainAnalyzeStatement struct {
Query string
Format enums.ExplainFormat
Width int64
PrintSections *planref.PrintSections
}
type ExplainLastQueryStatement ¶
type ExplainLastQueryStatement struct {
Analyze bool
Format enums.ExplainFormat
Width int64
PrintSections *planref.PrintSections
}
type ExplainStatement ¶
type ExplainStatement struct {
Explain string
IsDML bool // Whether the statement being explained is a DML
Format enums.ExplainFormat
Width int64
PrintSections *planref.PrintSections
}
func (*ExplainStatement) String ¶
func (s *ExplainStatement) String() string
type FKReference ¶
type FKReference struct {
ConstraintName string `spanner:"CONSTRAINT_NAME"`
ChildTable string `spanner:"CHILD_TABLE"`
ParentTable string `spanner:"PARENT_TABLE"`
}
FKReference represents a foreign key relationship between tables
type Feature ¶ added in v0.33.0
type Feature struct {
// Name identifies the feature (e.g. "GEMINI", "BIGQUERY", "CQL").
Name string
// StatementDefs are the client-side statement definitions the feature adds.
// They are appended after the core table, so feature keywords must be
// leading unique tokens (the #728 non-shadowing invariant proves this over
// the merged table).
StatementDefs []*StatementDef
// Vars are the system variables the feature registers. They ride the same
// varDef machinery (SET policy, RESET, generated docs) as core variables.
Vars []FeatureVar
// Flags is an optional pointer to a kong-tagged struct appended to the CLI
// parser via kong.Plugins. Nil when the feature contributes no flags.
Flags any
// KongVars supplies optional help-template values (e.g. default model
// names) merged into the parser's kong.Vars.
KongVars map[string]string
// ApplyFlags, when non-nil, routes parsed flag values into system variables
// through the registry after flag parsing. The set argument forwards to
// systemVariables.SetFromSimple, keeping feature flags out of the direct
// assignment path (consistent with the #725 PR4 direction). Invoked by
// applyFeatureFlags in initializeSystemVariables, before --set processing;
// GEMINI's --vertexai-* flags are the first user (feature/llm).
ApplyFlags func(set func(name, value string) error) error
}
Feature is a single optional statement family contributed to Main. Its StatementDefs are appended after the core defs in All() order; its Vars are converted into the system-variable registry; its Flags/KongVars are wired into the kong parser.
type FeatureVar ¶ added in v0.33.0
type FeatureVar struct {
Name string
Desc string
Var Variable
ReadOnly bool // read-only via SET
InitOnly bool // settable only before session creation
TxnGuard bool // SET rejected while a transaction is active
NoLocal bool // opt-out of SET LOCAL
NoReset bool // opt-out of RESET ALL
}
FeatureVar is the exported declaration shape for a feature-contributed system variable. Core converts it into an internal varDef at registry construction (see VarRegistry.registerAll); the boolean fields mirror the varDef policy flags. The variable's live state is owned by the feature package via Var.
type FeatureVars ¶ added in v0.28.0
type FeatureVars struct {
FuzzyFinderKey string // CLI_FUZZY_FINDER_KEY (empty = disabled)
FuzzyFinderOptions string // CLI_FUZZY_FINDER_OPTIONS
MCP bool // CLI_MCP
// CLI_VERTEXAI_PROJECT/MODEL/LOCATION state moved to the GEMINI feature's own
// config struct in internal/mycli/feature/llm (#778).
EchoExecutedDDL bool // CLI_ECHO_EXECUTED_DDL
EchoInput bool // CLI_ECHO_INPUT
AsyncDDL bool // CLI_ASYNC_DDL
AutoConnectAfterCreate bool // CLI_AUTO_CONNECT_AFTER_CREATE
LogLevel slog.Level // CLI_LOG_LEVEL
DatabaseDialect databasepb.DatabaseDialect // CLI_DATABASE_DIALECT
}
FeatureVars holds feature flags and experimental configuration.
type HelpStatement ¶
type HelpStatement struct{}
type HelpVariablesStatement ¶
type HelpVariablesStatement struct{}
type IntGetterVar ¶
type IntGetterVar struct {
// contains filtered or unexported fields
}
IntGetterVar handles integer variables with custom getters
func (*IntGetterVar) Get ¶
func (i *IntGetterVar) Get() (string, error)
func (*IntGetterVar) Set ¶
func (i *IntGetterVar) Set(value string) error
type InternalVars ¶ added in v0.28.0
type InternalVars struct {
ProtoDescriptorFile []string // CLI_PROTO_DESCRIPTOR_FILE
ProtoDescriptor *descriptorpb.FileDescriptorSet
}
InternalVars holds internal state not directly exposed as system variables.
type LastQueryCache ¶
type LastResult ¶ added in v0.32.0
type LastResult struct {
ReadTimestamp time.Time // READ_TIMESTAMP
CommitTimestamp time.Time // COMMIT_TIMESTAMP
CommitResponse *sppb.CommitResponse // COMMIT_RESPONSE
QueryCache *LastQueryCache
}
LastResult holds outputs of the most recently executed statement or transaction. It is written by statement execution and read back through read-only system variables (READ_TIMESTAMP, COMMIT_TIMESTAMP, COMMIT_RESPONSE) and last-query features such as CLI_INLINE_STATS. Unlike the *Vars groups, nothing here is user-settable.
type LogLevelVar ¶
type LogLevelVar struct {
// contains filtered or unexported fields
}
LogLevelVar handles CLI_LOG_LEVEL
func (*LogLevelVar) Get ¶
func (l *LogLevelVar) Get() (string, error)
func (*LogLevelVar) Set ¶
func (l *LogLevelVar) Set(value string) error
func (*LogLevelVar) ValidValues ¶
func (l *LogLevelVar) ValidValues() []string
ValidValues returns the standard log level names as GoogleSQL string literals.
type MarksDetachedCompatible ¶ added in v0.33.0
type MarksDetachedCompatible struct{}
MarksDetachedCompatible marks an embedding statement as DetachedCompatible.
type MarksMutation ¶ added in v0.33.0
type MarksMutation struct{}
MarksMutation marks an embedding statement as a MutationStatement.
type MetaCommandStatement ¶
type MetaCommandStatement interface {
Statement
// contains filtered or unexported methods
}
MetaCommandStatement is a marker interface for meta commands (commands starting with \). Meta commands are not SQL statements and have special handling in the CLI.
type MultiValueVar ¶ added in v0.33.0
MultiValueVar is an optional capability for a Variable whose SHOW VARIABLE result has multiple columns (e.g. COMMIT_RESPONSE, which surfaces COMMIT_TIMESTAMP and MUTATION_COUNT). Such a variable's plain Get returns an error (the value cannot be rendered as a single string); SHOW VARIABLE and SHOW VARIABLES consult GetMulti instead. Returning errIgnored signals that the value is currently unavailable and should be omitted.
type MutateStatement ¶
type MutationClassifier ¶ added in v0.33.0
type MutationClassifier struct {
Classify func() bool
}
MutationClassifier marks an embedding statement as a ConditionallyMutatingStatement whose mutation-ness is decided at runtime by Classify (e.g. CQL/BIGQUERY inspecting the statement's leading keyword). A nil Classify classifies as mutating: the zero value of an embedding statement fails closed under the READONLY guard instead of panicking.
type MutationStatement ¶
type MutationStatement interface {
// contains filtered or unexported methods
}
MutationStatement is a marker interface for mutation statements. Mutation statements are not permitted in a read-only transaction. It determines pending transactions.
type NopStatement ¶
type NopStatement struct{}
type OutputContext ¶
type OutputContext struct {
Verbose bool
IsExecutedDML bool
// Timestamp is kept for custom templates written before the read/commit split.
Timestamp string
ReadTimestamp string
CommitTimestamp string
Stats *QueryStats
CommitStats *sppb.CommitResponse_CommitStats
Metrics *metrics.ExecutionMetrics
}
type OutputRedirectMetaCommand ¶
type OutputRedirectMetaCommand struct {
FilePath string
}
OutputRedirectMetaCommand redirects output to a file using \o syntax (PostgreSQL-style: file only)
type PartitionStatement ¶
type PartitionStatement struct{ SQL string }
type PartitionedDmlStatement ¶
type PartitionedDmlStatement struct {
Dml string
}
type PromptMetaCommand ¶
type PromptMetaCommand struct {
PromptString string
}
PromptMetaCommand changes the prompt string using \R syntax
type ProtoDescriptorVar ¶
type ProtoDescriptorVar struct {
// contains filtered or unexported fields
}
ProtoDescriptorVar handles CLI_PROTO_DESCRIPTOR_FILE with ADD support
func (*ProtoDescriptorVar) Add ¶
func (p *ProtoDescriptorVar) Add(value string) error
func (*ProtoDescriptorVar) Get ¶
func (p *ProtoDescriptorVar) Get() (string, error)
func (*ProtoDescriptorVar) Set ¶
func (p *ProtoDescriptorVar) Set(value string) error
type ProtoEnumVar ¶
type ProtoEnumVar[T ~int32] struct { // contains filtered or unexported fields }
ProtoEnumVar handles Protocol Buffer enum variables
func DatabaseDialectVar ¶
func DatabaseDialectVar(ptr *databasepb.DatabaseDialect) *ProtoEnumVar[databasepb.DatabaseDialect]
func IsolationLevelVar ¶
func IsolationLevelVar(ptr *sppb.TransactionOptions_IsolationLevel) *ProtoEnumVar[sppb.TransactionOptions_IsolationLevel]
func QueryModeVar ¶
func QueryModeVar(ptr *sppb.ExecuteSqlRequest_QueryMode) *ProtoEnumVar[sppb.ExecuteSqlRequest_QueryMode]
func RPCPriorityVar ¶
func RPCPriorityVar(ptr *sppb.RequestOptions_Priority) *ProtoEnumVar[sppb.RequestOptions_Priority]
func ReadLockModeVar ¶
func ReadLockModeVar(ptr *sppb.TransactionOptions_ReadWrite_ReadLockMode) *ProtoEnumVar[sppb.TransactionOptions_ReadWrite_ReadLockMode]
ReadLockModeVar creates an enum handler for ReadLockMode
func (*ProtoEnumVar[T]) Get ¶
func (p *ProtoEnumVar[T]) Get() (string, error)
func (*ProtoEnumVar[T]) Set ¶
func (p *ProtoEnumVar[T]) Set(value string) error
func (*ProtoEnumVar[T]) ValidValues ¶
func (p *ProtoEnumVar[T]) ValidValues() []string
ValidValues returns sorted prefix-stripped valid values as GoogleSQL string literals.
type QueryIndexAdvice ¶
QueryIndexAdvice holds an index recommendation from the Spanner query advisor.
type QueryResult ¶
type QueryResult struct {
Iterator *spanner.RowIterator
Transaction *spanner.ReadOnlyTransaction
}
QueryResult holds the result of a query operation with optional transaction.
type QueryStats ¶
type QueryStats = spanstats.QueryStats
QueryStats contains query statistics. Some fields may not have a valid value depending on the environment. For example, only ElapsedTime and RowsReturned has valid value for Cloud Spanner Emulator.
type QueryVars ¶ added in v0.28.0
type QueryVars struct {
StatementTimeout *time.Duration // STATEMENT_TIMEOUT
RPCPriority sppb.RequestOptions_Priority // RPC_PRIORITY
ReadOnlyStaleness *spanner.TimestampBound // READ_ONLY_STALENESS
OptimizerVersion string // OPTIMIZER_VERSION
OptimizerStatisticsPackage string // OPTIMIZER_STATISTICS_PACKAGE
AutoPartitionMode bool // AUTO_PARTITION_MODE
DataBoostEnabled bool // DATA_BOOST_ENABLED
MaxPartitionedParallelism int64 // MAX_PARTITIONED_PARALLELISM
QueryMode *sppb.ExecuteSqlRequest_QueryMode // CLI_QUERY_MODE
TryPartitionQuery bool // CLI_TRY_PARTITION_QUERY
DirectedRead *sppb.DirectedReadOptions // CLI_DIRECT_READ
StreamingMode enums.StreamingMode // CLI_TABLE_STREAMING
TablePreviewRows int64 // CLI_TABLE_PREVIEW_ROWS
BuildStatementMode enums.ParseMode // CLI_PARSE_MODE
Profile bool // CLI_PROFILE
LintPlan bool // CLI_LINT_PLAN
}
QueryVars holds query execution configuration.
type ReadOnlyVar ¶
type ReadOnlyVar struct {
// contains filtered or unexported fields
}
ReadOnlyVar creates a read-only variable with custom getter
func NewReadOnlyVar ¶
func NewReadOnlyVar(getter func() string) *ReadOnlyVar
NewReadOnlyVar creates a new read-only variable
func (*ReadOnlyVar) Get ¶
func (r *ReadOnlyVar) Get() (string, error)
func (*ReadOnlyVar) Set ¶
func (r *ReadOnlyVar) Set(value string) error
type Result ¶
type Result struct {
ColumnAlign []tw.Align // optional
Rows []Row
// Typed holds the raw typed rows for a buffered query result; rendering
// derives display cells or replays raw rows at display time (printTableData).
// Mutually exclusive with Rows/RenderedOutput/Streamed (see TypedRows).
Typed *TypedRows
// RenderedOutput holds pre-rendered text (kind (d)) that should be written
// before appendices and result lines. Used when output must stay atomic until
// after execution side effects such as implicit DML commit have succeeded.
// A non-nil RenderedOutput is the signal to write it instead of formatting a
// body payload (printResult); the two producers (DUMP buffered fallback, DML
// THEN RETURN) always set it together with their content.
RenderedOutput []byte
Predicates []string
Appendices []ResultAppendix
AffectedRows int
AffectedRowsType rowCountType
Stats QueryStats
// IsExecutedDML indicates this is an executed DML statement (INSERT/UPDATE/DELETE) that can report affected rows
IsExecutedDML bool
ReadTimestamp time.Time // For SELECT/read-only transactions
CommitTimestamp time.Time // For COMMIT/DML operations
ForceVerbose bool
CommitStats *sppb.CommitResponse_CommitStats
KeepVariables bool
TableHeader TableHeader
ForceWrap bool
LintResults []string
IndexAdvice []QueryIndexAdvice // Index recommendations from query advisor
PreInput string
// SQLExportAllowed indicates that the display-text row values in Rows have
// been formatted as SQL literals using spanvalue.LiteralFormatConfig instead
// of regular display formatting, so they may be replayed into INSERT
// statements. This flag governs the display-text (Rows) replay path; the
// typed (Typed) path carries its own TypedRows.SQLExportAllowed.
// This flag is set to true only when:
// - executeSQL is called with SQL export format (SQL_INSERT, SQL_INSERT_OR_IGNORE, SQL_INSERT_OR_UPDATE)
// - The values in Rows are valid SQL literals that can be used in INSERT statements
// When false, SQL export formats will fall back to table format to prevent invalid SQL generation.
// Examples of statements that have this as false:
// - SHOW CREATE TABLE, SHOW TABLES (metadata queries)
// - EXPLAIN, EXPLAIN ANALYZE (query plan information)
// - DML with THEN RETURN (uses regular formatting)
SQLExportAllowed bool
// SQLTableNameForExport stores the auto-detected or explicitly set table name for SQL export.
// This field is populated during query execution when SQL export formats are used.
// It ensures the table name is available during the formatting phase, even in buffered mode.
SQLTableNameForExport string
BatchInfo *BatchInfo
PartitionCount int
Streamed bool // Indicates rows were streamed and not buffered
Metrics *metrics.ExecutionMetrics // Performance metrics for query execution
}
type ResultAppendix ¶ added in v0.31.0
ResultAppendix is a titled set of post-table diagnostic lines.
type RollbackStatement ¶
type RollbackStatement struct{}
type RowProcessor ¶
type RowProcessor interface {
// Init is called once after metadata becomes available (after first row fetch).
// This is where headers are written for formats like CSV, or table initialization occurs.
Init(metadata *sppb.ResultSetMetadata, sysVars *systemVariables) error
// ProcessRow is called for each row in the result set.
// In buffered mode, rows are collected. In streaming mode, rows are output immediately.
ProcessRow(row Row) error
// Finish is called after all rows have been processed.
// It receives final statistics and row count for summary output.
Finish(stats QueryStats, rowCount int64) error
}
RowProcessor handles rows either in buffered or streaming mode. It provides a unified interface for processing query results regardless of whether rows are collected first or streamed directly.
func NewStreamingProcessorForMode ¶
func NewStreamingProcessorForMode(mode enums.DisplayMode, out io.Writer, sysVars *systemVariables, screenWidth int) RowProcessor
NewStreamingProcessorForMode creates a streaming processor for the given display mode. Returns nil if the mode doesn't support streaming yet. This is primarily used for testing - production code uses createStreamingProcessor.
type RunBatchStatement ¶
type RunBatchStatement struct{}
type RunPartitionStatement ¶
type RunPartitionStatement struct{ Token string }
type RunPartitionedQueryStatement ¶
type RunPartitionedQueryStatement struct{ SQL string }
type SampleDatabase ¶
type SampleDatabase struct {
Name string `json:"name"` // Unique identifier for the sample
Description string `json:"description"` // Human-readable description
Dialect string `json:"dialect"` // SQL dialect (GOOGLE_STANDARD_SQL or POSTGRESQL)
SchemaURI string `json:"schemaURI"` // URI to schema file (can be relative or absolute)
DataURI string `json:"dataURI,omitempty"` // URI to data file (optional)
Source string `json:"source,omitempty"` // Documentation URL or description (optional)
// Runtime fields (not in JSON)
BaseDir string `json:"-"` // Base directory for relative path resolution
IsEmbedded bool `json:"-"` // Distinguishes embedded:// from file:// base URIs
ParsedDialect databasepb.DatabaseDialect `json:"-"` // Parsed dialect enum value
}
SampleDatabase represents both metadata and runtime configuration
func (*SampleDatabase) ResolveURIs ¶
func (s *SampleDatabase) ResolveURIs()
ResolveURIs converts relative paths to absolute URIs based on BaseDir
type SelectStatement ¶
type SelectStatement struct {
Query string
}
func (*SelectStatement) String ¶
func (s *SelectStatement) String() string
type Session ¶
type Session struct {
// contains filtered or unexported fields
}
Session represents a database session with transaction management.
func NewAdminSession ¶
func NewSession ¶
func (*Session) AuthOptions ¶ added in v0.33.0
func (s *Session) AuthOptions(ctx context.Context, credential []byte, allowWithoutAuthentication bool) ([]option.ClientOption, error)
AuthOptions builds client auth options for the given credential using the session's system variables. Exported wrapper over createAuthClientOptions for feature packages that build their own (non-Spanner) clients.
func (*Session) CredentialBytes ¶ added in v0.33.0
CredentialBytes returns a defensive copy of the raw --credential bytes stored on the durable startup config. Feature packages that build their own (non-Spanner) clients use it as the credential source; because the bytes live in the process-wide startup config rather than on the Session, they survive USE/DETACH session replacement without any carry-over machinery (#778 §4.6). Returns nil when no credential file was supplied.
func (*Session) DatabaseExists ¶
func (*Session) DatabasePath ¶
func (*Session) ExecuteStatement ¶
ExecuteStatement executes stmt. If stmt is a MutationStatement, pending transaction is determined and fails if there is an active read-only transaction.
func (*Session) ExecuteStatementWithOutput ¶ added in v0.32.0
func (s *Session) ExecuteStatementWithOutput(ctx context.Context, stmt Statement, out outputContext) (*Result, error)
ExecuteStatementWithOutput executes stmt with out as the per-statement output destination. Statements executed re-entrantly during stmt (e.g. RUN BATCH re-entering ExecuteStatement) inherit the same destination.
func (*Session) GetDatabaseDdlCached ¶ added in v0.29.0
func (s *Session) GetDatabaseDdlCached(ctx context.Context) (*adminpb.GetDatabaseDdlResponse, error)
GetDatabaseDdlCached returns the cached DDL response, fetching from the API only when the cache is stale (TTL expired or schema generation changed).
func (*Session) GetDatabaseSchema ¶
func (s *Session) GetDatabaseSchema(ctx context.Context) ([]string, *descriptorpb.FileDescriptorSet, error)
func (*Session) IncrementSchemaGeneration ¶
func (s *Session) IncrementSchemaGeneration()
IncrementSchemaGeneration bumps the schema generation counter, signaling that schema-dependent caches should be invalidated.
func (*Session) InstanceExists ¶
InstanceExists reports whether the configured Spanner instance is reachable. The caller's ctx is honored (including cancellation); a 30s timeout is layered on top as an upper bound so a hung RPC cannot block indefinitely.
func (*Session) InstancePath ¶
func (*Session) IsDetached ¶
func (*Session) Mode ¶
func (s *Session) Mode() SessionMode
func (*Session) ProjectID ¶ added in v0.33.0
ProjectID returns the configured Spanner project for the session.
func (*Session) RecreateClient ¶
RecreateClient closes the current client and creates a new client for the session. The caller's ctx governs client creation so cancellation is respected.
func (*Session) RequiresDatabaseConnection ¶
func (*Session) SchemaGeneration ¶
SchemaGeneration returns the current schema generation counter.
func (*Session) ValidateDatabaseOperation ¶
func (*Session) ValidateDetachedOperation ¶
func (*Session) ValidateStatementExecution ¶
type SessionHandler ¶
type SessionHandler struct {
*Session
}
SessionHandler manages a session pointer and can handle session-changing statements
func NewSessionHandler ¶
func NewSessionHandler(session *Session) *SessionHandler
func (*SessionHandler) Close ¶
func (h *SessionHandler) Close()
func (*SessionHandler) ExecuteStatement ¶
ExecuteStatement executes a statement, handling session-changing statements appropriately
func (*SessionHandler) ExecuteStatementWithOutput ¶ added in v0.32.0
func (h *SessionHandler) ExecuteStatementWithOutput(ctx context.Context, stmt Statement, out outputContext) (*Result, error)
ExecuteStatementWithOutput executes a statement like ExecuteStatement, routing streamed output to out. Session-changing statements (USE/DETACH) produce no streamed output and take their normal path.
func (*SessionHandler) GetSession ¶
func (h *SessionHandler) GetSession() *Session
type SetAddStatement ¶
type SetLocalStatement ¶ added in v0.32.0
SetLocalStatement implements `SET LOCAL <name> = <value>`: the change is scoped to the current transaction. The previous value is recorded in the transaction's undo log (TransactionManager.localVarUndo) and restored when the transaction ends, whether by COMMIT, ROLLBACK, or CLOSE. Following java-spanner, SET LOCAL outside a transaction is an error.
type SetParamTypeStatement ¶
type SetParamValueStatement ¶
type SetStatement ¶
type SetTransactionStatement ¶
type SetTransactionStatement struct {
IsReadOnly bool
}
type ShellMetaCommand ¶
type ShellMetaCommand struct {
Command string
}
ShellMetaCommand executes system shell commands using \! syntax
type ShowColumnsStatement ¶
type ShowCreateStatement ¶
type ShowDatabasesStatement ¶
type ShowDatabasesStatement struct{}
type ShowDdlsStatement ¶
type ShowDdlsStatement struct{}
type ShowIndexStatement ¶
type ShowLocalProtoStatement ¶
type ShowLocalProtoStatement struct{}
type ShowOperationStatement ¶
type ShowParamsStatement ¶
type ShowParamsStatement struct{}
type ShowPlanNodeStatement ¶
type ShowPlanNodeStatement struct {
NodeID int
}
type ShowQueryProfileStatement ¶
type ShowQueryProfileStatement struct {
Fprint int64
}
type ShowQueryProfilesStatement ¶
type ShowQueryProfilesStatement struct{}
type ShowRemoteProtoStatement ¶
type ShowRemoteProtoStatement struct{}
type ShowSchemaUpdateOperations ¶
type ShowSchemaUpdateOperations struct{}
type ShowSplitPointsStatement ¶
type ShowSplitPointsStatement struct{}
type ShowTablesStatement ¶
type ShowTablesStatement struct {
Schema string
}
type ShowVariableStatement ¶
type ShowVariableStatement struct {
VarName string
}
type ShowVariablesStatement ¶
type ShowVariablesStatement struct{}
type SourceMetaCommand ¶
type SourceMetaCommand struct {
FilePath string
}
SourceMetaCommand executes SQL statements from a file using \. syntax
type StartBatchStatement ¶
type StartBatchStatement struct {
Mode batchMode
}
type StartupConfig ¶ added in v0.32.0
type StartupConfig struct {
Host string // CLI_HOST
Port int // CLI_PORT
Insecure bool // CLI_INSECURE
WithoutAuthentication bool
ImpersonateServiceAccount string // CLI_IMPERSONATE_SERVICE_ACCOUNT
EnableADCPlus bool // CLI_ENABLE_ADC_PLUS
EmulatorPlatform string // CLI_EMULATOR_PLATFORM
LogGrpc bool // CLI_LOG_GRPC
MCP bool // CLI_MCP
SkipSystemCommand bool // CLI_SKIP_SYSTEM_COMMAND
// Credential holds the raw --credential file bytes, if any. It is the durable
// home for the credential (read-only, not a registered variable): features
// that build non-Spanner clients read it via Session.CredentialBytes(), and
// it survives USE/DETACH because startup config is not replaced on session
// switch (#778 §4.6). Do not mutate after startup.
Credential []byte
// Embedded runtime overrides used by tests and the embedded emulator.
EmbeddedClientOptions []option.ClientOption
EmbeddedClientConfig *spanner.ClientConfig
}
StartupConfig holds configuration that is immutable after startup. It is populated by parseFlags/createSystemVariablesFromOptions (and, for the embedded runtime, by setup code in app.go before any session is created) and must never be written afterwards: every corresponding system variable is registered read-only, and USE/DETACH do not touch it. Exception: EnableADCPlus is session-init-only; its custom setter rejects writes once a session exists (see var_registry.go).
type Statement ¶
func BuildCLIStatement ¶
func BuildStatement ¶
func BuildStatementWithDefs ¶ added in v0.33.0
func BuildStatementWithDefs(defs []*StatementDef, input string) (Statement, error)
BuildStatementWithDefs matches input against the given client-side statement defs (first-match-wins, same dispatch as BuildCLIStatement) and builds the corresponding Statement. Exported so feature tests can exercise their defs directly.
func ParseMetaCommand ¶
ParseMetaCommand parses a meta command string into a Statement
type StatementDef ¶ added in v0.33.0
type StatementDef = clientSideStatementDef
StatementDef is the exported alias for the client-side statement definition. Its fields (Descriptions, Pattern, HandleGroups, Completion) are already exported, so feature packages construct these directly.
func MergedStatementDefs ¶ added in v0.33.0
func MergedStatementDefs(features ...Feature) []*StatementDef
MergedStatementDefs returns the core statement table followed by each feature's StatementDefs in argument order. With no features it returns a copy of the core table, so the merged surface is identical to core.
type StatementDescription ¶ added in v0.33.0
type StatementDescription = clientSideStatementDescription
StatementDescription is the exported alias for a statement's human-readable description (Usage/Syntax/Note).
type StreamingProcessor ¶
type StreamingProcessor struct {
// contains filtered or unexported fields
}
StreamingProcessor processes rows immediately as they arrive. This reduces memory usage and improves Time To First Byte for large result sets.
func NewStreamingProcessor ¶
func NewStreamingProcessor(formatter format.StreamingFormatter, out io.Writer, screenWidth int) *StreamingProcessor
NewStreamingProcessor creates a processor that outputs rows immediately.
func (*StreamingProcessor) Finish ¶
func (p *StreamingProcessor) Finish(stats QueryStats, rowCount int64) error
Finish completes the streaming output.
func (*StreamingProcessor) Init ¶
func (p *StreamingProcessor) Init(metadata *sppb.ResultSetMetadata, sysVars *systemVariables) error
Init initializes the streaming processor and writes headers if needed.
func (*StreamingProcessor) ProcessRow ¶
func (p *StreamingProcessor) ProcessRow(row Row) error
ProcessRow immediately outputs a row.
type SyncProtoStatement ¶
type TableDependency ¶
type TableDependency struct {
TableName string
ParentTable string // INTERLEAVE parent
OnDeleteAction string // CASCADE, NO ACTION for INTERLEAVE
ChildrenTables []string // Tables that interleave in this table
ForeignKeys []FKReference // Foreign key references FROM this table
ReferencedBy []FKReference // Foreign key references TO this table
Level int // INTERLEAVE depth (0-7)
}
TableDependency represents a table with all its dependencies
type TableHeader ¶
type TableHeader interface {
// Render returns the header strings. When verbose is true, type information is included.
// Use renderTableHeader() as a nil-safe wrapper.
Render(verbose bool) []string
// contains filtered or unexported methods
}
func NewTableHeader ¶ added in v0.33.0
func NewTableHeader(names ...string) TableHeader
NewTableHeader builds a simple string-column TableHeader. Exported wrapper over toTableHeader for feature packages.
type TablePreviewProcessor ¶
type TablePreviewProcessor struct {
// contains filtered or unexported fields
}
TablePreviewProcessor collects a configurable number of rows for table width calculation. This allows table formats to determine optimal column widths before starting output.
func NewTablePreviewProcessor ¶
func NewTablePreviewProcessor(formatter format.StreamingFormatter, previewSize int) *TablePreviewProcessor
NewTablePreviewProcessor creates a processor that previews rows for width calculation. previewSize of 0 means collect all rows (non-streaming mode).
func (*TablePreviewProcessor) Finish ¶
func (p *TablePreviewProcessor) Finish(stats QueryStats, rowCount int64) error
Finish ensures formatter is initialized and completes output.
func (*TablePreviewProcessor) Init ¶
func (p *TablePreviewProcessor) Init(metadata *sppb.ResultSetMetadata, sysVars *systemVariables) error
Init stores metadata for later use.
func (*TablePreviewProcessor) ProcessRow ¶
func (p *TablePreviewProcessor) ProcessRow(row Row) error
ProcessRow collects rows for preview or passes them through after initialization.
type TeeOutputMetaCommand ¶
type TeeOutputMetaCommand struct {
FilePath string
}
TeeOutputMetaCommand enables output tee to a file using \T syntax (MySQL-style: both screen and file)
type TemplateVar ¶
type TemplateVar struct {
// contains filtered or unexported fields
}
TemplateVar handles template variables like CLI_ANALYZE_COLUMNS
func (*TemplateVar) Get ¶
func (t *TemplateVar) Get() (string, error)
func (*TemplateVar) Set ¶
func (t *TemplateVar) Set(value string) error
type TimestampBoundVar ¶
type TimestampBoundVar struct {
// contains filtered or unexported fields
}
TimestampBoundVar handles READ_ONLY_STALENESS variable
func (*TimestampBoundVar) Get ¶
func (t *TimestampBoundVar) Get() (string, error)
func (*TimestampBoundVar) Set ¶
func (t *TimestampBoundVar) Set(value string) error
type TimestampVar ¶
type TimestampVar struct {
// contains filtered or unexported fields
}
TimestampVar handles timestamp formatting for read-only timestamp variables
func (*TimestampVar) Get ¶
func (t *TimestampVar) Get() (string, error)
func (*TimestampVar) Set ¶
func (t *TimestampVar) Set(value string) error
type TransactionManager ¶ added in v0.28.0
type TransactionManager struct {
// contains filtered or unexported fields
}
TransactionManager manages transaction lifecycle, query execution, and mutex-based concurrency for transaction state.
Mutex Protection Rationale:
While spanner-mycli is primarily a CLI tool with sequential user interactions, mutex protection is essential for several reasons:
1. **Goroutine safety**: Even in a CLI, operations may spawn goroutines:
- Background heartbeat for long-running transactions
- Progress bars and monitoring features
- Future parallel query execution features
- Signal handlers (Ctrl+C) that may access transaction state
2. **Correctness over performance**: The mutex ensures:
- Atomic check-and-act operations (e.g., checking transaction state before modifying)
- Prevention of use-after-free bugs if transaction is closed concurrently
- Consistent transaction state across all operations
3. **Future extensibility**: The mutex-based design allows for:
- Safe addition of concurrent features without major refactoring
- Integration with tools that may access session state concurrently
- Support for multiplexed connections or parallel operations
4. **Best practices**: Following Go's concurrency principles:
- "Don't communicate by sharing memory; share memory by communicating"
- When sharing is necessary (as with session state), protect it properly
- Make the zero value useful - mutex provides safe default behavior
The performance overhead of mutex operations is negligible for CLI usage patterns, while the safety guarantees prevent subtle bugs that could corrupt user data.
func NewTransactionManager ¶ added in v0.28.0
func NewTransactionManager(client *spanner.Client, sysVars *systemVariables, clientConfig spanner.ClientConfig) *TransactionManager
NewTransactionManager creates a new TransactionManager.
func (*TransactionManager) BeginPendingTransaction ¶ added in v0.28.0
func (tm *TransactionManager) BeginPendingTransaction(ctx context.Context, isolationLevel sppb.TransactionOptions_IsolationLevel, priority sppb.RequestOptions_Priority) error
BeginPendingTransaction starts pending transaction. The actual start of the transaction is delayed until the first operation in the transaction is executed.
func (*TransactionManager) BeginReadOnlyTransaction ¶ added in v0.28.0
func (tm *TransactionManager) BeginReadOnlyTransaction(ctx context.Context, typ timestampBoundType, staleness time.Duration, timestamp time.Time, priority sppb.RequestOptions_Priority) (time.Time, error)
BeginReadOnlyTransaction starts read-only transaction and returns the snapshot timestamp for the transaction if successful.
func (*TransactionManager) BeginReadOnlyTransactionLocked ¶ added in v0.28.0
func (tm *TransactionManager) BeginReadOnlyTransactionLocked(ctx context.Context, typ timestampBoundType, staleness time.Duration, timestamp time.Time, priority sppb.RequestOptions_Priority) (time.Time, error)
BeginReadOnlyTransactionLocked starts read-only transaction and returns the snapshot timestamp for the transaction if successful. Caller must hold tm.mu.
func (*TransactionManager) BeginReadWriteTransaction ¶ added in v0.28.0
func (tm *TransactionManager) BeginReadWriteTransaction(ctx context.Context, isolationLevel sppb.TransactionOptions_IsolationLevel, priority sppb.RequestOptions_Priority) error
BeginReadWriteTransaction starts read-write transaction.
func (*TransactionManager) BeginReadWriteTransactionLocked ¶ added in v0.28.0
func (tm *TransactionManager) BeginReadWriteTransactionLocked(ctx context.Context, isolationLevel sppb.TransactionOptions_IsolationLevel, priority sppb.RequestOptions_Priority) error
BeginReadWriteTransactionLocked starts read-write transaction. Caller must hold tm.mu.
func (*TransactionManager) ClosePendingTransaction ¶ added in v0.28.0
func (tm *TransactionManager) ClosePendingTransaction() error
ClosePendingTransaction closes a pending transaction.
func (*TransactionManager) CloseReadOnlyTransaction ¶ added in v0.28.0
func (tm *TransactionManager) CloseReadOnlyTransaction() error
CloseReadOnlyTransaction closes a running read-only transaction.
func (*TransactionManager) CommitReadWriteTransaction ¶ added in v0.28.0
func (tm *TransactionManager) CommitReadWriteTransaction(ctx context.Context) (spanner.CommitResponse, error)
CommitReadWriteTransaction commits read-write transaction and returns commit timestamp if successful.
func (*TransactionManager) CommitReadWriteTransactionLocked ¶ added in v0.28.0
func (tm *TransactionManager) CommitReadWriteTransactionLocked(ctx context.Context) (spanner.CommitResponse, error)
CommitReadWriteTransactionLocked commits read-write transaction and returns commit timestamp if successful. Caller must hold tm.mu.
func (*TransactionManager) DetermineTransaction ¶ added in v0.28.0
DetermineTransaction determines the type of transaction to start based on the pending transaction and system variables. It returns the timestamp for read-only transactions or a zero time for read-write transactions.
func (*TransactionManager) DetermineTransactionAndState ¶ added in v0.28.0
func (tm *TransactionManager) DetermineTransactionAndState(ctx context.Context) (time.Time, bool, error)
DetermineTransactionAndState determines transaction and returns both the timestamp and current transaction state. This combines DetermineTransaction and InTransaction checks in a single lock acquisition.
func (*TransactionManager) DetermineTransactionLocked ¶ added in v0.28.0
DetermineTransactionLocked determines the type of transaction to start based on the pending transaction and system variables. It returns the timestamp for read-only transactions or a zero time for read-write transactions. Caller must hold tm.mu.
func (*TransactionManager) GetTransactionFlagsWithLock ¶ added in v0.28.0
func (tm *TransactionManager) GetTransactionFlagsWithLock() (inTransaction bool, inReadWriteTransaction bool)
GetTransactionFlagsWithLock returns multiple transaction state flags in a single lock acquisition. This is useful for avoiding multiple lock acquisitions when checking different transaction states. Acquires RLock for concurrent read access.
func (*TransactionManager) InPendingTransaction ¶ added in v0.28.0
func (tm *TransactionManager) InPendingTransaction() bool
InPendingTransaction returns true if the session is running pending transaction.
func (*TransactionManager) InReadOnlyTransaction ¶ added in v0.28.0
func (tm *TransactionManager) InReadOnlyTransaction() bool
InReadOnlyTransaction returns true if the session is running read-only transaction.
func (*TransactionManager) InReadWriteTransaction ¶ added in v0.28.0
func (tm *TransactionManager) InReadWriteTransaction() bool
InReadWriteTransaction returns true if the session is running read-write transaction.
func (*TransactionManager) InTransaction ¶ added in v0.28.0
func (tm *TransactionManager) InTransaction() bool
InTransaction returns true if the session is running transaction.
func (*TransactionManager) NewTransactionOptionsBuilder ¶ added in v0.28.0
func (tm *TransactionManager) NewTransactionOptionsBuilder() *TransactionOptionsBuilder
NewTransactionOptionsBuilder creates a new builder with session defaults.
func (*TransactionManager) RollbackReadWriteTransaction ¶ added in v0.28.0
func (tm *TransactionManager) RollbackReadWriteTransaction(ctx context.Context) error
RollbackReadWriteTransaction rollbacks read-write transaction.
func (*TransactionManager) RollbackReadWriteTransactionLocked ¶ added in v0.28.0
func (tm *TransactionManager) RollbackReadWriteTransactionLocked(ctx context.Context) error
RollbackReadWriteTransactionLocked rollbacks read-write transaction. Caller must hold tm.mu.
func (*TransactionManager) RunAnalyzeQuery ¶ added in v0.28.0
func (tm *TransactionManager) RunAnalyzeQuery(ctx context.Context, stmt spanner.Statement) (*sppb.QueryPlan, *sppb.ResultSetMetadata, error)
RunAnalyzeQuery analyzes a statement either on the running transaction or on the temporal read-only transaction.
func (*TransactionManager) RunInNewOrExistRwTx ¶ added in v0.28.0
func (tm *TransactionManager) RunInNewOrExistRwTx(ctx context.Context, f func(tx *spanner.ReadWriteStmtBasedTransaction, implicit bool) (affected int64, plan *sppb.QueryPlan, metadata *sppb.ResultSetMetadata, err error), ) (*DMLResult, error)
RunInNewOrExistRwTx is a helper function for DML execution. It executes a function in the current RW transaction or an implicit RW transaction. If there is an error, the transaction will be rolled back.
func (*TransactionManager) RunInNewOrExistRwTxLocked ¶ added in v0.28.0
func (tm *TransactionManager) RunInNewOrExistRwTxLocked(ctx context.Context, f func(tx *spanner.ReadWriteStmtBasedTransaction, implicit bool) (affected int64, plan *sppb.QueryPlan, metadata *sppb.ResultSetMetadata, err error), ) (*DMLResult, error)
RunInNewOrExistRwTxLocked is a helper function for DML execution. It executes a function in the current RW transaction or an implicit RW transaction. If there is an error, the transaction will be rolled back. Caller must hold tm.mu.
func (*TransactionManager) RunPartitionQuery ¶ added in v0.28.0
func (tm *TransactionManager) RunPartitionQuery(ctx context.Context, stmt spanner.Statement) ([]*spanner.Partition, *spanner.BatchReadOnlyTransaction, error)
RunPartitionQuery runs a partition query.
func (*TransactionManager) RunQuery ¶ added in v0.28.0
func (tm *TransactionManager) RunQuery(ctx context.Context, stmt spanner.Statement) (*spanner.RowIterator, *spanner.ReadOnlyTransaction, error)
RunQuery executes a statement either on the running transaction or on the temporal read-only transaction. It returns row iterator and read-only transaction if the statement was executed on the read-only transaction. An error is returned when no database connection is available; this should not happen if DetachedCompatible interface validation is working correctly.
func (*TransactionManager) RunQueryWithStats ¶ added in v0.28.0
func (tm *TransactionManager) RunQueryWithStats(ctx context.Context, stmt spanner.Statement, implicit bool, mode sppb.ExecuteSqlRequest_QueryMode) (*spanner.RowIterator, *spanner.ReadOnlyTransaction, error)
RunQueryWithStats executes a statement with stats either on the running transaction or on the temporal read-only transaction. It returns row iterator and read-only transaction if the statement was executed on the read-only transaction. The mode must be a QueryMode that returns execution statistics: PROFILE, WITH_STATS, or WITH_PLAN_AND_STATS. Callers that need the query plan (e.g. EXPLAIN ANALYZE) must pass PROFILE; regular execution should pass effectiveQueryMode() so a user-specified CLI_QUERY_MODE is respected. An error is returned when no database connection is available; this should not happen if DetachedCompatible interface validation is working correctly.
func (*TransactionManager) SetClient ¶ added in v0.33.0
func (tm *TransactionManager) SetClient(client *spanner.Client) error
SetClient replaces the Spanner client under tm.mu. It refuses to replace the client while any transaction context exists: the old client is closed by the caller, so a live tc (and its heartbeat goroutine) would be left using a closed client. All Aborted paths that trigger RecreateClient roll back or clear the transaction first; this guard turns that ordering from an emergent property into an enforced invariant.
func (*TransactionManager) TransactionAttrsWithLock ¶ added in v0.28.0
func (tm *TransactionManager) TransactionAttrsWithLock() transactionAttributes
TransactionAttrsWithLock returns a copy of all transaction attributes. This allows safe inspection of transaction state without holding the mutex. If no transaction is active, returns a zero-value struct with mode=transactionModeUndetermined.
Design decision: This method uses RLock for read-only access, allowing concurrent reads of transaction state.
Naming convention: - TransactionAttrsWithLock() - Acquires read lock internally (this method) - transactionAttrsLocked() - Assumes caller holds lock (read or write)
func (*TransactionManager) TransactionMode ¶ added in v0.28.0
func (tm *TransactionManager) TransactionMode() transactionMode
TransactionMode returns the current transaction mode. Deprecated: Use TransactionState() for new code.
func (*TransactionManager) TransactionState ¶ added in v0.28.0
func (tm *TransactionManager) TransactionState() (mode transactionMode, isActive bool)
TransactionState returns the current transaction mode and whether a transaction is active. This consolidates multiple transaction state checks into a single method.
func (*TransactionManager) TransitTransaction ¶ added in v0.28.0
func (tm *TransactionManager) TransitTransaction(ctx context.Context, fn func(tc *transactionContext) (*transactionContext, error)) error
TransitTransaction implements a functional state transition pattern for transaction management. It atomically transitions from one transaction state to another, handling cleanup of the old state. The transition function receives the current context and returns the new context. If an error occurs during transition, the original state is preserved.
func (*TransactionManager) ValidateDatabaseOperation ¶ added in v0.28.0
func (tm *TransactionManager) ValidateDatabaseOperation() error
ValidateDatabaseOperation checks whether the TransactionManager has a valid client.
type TransactionOptionsBuilder ¶
type TransactionOptionsBuilder struct {
// contains filtered or unexported fields
}
TransactionOptionsBuilder helps build transaction options with proper defaults.
func (*TransactionOptionsBuilder) Build ¶
func (b *TransactionOptionsBuilder) Build() spanner.TransactionOptions
Build creates the final TransactionOptions with resolved defaults.
func (*TransactionOptionsBuilder) BuildIsolationLevel ¶
func (b *TransactionOptionsBuilder) BuildIsolationLevel() sppb.TransactionOptions_IsolationLevel
BuildIsolationLevel returns just the resolved isolation level.
func (*TransactionOptionsBuilder) BuildPriority ¶
func (b *TransactionOptionsBuilder) BuildPriority() sppb.RequestOptions_Priority
BuildPriority returns just the resolved priority.
func (*TransactionOptionsBuilder) WithIsolationLevel ¶
func (b *TransactionOptionsBuilder) WithIsolationLevel(level sppb.TransactionOptions_IsolationLevel) *TransactionOptionsBuilder
WithIsolationLevel sets the transaction isolation level.
func (*TransactionOptionsBuilder) WithPriority ¶
func (b *TransactionOptionsBuilder) WithPriority(priority sppb.RequestOptions_Priority) *TransactionOptionsBuilder
WithPriority sets the transaction priority.
func (*TransactionOptionsBuilder) WithTag ¶
func (b *TransactionOptionsBuilder) WithTag(tag string) *TransactionOptionsBuilder
WithTag sets the transaction tag.
type TransactionVars ¶ added in v0.28.0
type TransactionVars struct {
TransactionTag string // TRANSACTION_TAG
RequestTag string // STATEMENT_TAG
ReadOnly bool // READONLY
ExcludeTxnFromChangeStreams bool // EXCLUDE_TXN_FROM_CHANGE_STREAMS
MaxCommitDelay *time.Duration // MAX_COMMIT_DELAY
AutoBatchDML bool // AUTO_BATCH_DML
AutocommitDMLMode enums.AutocommitDMLMode // AUTOCOMMIT_DML_MODE
ReturnCommitStats bool // RETURN_COMMIT_STATS
DefaultIsolationLevel sppb.TransactionOptions_IsolationLevel // DEFAULT_ISOLATION_LEVEL
ReadLockMode sppb.TransactionOptions_ReadWrite_ReadLockMode // READ_LOCK_MODE
// Unimplemented variables (kept for compatibility)
Autocommit bool // AUTOCOMMIT (unimplemented)
RetryAbortsInternally bool // RETRY_ABORTS_INTERNALLY (unimplemented)
}
TransactionVars holds transaction-related configuration.
type TruncateTableStatement ¶
type TryPartitionedQueryStatement ¶
type TryPartitionedQueryStatement struct{ SQL string }
type TypedRows ¶ added in v0.33.0
type TypedRows struct {
// Metadata is the authoritative column names + types for the result set.
Metadata *sppb.ResultSetMetadata
// Rows are the raw decoded rows; they remain valid after RowIterator.Stop
// because each row owns its decoded values.
Rows []*spanner.Row
// SQLExportAllowed preserves today's rule that only real query results are
// exported as INSERTs; other typed producers fall back to TABLE under
// SQL_INSERT* (successor of the buffered-query use of SQLExportAllowed).
SQLExportAllowed bool
}
TypedRows preserves the raw result-set (metadata + typed rows) for a buffered Result so export formats re-render from values, not display text. It is the (c) "typed buffered" body payload described in issue #738: at most one of Result.Rows, Result.Typed, Result.RenderedOutput is set, and Result.Streamed means the body was already emitted during execution.
type UnimplementedVar ¶
type UnimplementedVar struct {
// contains filtered or unexported fields
}
UnimplementedVar handles unimplemented variables
func (*UnimplementedVar) Get ¶
func (u *UnimplementedVar) Get() (string, error)
func (*UnimplementedVar) Set ¶
func (u *UnimplementedVar) Set(value string) error
type UnsetParamStatement ¶
type UnsetParamStatement struct {
Name string
}
type UpdateResult ¶
type UpdateResult struct {
// Rows holds the raw typed rows returned by the operation (e.g., THEN
// RETURN); display formatting is deferred to display time (issue #738 PR2).
Rows []*spanner.Row
Stats map[string]any // Query statistics from the operation
Count int64 // Number of rows affected by the update
Metadata *sppb.ResultSetMetadata // Metadata about the result set
Plan *sppb.QueryPlan // Query execution plan (when requested)
}
UpdateResult holds the complete result of an update operation.
type UseDatabaseMetaCommand ¶
type UseDatabaseMetaCommand struct {
Database string
}
UseDatabaseMetaCommand switches database using \u syntax
type UseStatement ¶
type UseStatement struct {
Database string
Role string
NopStatement
}
UseStatement is actually implemented in cli.go because it needs to replace Session pointer in Cli.
type ValidValuesEnumerator ¶
type ValidValuesEnumerator interface {
ValidValues() []string
}
ValidValuesEnumerator is implemented by variables that have a constrained set of valid values. Used by fuzzy completion to offer value candidates for SET <name> = <Ctrl+T>. Values must be returned as valid GoogleSQL literals (e.g., 'TABLE' for strings, TRUE for booleans).
type VarHandler ¶
type VarHandler[T any] struct { // contains filtered or unexported fields }
VarHandler handles get/set operations for a variable.
Read-only enforcement no longer lives here: the varDef's scope/readOnly metadata drives it in VarRegistry.Set, so a handler only needs to know how to format, parse, and validate its value.
func BoolVar ¶
func BoolVar(ptr *bool) *VarHandler[bool]
BoolVar creates a handler for bool variables
func IntVar ¶
func IntVar(ptr *int64) *VarHandler[int64]
IntVar creates a handler for int64 variables
func NullableDurationVar ¶
func NullableDurationVar(ptr **time.Duration) *VarHandler[*time.Duration]
NullableDurationVar creates a handler for nullable duration variables
func NullableIntVar ¶
func NullableIntVar(ptr **int64) *VarHandler[*int64]
NullableIntVar creates a handler for nullable int64 variables
func StringVar ¶
func StringVar(ptr *string) *VarHandler[string]
StringVar creates a handler for string variables
func (*VarHandler[T]) Get ¶
func (h *VarHandler[T]) Get() (string, error)
Get returns the formatted value
func (*VarHandler[T]) Set ¶
func (h *VarHandler[T]) Set(value string) error
Set parses and sets the value
func (*VarHandler[T]) ValidValues ¶
func (h *VarHandler[T]) ValidValues() []string
ValidValues returns the constrained valid values, if any. Implements ValidValuesEnumerator for VarHandler instances with enumValues set.
func (*VarHandler[T]) WithValidator ¶
func (h *VarHandler[T]) WithValidator(validate func(T) error) *VarHandler[T]
WithValidator adds a validator function
type VarRegistry ¶
type VarRegistry struct {
// contains filtered or unexported fields
}
VarRegistry is a registry for system variables
func NewVarRegistry ¶
func NewVarRegistry(sv *systemVariables) *VarRegistry
NewVarRegistry creates a new variable registry
func (*VarRegistry) Add ¶
func (r *VarRegistry) Add(name, value string) error
Add performs ADD operation on a variable
func (*VarRegistry) Get ¶
func (r *VarRegistry) Get(name string) (string, error)
Get retrieves a variable value
func (*VarRegistry) GetDescription ¶
func (r *VarRegistry) GetDescription(name string) (string, error)
GetDescription returns variable description
func (*VarRegistry) GetVariable ¶
func (r *VarRegistry) GetVariable(name string) Variable
GetVariable retrieves the Variable handler by name, or nil if not found.
func (*VarRegistry) IsReadOnly ¶
func (r *VarRegistry) IsReadOnly(name string) (bool, error)
IsReadOnly checks if a variable is read-only
func (*VarRegistry) ListMultiValues ¶ added in v0.33.0
func (r *VarRegistry) ListMultiValues() map[string]string
ListMultiValues returns the merged GetMulti() output of every registered MultiValueVar whose value is currently available. Keys may intentionally collide with single-valued variables (COMMIT_RESPONSE's COMMIT_TIMESTAMP overrides the plain COMMIT_TIMESTAMP row in SHOW VARIABLES).
func (*VarRegistry) ListVariableInfo ¶
func (r *VarRegistry) ListVariableInfo() map[string]struct { Description string ReadOnly bool CanAdd bool Unimplemented bool }
ListVariableInfo returns information about all variables
func (*VarRegistry) ListVariables ¶
func (r *VarRegistry) ListVariables() map[string]string
ListVariables returns a map of all variables with their current values. It iterates defs by canonical name so aliases are excluded, and skips variables whose Get reports the value as unavailable (e.g. multi-valued COMMIT_RESPONSE, whose columns are merged in separately via ListMultiValues).
Source Files
¶
- app.go
- batch_manager.go
- cli.go
- cli_mcp.go
- cli_output.go
- cli_readline.go
- client_side_statement_def.go
- config.go
- dependency_resolver.go
- emulator.go
- errors.go
- execute_ddl.go
- execute_dml.go
- execute_partitioned.go
- execute_sql.go
- explain_print_sections.go
- feature.go
- formatter_utils.go
- fuzzy_finder.go
- kong_toml_loader.go
- lint_plan.go
- memefish_parser.go
- meta_commands.go
- output_context.go
- result_sink.go
- row_iter.go
- row_iterator_transform.go
- row_processor.go
- sample_databases.go
- separator.go
- session.go
- session_transaction_context.go
- spancodec_bridge.go
- spanvalue_streaming.go
- sql_export_table_name.go
- statement_processing.go
- statements.go
- statements_dump.go
- statements_explain_describe.go
- statements_mutations.go
- statements_params.go
- statements_partitioned_query.go
- statements_proto.go
- statements_query_profile.go
- statements_schema.go
- statements_split_points.go
- statements_system_variable.go
- statements_transaction.go
- streaming.go
- system_variables.go
- system_variables_registry.go
- transaction_manager.go
- type_styles.go
- typed_rows.go
- var_custom_handlers.go
- var_defs.go
- var_enum_handlers.go
- var_errors.go
- var_handler.go
- var_registry.go
- zap_logger.go
Directories
¶
| Path | Synopsis |
|---|---|
|
feature
|
|
|
all
Package all assembles the full set of optional features (issue #778) for the full spanner-mycli binary.
|
Package all assembles the full set of optional features (issue #778) for the full spanner-mycli binary. |
|
bigquery
Package bigquery contributes the BIGQUERY statement family to spanner-mycli through the Feature registration seam (issue #778).
|
Package bigquery contributes the BIGQUERY statement family to spanner-mycli through the Feature registration seam (issue #778). |
|
cql
Package cql contributes the CQL (Cassandra interface) statement family to spanner-mycli through the Feature registration seam (issue #778).
|
Package cql contributes the CQL (Cassandra interface) statement family to spanner-mycli through the Feature registration seam (issue #778). |
|
llm
Package llm contributes the GEMINI statement family (LLM-assisted query composition) to spanner-mycli through the Feature registration seam (issue #778).
|
Package llm contributes the GEMINI statement family (LLM-assisted query composition) to spanner-mycli through the Feature registration seam (issue #778). |
|
StreamManager manages all I/O streams for the CLI.
|
StreamManager manages all I/O streams for the CLI. |