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 AutocommitVar(sv *systemVariables) *autocommitVar
- 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
- 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 DDLExecutionModeVar(ptr *enums.DDLExecutionMode) *EnumVar[enums.DDLExecutionMode]
- func DdlInTransactionModeVar(ptr *enums.DdlInTransactionMode) *EnumVar[enums.DdlInTransactionMode]
- func DisplayModeVar(ptr *enums.DisplayMode) *EnumVar[enums.DisplayMode]
- func DumpCyclicModeVar(ptr *enums.DumpCyclicMode) *EnumVar[enums.DumpCyclicMode]
- func ExplainFormatVar(ptr *enums.ExplainFormat) *EnumVar[enums.ExplainFormat]
- func ParseModeVar(ptr *enums.ParseMode) *EnumVar[enums.ParseMode]
- func SavepointSupportVar(ptr *enums.SavepointSupport) *EnumVar[enums.SavepointSupport]
- func StreamingModeVar(ptr *enums.StreamingMode) *EnumVar[enums.StreamingMode]
- func StringQuoteModeVar(ptr *enums.StringQuoteMode) *EnumVar[enums.StringQuoteMode]
- 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 ExportDataStatement
- 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 OperationOutput
- type OutputContext
- type OutputRedirectMetaCommand
- type PartitionStatement
- type PartitionedDmlStatement
- type PromptMetaCommand
- type ProtoDescriptorVar
- type ProtoDescriptorsVar
- 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 PullRemoteProtoStatement
- type QueryIndexAdvice
- type QueryResult
- type QueryStats
- type QueryVars
- type ReadOnlyVar
- type ReleaseSavepointStatement
- type ResetAllStatement
- type ResetStatement
- type Result
- type ResultAppendix
- type ResultBody
- type RollbackStatement
- type RollbackToSavepointStatement
- type Row
- type RowProcessor
- type RunBatchStatement
- type RunPartitionStatement
- type RunPartitionedQueryStatement
- type SampleDatabase
- type SavepointStatement
- 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, error)
- func (s *Session) ExecuteStatementWithOutput(ctx context.Context, stmt Statement, out OperationOutput) (*Result, error)
- func (s *Session) GetDatabaseDdlCached(ctx context.Context) (*adminpb.GetDatabaseDdlResponse, error)
- func (s *Session) GetDatabaseDdlFresh(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 OperationOutput) (*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 ShowLastQueryPlanStatement
- type ShowLocalProtoStatement
- type ShowOperationStatement
- type ShowParamsStatement
- type ShowPlanNodeStatement
- type ShowQueryProfileStatement
- type ShowQueryProfilesStatement
- type ShowRemoteProtoStatement
- type ShowSchemaUpdateOperations
- type ShowSplitPointsStatement
- type ShowTablesStatement
- type ShowTransactionStatement
- 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) AutomaticBatchInfo() *BatchInfo
- 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) CreateSavepoint(ctx context.Context, name string) 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) DiscardAutomaticDML()
- func (tm *TransactionManager) FlushAutomaticDML(ctx context.Context) (*Result, error)
- func (tm *TransactionManager) GetTransactionFlagsWithLock() (inTransaction bool, inReadWriteTransaction bool)
- func (tm *TransactionManager) HandleOwnerFailure(ctx context.Context, tok *captureToken, err error) error
- func (tm *TransactionManager) HasAutomaticDML() bool
- func (tm *TransactionManager) HasUserWork() bool
- func (tm *TransactionManager) InPendingTransaction() bool
- func (tm *TransactionManager) InReadOnlyTransaction() bool
- func (tm *TransactionManager) InReadWriteTransaction() bool
- func (tm *TransactionManager) InTransaction() bool
- func (tm *TransactionManager) NeedsRecovery() bool
- func (tm *TransactionManager) ReleaseSavepoint(name string) error
- func (tm *TransactionManager) RollbackReadWriteTransaction(ctx context.Context) error
- func (tm *TransactionManager) RollbackReadWriteTransactionLocked(ctx context.Context) error
- func (tm *TransactionManager) RollbackToSavepoint(ctx context.Context, name string) 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) RunSingleUseQueryWithStats(ctx context.Context, stmt spanner.Statement, ...) (*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) TryEnqueueAutomaticDML(stmt spanner.Statement) (bool, error)
- func (tm *TransactionManager) ValidateDatabaseOperation() error
- type TransactionVars
- type TruncateTableStatement
- type TryPartitionedQueryStatement
- type TypedRows
- type UnimplementedVar
- type UnsetParamStatement
- type UpdateResult
- type UseDatabaseMetaCommand
- type UseStatement
- type ValidValuesEnumerator
- type VarHandler
- func BoolVar(ptr *bool) *VarHandler[bool]
- func DefaultSequenceKindVar(ptr *string) *VarHandler[string]
- func DurationVar(ptr *time.Duration) *VarHandler[time.Duration]
- func Float64Var(ptr *float64) *VarHandler[float64]
- func IntVar(ptr *int64) *VarHandler[int64]
- func NullableDurationVar(ptr **time.Duration) *VarHandler[*time.Duration]
- func NullableIntVar(ptr **int64) *VarHandler[*int64]
- func StringVar(ptr *string) *VarHandler[string]
- 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) Reset(name string) error
- func (r *VarRegistry) ResetAll() error
- 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 AutocommitVar ¶ added in v0.35.0
func AutocommitVar(sv *systemVariables) *autocommitVar
AutocommitVar binds AUTOCOMMIT to sv.Transaction.Autocommit.
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{}
func (*AbortBatchStatement) Execute ¶
func (s *AbortBatchStatement) Execute(ctx context.Context, session *Session, out OperationOutput) (*Result, error)
type AddSplitPointsStatement ¶
type AddSplitPointsStatement struct {
SplitPoints []*databasepb.SplitPoints
}
func (*AddSplitPointsStatement) Execute ¶
func (s *AddSplitPointsStatement) Execute(ctx context.Context, session *Session, out OperationOutput) (*Result, error)
type BatchDMLStatement ¶
func (*BatchDMLStatement) Execute ¶
func (s *BatchDMLStatement) Execute(ctx context.Context, session *Session, out OperationOutput) (*Result, error)
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. Automatic DML is stored on transactionContext; this remains for tests and any caller that must install a manual batch without Start.
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 BeginRoStatement struct {
TimestampBoundType timestampBoundType
Staleness time.Duration
Timestamp time.Time
Priority sppb.RequestOptions_Priority
}
func (*BeginRoStatement) Execute ¶
func (s *BeginRoStatement) Execute(ctx context.Context, session *Session, out OperationOutput) (*Result, error)
type BeginRwStatement ¶
type BeginRwStatement struct {
IsolationLevel sppb.TransactionOptions_IsolationLevel
Priority sppb.RequestOptions_Priority
}
func (*BeginRwStatement) Execute ¶
func (s *BeginRwStatement) Execute(ctx context.Context, session *Session, out OperationOutput) (*Result, error)
type BeginStatement ¶
type BeginStatement struct {
IsolationLevel sppb.TransactionOptions_IsolationLevel
Priority sppb.RequestOptions_Priority
}
func (*BeginStatement) Execute ¶
func (s *BeginStatement) Execute(ctx context.Context, session *Session, out OperationOutput) (*Result, error)
type BulkDdlStatement ¶
type BulkDdlStatement struct {
Ddls []string
}
func (*BulkDdlStatement) Execute ¶
func (s *BulkDdlStatement) Execute(ctx context.Context, session *Session, out OperationOutput) (*Result, error)
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{}
func (*CommitStatement) Execute ¶
func (s *CommitStatement) Execute(ctx context.Context, session *Session, out OperationOutput) (*Result, error)
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 published on successful USE/DETACH (SessionHandler.adoptSession). These live fields are the values shown by the registry. Each Session stores a copy captured at construction and uses that copy for client and administrative resource paths.
func (ConnectionVars) DatabasePath ¶ added in v0.35.0
func (c ConnectionVars) DatabasePath() string
func (ConnectionVars) InstancePath ¶ added in v0.35.0
func (c ConnectionVars) InstancePath() string
func (ConnectionVars) ProjectPath ¶ added in v0.35.0
func (c ConnectionVars) ProjectPath() string
type CreateDatabaseStatement ¶
type CreateDatabaseStatement struct {
CreateStatement string
}
CreateDatabaseStatement is intentionally left on the MutationStatement path and outside CLI_DDL_IN_TRANSACTION_MODE (#402). UpdateDatabaseDdl admission applies to DdlStatement, BulkDdlStatement, and SYNC PROTO BUNDLE only.
func (*CreateDatabaseStatement) Execute ¶
func (s *CreateDatabaseStatement) Execute(ctx context.Context, session *Session, out OperationOutput) (*Result, error)
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
func (*CustomVar) PrepareReset ¶ added in v0.35.0
PrepareReset validates without running a mutating customSetter.
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) Execute ¶
func (s *DdlStatement) Execute(ctx context.Context, session *Session, out OperationOutput) (*Result, error)
func (*DdlStatement) String ¶
func (s *DdlStatement) String() string
type DependencyResolver ¶
type DependencyResolver struct {
// contains filtered or unexported fields
}
DependencyResolver orders dump tables by interleave and FK edges.
func NewDependencyResolver ¶
func NewDependencyResolver() *DependencyResolver
func (*DependencyResolver) BuildDependencyGraphWithTxn ¶
func (dr *DependencyResolver) BuildDependencyGraphWithTxn(ctx context.Context, txn *spanner.ReadOnlyTransaction, dro *sppb.DirectedReadOptions) error
func (*DependencyResolver) GetOrderForTables ¶
func (dr *DependencyResolver) GetOrderForTables(tablesToExport []tableID) ([]tableID, error)
func (*DependencyResolver) GetTableOrder ¶
func (dr *DependencyResolver) GetTableOrder() ([]tableID, error)
type DescribeStatement ¶
type DescribeStatement struct {
Statement string
IsDML bool // Whether the statement being described is a DML
}
func (*DescribeStatement) Execute ¶
func (s *DescribeStatement) Execute(ctx context.Context, session *Session, out OperationOutput) (*Result, error)
Execute processes `DESCRIBE` statement for queries and DMLs.
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
func (*DisableOutputRedirectMetaCommand) Execute ¶
func (d *DisableOutputRedirectMetaCommand) Execute(ctx context.Context, session *Session, out OperationOutput) (*Result, error)
Execute disables output redirect (returns to stdout)
type DisableTeeMetaCommand ¶
type DisableTeeMetaCommand struct{}
DisableTeeMetaCommand disables output tee using \t syntax
func (*DisableTeeMetaCommand) Execute ¶
func (d *DisableTeeMetaCommand) Execute(ctx context.Context, session *Session, out OperationOutput) (*Result, error)
Execute disables tee output
type DisplayVars ¶ added in v0.28.0
type DisplayVars struct {
DumpCyclicMode enums.DumpCyclicMode // CLI_DUMP_CYCLIC_MODE
DumpCyclicMaxBytes int64 // CLI_DUMP_CYCLIC_MAX_BYTES
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
StringQuoteMode enums.StringQuoteMode // CLI_STRING_QUOTE_MODE
SuppressResultLines bool // CLI_SUPPRESS_RESULT_LINES
ExplainFormat enums.ExplainFormat // CLI_EXPLAIN_FORMAT
ExplainWrapWidth int64 // CLI_EXPLAIN_WRAP_WIDTH
ExplainOperatorHeader string // CLI_EXPLAIN_OPERATOR_HEADER
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) Execute ¶
func (s *DmlStatement) Execute(ctx context.Context, session *Session, out OperationOutput) (*Result, error)
func (*DmlStatement) String ¶
func (s *DmlStatement) String() string
type DropDatabaseStatement ¶
type DropDatabaseStatement struct {
DatabaseId string
}
func (*DropDatabaseStatement) Execute ¶
func (s *DropDatabaseStatement) Execute(ctx context.Context, session *Session, out OperationOutput) (*Result, error)
type DumpDatabaseStatement ¶
type DumpDatabaseStatement struct{}
DumpDatabaseStatement represents DUMP DATABASE statement It exports both DDL and data for all tables in the database
func (*DumpDatabaseStatement) Execute ¶
func (s *DumpDatabaseStatement) Execute(ctx context.Context, session *Session, out OperationOutput) (*Result, error)
type DumpSchemaStatement ¶
type DumpSchemaStatement struct{}
DumpSchemaStatement represents DUMP SCHEMA statement It exports only DDL statements without any data
func (*DumpSchemaStatement) Execute ¶
func (s *DumpSchemaStatement) Execute(ctx context.Context, session *Session, out OperationOutput) (*Result, error)
type DumpTablesStatement ¶
type DumpTablesStatement struct {
Tables []tableID
Selector *dumpTableSelector
}
DumpTablesStatement represents DUMP TABLES statement It exports data only for specified tables (no DDL)
func (*DumpTablesStatement) Execute ¶
func (s *DumpTablesStatement) Execute(ctx context.Context, session *Session, out OperationOutput) (*Result, error)
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 DDLExecutionModeVar ¶ added in v0.35.0
func DDLExecutionModeVar(ptr *enums.DDLExecutionMode) *EnumVar[enums.DDLExecutionMode]
func DdlInTransactionModeVar ¶ added in v0.35.0
func DdlInTransactionModeVar(ptr *enums.DdlInTransactionMode) *EnumVar[enums.DdlInTransactionMode]
func DisplayModeVar ¶
func DisplayModeVar(ptr *enums.DisplayMode) *EnumVar[enums.DisplayMode]
DisplayModeVar creates an enum handler for DisplayMode
func DumpCyclicModeVar ¶ added in v0.35.0
func DumpCyclicModeVar(ptr *enums.DumpCyclicMode) *EnumVar[enums.DumpCyclicMode]
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 SavepointSupportVar ¶ added in v0.35.0
func SavepointSupportVar(ptr *enums.SavepointSupport) *EnumVar[enums.SavepointSupport]
func StreamingModeVar ¶
func StreamingModeVar(ptr *enums.StreamingMode) *EnumVar[enums.StreamingMode]
StreamingModeVar creates an enum handler for StreamingMode
func StringQuoteModeVar ¶ added in v0.35.0
func StringQuoteModeVar(ptr *enums.StringQuoteMode) *EnumVar[enums.StringQuoteMode]
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]) PrepareReset ¶ added in v0.35.0
PrepareReset validates the enum without assigning to the live pointer.
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
}
func (*ExplainAnalyzeDmlStatement) Execute ¶
func (s *ExplainAnalyzeDmlStatement) Execute(ctx context.Context, session *Session, out OperationOutput) (*Result, error)
type ExplainAnalyzeStatement ¶
type ExplainAnalyzeStatement struct {
Query string
Format enums.ExplainFormat
Width int64
PrintSections *planref.PrintSections
}
func (*ExplainAnalyzeStatement) Execute ¶
func (s *ExplainAnalyzeStatement) Execute(ctx context.Context, session *Session, out OperationOutput) (*Result, error)
type ExplainLastQueryStatement ¶
type ExplainLastQueryStatement struct {
Analyze bool
Format enums.ExplainFormat
Width int64
PrintSections *planref.PrintSections
}
func (*ExplainLastQueryStatement) Execute ¶
func (s *ExplainLastQueryStatement) Execute(ctx context.Context, session *Session, out OperationOutput) (*Result, error)
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) Execute ¶
func (s *ExplainStatement) Execute(ctx context.Context, session *Session, out OperationOutput) (*Result, error)
Execute processes `EXPLAIN` statement for queries and DMLs.
func (*ExplainStatement) String ¶
func (s *ExplainStatement) String() string
type ExportDataStatement ¶ added in v0.34.0
type ExportDataStatement struct {
SQL string
}
ExportDataStatement runs a Spanner Graph algorithm query and persists its results according to the EXPORT DATA options. The persistence operation is non-transactional, so execution deliberately uses a single-use transaction instead of joining the session's current transaction.
https://cloud.google.com/spanner/docs/graph/run-algorithms
func (*ExportDataStatement) Execute ¶ added in v0.34.0
func (s *ExportDataStatement) Execute(ctx context.Context, session *Session, out OperationOutput) (*Result, error)
func (*ExportDataStatement) String ¶ added in v0.34.0
func (s *ExportDataStatement) String() string
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 / 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
DDLExecutionMode enums.DDLExecutionMode // DDL_EXECUTION_MODE
DDLAsyncWaitTimeout time.Duration // DDL_ASYNC_WAIT_TIMEOUT
DefaultSequenceKind string // DEFAULT_SEQUENCE_KIND (empty = disabled)
AutoConnectAfterCreate bool // CLI_AUTO_CONNECT_AFTER_CREATE
LogLevel slog.Level // CLI_LOG_LEVEL (session-reported; runtime threshold is runtimeLogLevel when bound)
DatabaseDialect databasepb.DatabaseDialect // CLI_DATABASE_DIALECT
}
FeatureVars holds feature flags and experimental configuration.
type HelpStatement ¶
type HelpStatement struct{}
func (*HelpStatement) Execute ¶
func (s *HelpStatement) Execute(ctx context.Context, session *Session, out OperationOutput) (*Result, error)
type HelpVariablesStatement ¶
type HelpVariablesStatement struct{}
func (*HelpVariablesStatement) Execute ¶
func (s *HelpVariablesStatement) Execute(ctx context.Context, session *Session, out OperationOutput) (*Result, error)
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 // PROTO_DESCRIPTORS_FILE_PATH
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. runtime is nil for isolated fixtures.
func (*LogLevelVar) Get ¶
func (l *LogLevelVar) Get() (string, error)
func (*LogLevelVar) PrepareReset ¶ added in v0.35.0
func (l *LogLevelVar) PrepareReset(value string) error
PrepareReset parses a log level without changing the process threshold.
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 ¶
func (*MutateStatement) Execute ¶
func (s *MutateStatement) Execute(ctx context.Context, session *Session, out OperationOutput) (*Result, error)
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{}
func (*NopStatement) Execute ¶
func (s *NopStatement) Execute(ctx context.Context, session *Session, out OperationOutput) (*Result, error)
type OperationOutput ¶ added in v0.35.0
type OperationOutput struct {
// contains filtered or unexported fields
}
OperationOutput is the per-statement output destination for streamed results (streaming formats, DUMP, shell). It is resolved once at the statement entry point (Cli.executeStatement, which also serves the MCP handler through its writer argument, and Session.ExecuteStatement for direct callers) and carried through Execute and every nested execution path.
Before this type existed, streaming paths wrote to the process-global StreamManager writer regardless of which writer the caller passed to Cli.executeStatement. Under --mcp that writer is the JSON-RPC stdout, so any streamed statement corrupted the protocol stream. The caller-provided writer is authoritative on every path. A statement that does not emit output ignores the value.
func (OperationOutput) ScreenWidth ¶ added in v0.35.0
func (o OperationOutput) ScreenWidth() int
ScreenWidth returns the screen width for streamed rendering. When no resolver is set, wrapping is disabled.
func (OperationOutput) Writer ¶ added in v0.35.0
func (o OperationOutput) Writer() io.Writer
Writer returns the destination for streamed statement output. Nil means streaming paths should buffer instead.
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)
func (*OutputRedirectMetaCommand) Execute ¶
func (o *OutputRedirectMetaCommand) Execute(ctx context.Context, session *Session, out OperationOutput) (*Result, error)
Execute enables output redirect to the specified file (file only)
type PartitionStatement ¶
type PartitionStatement struct{ SQL string }
func (*PartitionStatement) Execute ¶
func (s *PartitionStatement) Execute(ctx context.Context, session *Session, out OperationOutput) (*Result, error)
type PartitionedDmlStatement ¶
type PartitionedDmlStatement struct {
Dml string
}
func (*PartitionedDmlStatement) Execute ¶
func (s *PartitionedDmlStatement) Execute(ctx context.Context, session *Session, out OperationOutput) (*Result, error)
type PromptMetaCommand ¶
type PromptMetaCommand struct {
PromptString string
}
PromptMetaCommand changes the prompt string using \R syntax
func (*PromptMetaCommand) Execute ¶
func (p *PromptMetaCommand) Execute(ctx context.Context, session *Session, out OperationOutput) (*Result, error)
Execute updates the CLI_PROMPT system variable
type ProtoDescriptorVar ¶
type ProtoDescriptorVar struct {
// contains filtered or unexported fields
}
ProtoDescriptorVar handles PROTO_DESCRIPTORS_FILE_PATH 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 ProtoDescriptorsVar ¶ added in v0.35.0
type ProtoDescriptorsVar struct {
// contains filtered or unexported fields
}
ProtoDescriptorsVar handles PROTO_DESCRIPTORS (base64 FileDescriptorSet).
func (*ProtoDescriptorsVar) Get ¶ added in v0.35.0
func (p *ProtoDescriptorsVar) Get() (string, error)
func (*ProtoDescriptorsVar) Set ¶ added in v0.35.0
func (p *ProtoDescriptorsVar) 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]) PrepareReset ¶ added in v0.35.0
func (p *ProtoEnumVar[T]) PrepareReset(value string) error
PrepareReset validates the proto enum without assigning to the live pointer.
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 PullRemoteProtoStatement ¶ added in v0.35.0
PullRemoteProtoStatement copies selected remote PROTO/ENUM files and their import closure into the local descriptor store. It never submits remote DDL.
func (*PullRemoteProtoStatement) Execute ¶ added in v0.35.0
func (s *PullRemoteProtoStatement) Execute(ctx context.Context, session *Session, out OperationOutput) (*Result, error)
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 // DIRECTED_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 ReleaseSavepointStatement ¶ added in v0.35.0
type ReleaseSavepointStatement struct {
Name string
}
func (*ReleaseSavepointStatement) Execute ¶ added in v0.35.0
func (s *ReleaseSavepointStatement) Execute(_ context.Context, session *Session, _ OperationOutput) (*Result, error)
type ResetAllStatement ¶ added in v0.35.0
type ResetAllStatement struct{}
ResetAllStatement implements `RESET ALL`: restore captured startup snapshots for every supported resettable variable. Init-command values are included because capture happens before both init-command forms.
func (*ResetAllStatement) Execute ¶ added in v0.35.0
func (s *ResetAllStatement) Execute(ctx context.Context, session *Session, out OperationOutput) (*Result, error)
type ResetStatement ¶ added in v0.35.0
type ResetStatement struct {
VarName string
}
ResetStatement implements `RESET <name>`: restore one canonical name or alias to its captured startup snapshot. It uses the shared prepare/commit path so a successful reset retires only that variable's LOCAL undo.
func (*ResetStatement) Execute ¶ added in v0.35.0
func (s *ResetStatement) Execute(ctx context.Context, session *Session, out OperationOutput) (*Result, error)
type Result ¶
type Result struct {
ColumnAlign []tw.Align // optional
// Body is the single closed payload. The zero value is no body and does
// not mean output was already delivered. Constructors on ResultBody set
// presentation rows, typed rows, prepared bytes, or already-delivered output.
Body ResultBody
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
// MutationLimitFallback is set when implicit transactional DML was retried
// as partitioned DML after a SQL-phase mutation-limit failure. The count
// is a lower bound and the write is non-atomic.
MutationLimitFallback 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 presentation-body cells were formatted as
// SQL literals using spanvalue.LiteralFormatConfig instead of regular display
// formatting, so they may be replayed into INSERT statements. This flag
// governs the presentation-body replay path; the 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 presentation cells 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
Metrics *metrics.ExecutionMetrics // Performance metrics for query execution
// contains filtered or unexported fields
}
type ResultAppendix ¶ added in v0.31.0
ResultAppendix is a titled set of post-table diagnostic lines.
type ResultBody ¶ added in v0.35.0
type ResultBody struct {
// contains filtered or unexported fields
}
ResultBody is the closed payload of a Result. Shared metadata stays on Result. The zero value is no body and does not imply that output was already delivered. Constructors are the only way to set a kind; the discriminant is not settable. Feature packages construct presentation tables through PresentationBody.
func DeliveredBody ¶ added in v0.35.0
func DeliveredBody() ResultBody
DeliveredBody means the body was already written during execution. Appendices and summaries still print; no-body is a different kind.
func PreparedBody ¶ added in v0.35.0
func PreparedBody(output []byte) ResultBody
PreparedBody is pre-rendered output that must be written as-is, including zero-length bytes. Empty prepared output bypasses table rendering rather than falling through to headers.
func PresentationBody ¶ added in v0.35.0
func PresentationBody(rows []Row) ResultBody
PresentationBody is a display-text table, including a zero-row table whose headers still render. Passing a nil or empty slice is an explicit empty presentation table, not no-body.
func TypedBody ¶ added in v0.35.0
func TypedBody(typed *TypedRows) ResultBody
TypedBody is a buffered result-set of raw *spanner.Row values. A TypedRows with metadata and zero rows is zero-row typed data, not no-body.
func (ResultBody) AlreadyDelivered ¶ added in v0.35.0
func (b ResultBody) AlreadyDelivered() bool
AlreadyDelivered reports that execution already wrote the body.
func (ResultBody) IsNone ¶ added in v0.35.0
func (b ResultBody) IsNone() bool
IsNone reports the zero value: no body, and not already delivered.
func (ResultBody) PreparedBytes ¶ added in v0.35.0
func (b ResultBody) PreparedBytes() (output []byte, ok bool)
PreparedBytes returns the pre-rendered bytes when the body is prepared output. ok is true even when the slice is empty or nil.
func (ResultBody) PresentationRows ¶ added in v0.35.0
func (b ResultBody) PresentationRows() (rows []Row, ok bool)
PresentationRows returns the display-text rows when the body is a presentation table. ok is false for every other kind.
func (ResultBody) Typed ¶ added in v0.35.0
func (b ResultBody) Typed() (typed *TypedRows, ok bool)
Typed returns the typed buffered payload when the body is typed rows.
type RollbackStatement ¶
type RollbackStatement struct{}
func (*RollbackStatement) Execute ¶
func (s *RollbackStatement) Execute(ctx context.Context, session *Session, out OperationOutput) (*Result, error)
type RollbackToSavepointStatement ¶ added in v0.35.0
type RollbackToSavepointStatement struct {
Name string
}
func (*RollbackToSavepointStatement) Execute ¶ added in v0.35.0
func (s *RollbackToSavepointStatement) Execute(ctx context.Context, session *Session, _ OperationOutput) (*Result, error)
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, config format.FormatConfig) 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 streamingProcessorFor.
type RunBatchStatement ¶
type RunBatchStatement struct{}
func (*RunBatchStatement) Execute ¶
func (s *RunBatchStatement) Execute(ctx context.Context, session *Session, out OperationOutput) (*Result, error)
type RunPartitionStatement ¶
type RunPartitionStatement struct{ Token string }
func (*RunPartitionStatement) Execute ¶
func (s *RunPartitionStatement) Execute(ctx context.Context, session *Session, out OperationOutput) (*Result, error)
type RunPartitionedQueryStatement ¶
type RunPartitionedQueryStatement struct{ SQL string }
func (*RunPartitionedQueryStatement) Execute ¶
func (s *RunPartitionedQueryStatement) Execute(ctx context.Context, session *Session, out OperationOutput) (*Result, error)
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 SavepointStatement ¶ added in v0.35.0
type SavepointStatement struct {
Name string
}
func (*SavepointStatement) Execute ¶ added in v0.35.0
func (s *SavepointStatement) Execute(ctx context.Context, session *Session, _ OperationOutput) (*Result, error)
type SelectStatement ¶
type SelectStatement struct {
Query string
}
func (*SelectStatement) Execute ¶
func (s *SelectStatement) Execute(ctx context.Context, session *Session, out OperationOutput) (*Result, error)
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 with the session's default output destination (StreamManager writer, or nil so streaming paths buffer). Nested execution that must keep a caller-provided destination should use ExecuteStatementWithOutput instead. 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 OperationOutput) (*Result, error)
ExecuteStatementWithOutput executes stmt with out as the per-statement output destination. Fallback writer and width are resolved here; nested execution (e.g. RUN BATCH) must forward the same value rather than re-entering ExecuteStatement, which would rebuild a default 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) GetDatabaseDdlFresh ¶ added in v0.35.0
GetDatabaseDdlFresh fetches schema DDL without using the 30-second cache. DUMP data-catalog interleave edges use this so a stale cached parent FQN cannot silently bind the wrong schema. It does not populate ddlCache.
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 session's construction-time Spanner project.
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
// contains filtered or unexported fields
}
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 OperationOutput) (*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 ¶
func (*SetAddStatement) Execute ¶
func (s *SetAddStatement) Execute(ctx context.Context, session *Session, out OperationOutput) (*Result, error)
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 transactionContext undo log and restored when the transaction ends, whether by COMMIT, ROLLBACK, or CLOSE. Following java-spanner, SET LOCAL outside a transaction is an error.
func (*SetLocalStatement) Execute ¶ added in v0.32.0
func (s *SetLocalStatement) Execute(ctx context.Context, session *Session, out OperationOutput) (*Result, error)
type SetParamTypeStatement ¶
func (*SetParamTypeStatement) Execute ¶
func (s *SetParamTypeStatement) Execute(ctx context.Context, session *Session, out OperationOutput) (*Result, error)
type SetParamValueStatement ¶
func (*SetParamValueStatement) Execute ¶
func (s *SetParamValueStatement) Execute(ctx context.Context, session *Session, out OperationOutput) (*Result, error)
type SetStatement ¶
func (*SetStatement) Execute ¶
func (s *SetStatement) Execute(ctx context.Context, session *Session, out OperationOutput) (*Result, error)
type SetTransactionStatement ¶
type SetTransactionStatement struct {
IsReadOnly bool
}
func (*SetTransactionStatement) Execute ¶
func (s *SetTransactionStatement) Execute(ctx context.Context, session *Session, out OperationOutput) (*Result, error)
type ShellMetaCommand ¶
type ShellMetaCommand struct {
Command string
}
ShellMetaCommand executes system shell commands using \! syntax
func (*ShellMetaCommand) Execute ¶
func (s *ShellMetaCommand) Execute(ctx context.Context, session *Session, out OperationOutput) (*Result, error)
Execute runs the shell command
type ShowColumnsStatement ¶
func (*ShowColumnsStatement) Execute ¶
func (s *ShowColumnsStatement) Execute(ctx context.Context, session *Session, out OperationOutput) (*Result, error)
type ShowCreateStatement ¶
func (*ShowCreateStatement) Execute ¶
func (s *ShowCreateStatement) Execute(ctx context.Context, session *Session, out OperationOutput) (*Result, error)
type ShowDatabasesStatement ¶
type ShowDatabasesStatement struct{}
func (*ShowDatabasesStatement) Execute ¶
func (s *ShowDatabasesStatement) Execute(ctx context.Context, session *Session, out OperationOutput) (*Result, error)
type ShowDdlsStatement ¶
type ShowDdlsStatement struct{}
func (*ShowDdlsStatement) Execute ¶
func (s *ShowDdlsStatement) Execute(ctx context.Context, session *Session, out OperationOutput) (*Result, error)
type ShowIndexStatement ¶
func (*ShowIndexStatement) Execute ¶
func (s *ShowIndexStatement) Execute(ctx context.Context, session *Session, out OperationOutput) (*Result, error)
type ShowLastQueryPlanStatement ¶ added in v0.33.1
ShowLastQueryPlanStatement exports the cached last query plan as official Cloud Spanner ProtoJSON, or as ProtoJSON-equivalent YAML for .yaml/.yml destinations (QueryPlan, or ResultSetStats when WITH STATS is set). It is intended as a lossless handoff boundary for external viewers; it does not expose plantree/renderer DTOs.
func (*ShowLastQueryPlanStatement) Execute ¶ added in v0.33.1
func (s *ShowLastQueryPlanStatement) Execute(ctx context.Context, session *Session, out OperationOutput) (*Result, error)
type ShowLocalProtoStatement ¶
type ShowLocalProtoStatement struct{}
func (*ShowLocalProtoStatement) Execute ¶
func (s *ShowLocalProtoStatement) Execute(ctx context.Context, session *Session, out OperationOutput) (*Result, error)
type ShowOperationStatement ¶
func (*ShowOperationStatement) Execute ¶
func (s *ShowOperationStatement) Execute(ctx context.Context, session *Session, out OperationOutput) (*Result, error)
type ShowParamsStatement ¶
type ShowParamsStatement struct{}
func (*ShowParamsStatement) Execute ¶
func (s *ShowParamsStatement) Execute(ctx context.Context, session *Session, out OperationOutput) (*Result, error)
type ShowPlanNodeStatement ¶
type ShowPlanNodeStatement struct {
NodeID int
}
func (*ShowPlanNodeStatement) Execute ¶
func (s *ShowPlanNodeStatement) Execute(ctx context.Context, session *Session, out OperationOutput) (*Result, error)
type ShowQueryProfileStatement ¶
type ShowQueryProfileStatement struct {
Fprint int64
}
func (*ShowQueryProfileStatement) Execute ¶
func (s *ShowQueryProfileStatement) Execute(ctx context.Context, session *Session, out OperationOutput) (*Result, error)
type ShowQueryProfilesStatement ¶
type ShowQueryProfilesStatement struct{}
func (*ShowQueryProfilesStatement) Execute ¶
func (s *ShowQueryProfilesStatement) Execute(ctx context.Context, session *Session, out OperationOutput) (*Result, error)
type ShowRemoteProtoStatement ¶
type ShowRemoteProtoStatement struct{}
func (*ShowRemoteProtoStatement) Execute ¶
func (s *ShowRemoteProtoStatement) Execute(ctx context.Context, session *Session, out OperationOutput) (*Result, error)
type ShowSchemaUpdateOperations ¶
type ShowSchemaUpdateOperations struct{}
func (*ShowSchemaUpdateOperations) Execute ¶
func (s *ShowSchemaUpdateOperations) Execute(ctx context.Context, session *Session, out OperationOutput) (*Result, error)
type ShowSplitPointsStatement ¶
type ShowSplitPointsStatement struct{}
func (*ShowSplitPointsStatement) Execute ¶
func (s *ShowSplitPointsStatement) Execute(ctx context.Context, session *Session, out OperationOutput) (*Result, error)
type ShowTablesStatement ¶
type ShowTablesStatement struct {
Schema string
}
func (*ShowTablesStatement) Execute ¶
func (s *ShowTablesStatement) Execute(ctx context.Context, session *Session, out OperationOutput) (*Result, error)
type ShowTransactionStatement ¶ added in v0.35.0
type ShowTransactionStatement struct {
Kind showTransactionKind
}
func (*ShowTransactionStatement) Execute ¶ added in v0.35.0
func (s *ShowTransactionStatement) Execute(ctx context.Context, session *Session, out OperationOutput) (*Result, error)
type ShowVariableStatement ¶
type ShowVariableStatement struct {
VarName string
}
func (*ShowVariableStatement) Execute ¶
func (s *ShowVariableStatement) Execute(ctx context.Context, session *Session, out OperationOutput) (*Result, error)
type ShowVariablesStatement ¶
type ShowVariablesStatement struct{}
func (*ShowVariablesStatement) Execute ¶
func (s *ShowVariablesStatement) Execute(ctx context.Context, session *Session, out OperationOutput) (*Result, error)
type SourceMetaCommand ¶
type SourceMetaCommand struct {
FilePath string
}
SourceMetaCommand executes SQL statements from a file using \. syntax
func (*SourceMetaCommand) Execute ¶
func (s *SourceMetaCommand) Execute(ctx context.Context, session *Session, out OperationOutput) (*Result, error)
Execute is not used for SourceMetaCommand as it's handled specially in CLI
type StartBatchStatement ¶
type StartBatchStatement struct {
Mode batchMode
}
func (*StartBatchStatement) Execute ¶
func (s *StartBatchStatement) Execute(ctx context.Context, session *Session, out OperationOutput) (*Result, error)
type StartupConfig ¶ added in v0.32.0
type StartupConfig struct {
Host string // CLI_HOST
Port int // CLI_PORT
Insecure bool // CLI_INSECURE
WithoutAuthentication bool // CLI_WITHOUT_AUTHENTICATION
CaCertFile string // CLI_CA_CERT_FILE
ClientCertFile string // CLI_CLIENT_CERT_FILE
ClientCertKey string // CLI_CLIENT_CERT_KEY
ImpersonateServiceAccount string // CLI_IMPERSONATE_SERVICE_ACCOUNT
// TLSClientOptions is the immutable custom-TLS transport captured once at
// startup via omni.ConnectionOptions. USE/DETACH/RecreateClient reuse
// Session.clientOpts and must not reread certificate files.
TLSClientOptions []option.ClientOption
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
// SpannerMetricsExporter and SpannerMetricsEndpoint are startup-only
// caller-owned client-metrics settings (--spanner-metrics-exporter /
// --spanner-metrics-endpoint). Empty exporter is treated as off.
SpannerMetricsExporter string // CLI_SPANNER_METRICS_EXPORTER
SpannerMetricsEndpoint string // CLI_SPANNER_METRICS_ENDPOINT
// SpannerTracesExporter, SpannerTracesEndpoint, and
// SpannerTracesSampleRatio are startup-only process-owned client-trace
// settings. Empty exporter is treated as off. Off mode must not change
// the global TracerProvider or environment.
SpannerTracesExporter string // CLI_SPANNER_TRACES_EXPORTER
SpannerTracesEndpoint string // CLI_SPANNER_TRACES_ENDPOINT
SpannerTracesSampleRatio float64 // CLI_SPANNER_TRACES_SAMPLE_RATIO
// ClientMetricsProvider is the process-owned or test-injected meter
// provider. Not a registered variable. Off mode must not clear a
// preexisting injected value.
ClientMetricsProvider metric.MeterProvider
// EmbeddedLogLevel is the --log-level value parsed at startup. It gates
// embedded runtime container lifecycle logs and is not CLI_LOG_LEVEL:
// --set and later SQL SET must not change it.
EmbeddedLogLevel slog.Level
// 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 ¶
type Statement interface {
Execute(ctx context.Context, session *Session, out OperationOutput) (*Result, error)
}
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, config format.FormatConfig) 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 SyncProtoStatement struct {
UpsertPaths []string
DeletePaths []string
// contains filtered or unexported fields
}
func (*SyncProtoStatement) Execute ¶
func (s *SyncProtoStatement) Execute(ctx context.Context, session *Session, out OperationOutput) (*Result, error)
type TableDependency ¶
type TableDependency struct {
ID tableID
ParentBasename string // TABLES.PARENT_TABLE_NAME; never a schema
InterleaveParent *tableID // set only after authoritative DDL, and only if selected
// FKParents are selected-table FK prerequisites used only for physical
// INSERT order. Self-edges are omitted because a table cannot precede
// itself. Known NOT ENFORCED FKs are omitted from this graph as well as
// from SafetyFKParents. Ancestor-to-descendant FKs stay here but are
// skipped at order time so INTERLEAVE parent-first is preserved.
FKParents []tableID
// SafetyFKParents are enforced (or unknown-enforcement) FK prerequisites
// including self-edges. Known NOT ENFORCED constraints are omitted.
// This graph is not used for INSERT order.
SafetyFKParents []tableID
}
TableDependency is a BASE TABLE member of the dump data catalog.
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, config format.FormatConfig) 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)
func (*TeeOutputMetaCommand) Execute ¶
func (t *TeeOutputMetaCommand) Execute(ctx context.Context, session *Session, out OperationOutput) (*Result, error)
Execute enables tee output to the specified file (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) PrepareReset ¶ added in v0.35.0
func (t *TemplateVar) PrepareReset(value string) error
PrepareReset validates the template string without writing parsed state.
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) PrepareReset ¶ added in v0.35.0
func (t *TimestampBoundVar) PrepareReset(value string) error
PrepareReset parses a timestamp bound without assigning it.
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 TransactionManager and binds it as the live inTransaction / TRANSACTION_TAG callbacks. SessionHandler candidate construction uses newTransactionManager instead.
func (*TransactionManager) AutomaticBatchInfo ¶ added in v0.35.0
func (tm *TransactionManager) AutomaticBatchInfo() *BatchInfo
AutomaticBatchInfo returns pending-automatic BatchInfo, or nil if the queue is empty.
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 the current read-write transaction. A Commit RPC attempt invalidates the server transaction, so the owner is retired after that attempt. Recovery/flush admission errors do not retire.
func (*TransactionManager) CreateSavepoint ¶ added in v0.35.0
func (tm *TransactionManager) CreateSavepoint(ctx context.Context, name string) error
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) DiscardAutomaticDML ¶ added in v0.35.0
func (tm *TransactionManager) DiscardAutomaticDML()
DiscardAutomaticDML drops pending automatic DML without executing it. ABORT BATCH uses this; it does not roll back already executed statements and does not change AUTO_BATCH_DML.
func (*TransactionManager) FlushAutomaticDML ¶ added in v0.35.0
func (tm *TransactionManager) FlushAutomaticDML(ctx context.Context) (*Result, error)
FlushAutomaticDML executes queued automatic DML on the existing RW owner. It never starts an implicit transaction. An empty queue is a no-op. On BatchUpdate failure the RW transaction is rolled back and the queue is not replayable in a later owner. I/O under mu matches executeBatchDML.
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) HandleOwnerFailure ¶ added in v0.35.0
func (tm *TransactionManager) HandleOwnerFailure(ctx context.Context, tok *captureToken, err error) error
func (*TransactionManager) HasAutomaticDML ¶ added in v0.35.0
func (tm *TransactionManager) HasAutomaticDML() bool
HasAutomaticDML reports whether automatic DML is waiting on the current transaction context.
func (*TransactionManager) HasUserWork ¶ added in v0.35.0
func (tm *TransactionManager) HasUserWork() bool
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) NeedsRecovery ¶ added in v0.35.0
func (tm *TransactionManager) NeedsRecovery() bool
func (*TransactionManager) ReleaseSavepoint ¶ added in v0.35.0
func (tm *TransactionManager) ReleaseSavepoint(name string) error
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) RollbackToSavepoint ¶ added in v0.35.0
func (tm *TransactionManager) RollbackToSavepoint(ctx context.Context, name string) error
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) RunSingleUseQueryWithStats ¶ added in v0.34.0
func (tm *TransactionManager) RunSingleUseQueryWithStats(ctx context.Context, stmt spanner.Statement, mode sppb.ExecuteSqlRequest_QueryMode) (*spanner.RowIterator, *spanner.ReadOnlyTransaction, error)
RunSingleUseQueryWithStats executes a statement in a single-use read-only transaction even when the session has an active explicit transaction. It preserves the query options and one-shot request-tag behavior of ordinary query execution.
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. Aborted paths that trigger RecreateClient roll back or clear the transaction first; recoverable SAVEPOINT abort skips recreation while the owner is still attached. 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) TryEnqueueAutomaticDML ¶ added in v0.35.0
func (tm *TransactionManager) TryEnqueueAutomaticDML(stmt spanner.Statement) (bool, error)
TryEnqueueAutomaticDML appends stmt to the current explicit RW transaction's automatic queue. It returns enqueued=false without error when no RW owner exists so implicit DML can execute immediately.
func (*TransactionManager) ValidateDatabaseOperation ¶ added in v0.28.0
func (tm *TransactionManager) ValidateDatabaseOperation() error
ValidateDatabaseOperation checks whether the TransactionManager has a valid client.
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
AutoBatchDMLUpdateCount int64 // AUTO_BATCH_DML_UPDATE_COUNT
AutoBatchDMLUpdateCountVerification bool // AUTO_BATCH_DML_UPDATE_COUNT_VERIFICATION
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
CommitPriority sppb.RequestOptions_Priority // COMMIT_PRIORITY
KeepTransactionAlive bool // KEEP_TRANSACTION_ALIVE
TransactionTimeout *time.Duration // TRANSACTION_TIMEOUT
IdleTransactionTimeout *time.Duration // CLI_IDLE_TRANSACTION_TIMEOUT
DdlInTransactionMode enums.DdlInTransactionMode // CLI_DDL_IN_TRANSACTION_MODE
SavepointSupport enums.SavepointSupport // CLI_SAVEPOINT_SUPPORT
Autocommit bool // AUTOCOMMIT
RetryAbortsInternally bool // RETRY_ABORTS_INTERNALLY (default FALSE)
}
TransactionVars holds transaction-related configuration.
type TruncateTableStatement ¶
func (*TruncateTableStatement) Execute ¶
func (s *TruncateTableStatement) Execute(ctx context.Context, session *Session, out OperationOutput) (*Result, error)
type TryPartitionedQueryStatement ¶
type TryPartitionedQueryStatement struct{ SQL string }
func (*TryPartitionedQueryStatement) Execute ¶
func (s *TryPartitionedQueryStatement) Execute(ctx context.Context, session *Session, out OperationOutput) (*Result, error)
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 typed-body payload of Result.Body; presentation rows, prepared bytes, and already-delivered output are the other ResultBody kinds.
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
}
func (*UnsetParamStatement) Execute ¶
func (s *UnsetParamStatement) Execute(ctx context.Context, session *Session, out OperationOutput) (*Result, error)
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)
// contains filtered or unexported fields
}
UpdateResult holds the complete result of an update operation.
type UseDatabaseMetaCommand ¶
type UseDatabaseMetaCommand struct {
Database string
}
UseDatabaseMetaCommand switches database using \u syntax
func (*UseDatabaseMetaCommand) Execute ¶
func (s *UseDatabaseMetaCommand) Execute(ctx context.Context, session *Session, out OperationOutput) (*Result, error)
Execute is required by Statement interface but the actual logic is handled in SessionHandler
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 DefaultSequenceKindVar ¶ added in v0.35.0
func DefaultSequenceKindVar(ptr *string) *VarHandler[string]
func DurationVar ¶ added in v0.35.0
func DurationVar(ptr *time.Duration) *VarHandler[time.Duration]
DurationVar creates a handler for non-nullable duration variables.
func Float64Var ¶ added in v0.35.0
func Float64Var(ptr *float64) *VarHandler[float64]
Float64Var creates a handler for float64 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]) PrepareReset ¶ added in v0.35.0
func (h *VarHandler[T]) PrepareReset(value string) error
PrepareReset parses and validates without assigning to the live pointer.
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).
func (*VarRegistry) Reset ¶ added in v0.35.0
func (r *VarRegistry) Reset(name string) error
func (*VarRegistry) ResetAll ¶ added in v0.35.0
func (r *VarRegistry) ResetAll() error
Source Files
¶
- app.go
- autocommit.go
- batch_manager.go
- cli.go
- cli_mcp.go
- cli_output.go
- cli_readline.go
- client_side_statement_def.go
- config.go
- ddl_in_transaction.go
- default_sequence_kind.go
- dependency_resolver.go
- directed_read.go
- dml_mutation_limit.go
- dump_cycle_safety.go
- dump_cycle_safety_flag.go
- dump_cyclic_mutations.go
- dump_ddl_replay.go
- dump_interleave.go
- dump_table_id.go
- dump_table_selector.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
- idle_transaction.go
- kong_toml_loader.go
- lint_plan.go
- memefish_parser.go
- meta_commands.go
- mutate_prefix.go
- output_context.go
- partition_native.go
- partition_token.go
- proto_descriptor_url.go
- proto_descriptors.go
- pull_remote_proto.go
- result_body.go
- result_sink.go
- retry_aborts.go
- row_iter.go
- row_iterator_transform.go
- row_processor.go
- sample_databases.go
- savepoint_capture.go
- savepoint_fingerprint.go
- savepoint_journal.go
- savepoint_receipt.go
- savepoint_replay.go
- savepoint_statements.go
- separator.go
- session.go
- session_transaction_context.go
- spancodec_bridge.go
- spanner_metrics.go
- spanner_traces.go
- spanner_traces_export.go
- spanvalue_streaming.go
- sql_export_table_name.go
- sql_input.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
- string_quote.go
- system_variables.go
- system_variables_registry.go
- tls_transport.go
- transaction_manager.go
- transaction_manager_auto_dml.go
- transaction_timeout.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
- var_reset.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. |