Documentation
¶
Overview ¶
Package mygram is a Go client library for the MygramDB full-text search engine.
MygramDB is an in-memory full-text search engine using a memcached-style text protocol, answering queries from memory rather than an on-disk MySQL FULLTEXT index.
Basic usage:
client := mygram.NewClient("localhost:11016")
defer client.Close()
if err := client.Connect(); err != nil {
log.Fatal(err)
}
resp, err := client.Search("threads", "keyword", mygram.SearchOptions{
Limit: 100,
SortColumn: "created_at",
SortDesc: true,
})
Index ¶
- func ConvertSearchExpression(expression string) (string, error)
- func HasComplexExpression(expr *SearchExpression) bool
- func ParseTableIdentity(identity string) (database, table string, err error)
- func QualifyTableIdentity(table, database string) (string, error)
- func ToQueryString(expr *SearchExpression) string
- type CacheStats
- type CircuitBreakerConfig
- type CircuitOpenError
- type Client
- func (c *Client) Authenticate(token string) error
- func (c *Client) AuthenticateContext(ctx context.Context, token string) error
- func (c *Client) CacheClear(table string) error
- func (c *Client) CacheClearContext(ctx context.Context, table string) error
- func (c *Client) CacheDisable() error
- func (c *Client) CacheDisableContext(ctx context.Context) error
- func (c *Client) CacheEnable() error
- func (c *Client) CacheEnableContext(ctx context.Context) error
- func (c *Client) CacheStats() (*CacheStats, error)
- func (c *Client) CacheStatsContext(ctx context.Context) (*CacheStats, error)
- func (c *Client) Close() error
- func (c *Client) Connect() error
- func (c *Client) ConnectContext(ctx context.Context) error
- func (c *Client) Count(table, query string, opts CountOptions) (*CountResponse, error)
- func (c *Client) CountContext(ctx context.Context, table, query string, opts CountOptions) (*CountResponse, error)
- func (c *Client) DisableDebug() error
- func (c *Client) DisableDebugContext(ctx context.Context) error
- func (c *Client) DumpInfo(filepath string) (string, error)
- func (c *Client) DumpInfoContext(ctx context.Context, filepath string) (string, error)
- func (c *Client) DumpLoad(filepath string) error
- func (c *Client) DumpLoadContext(ctx context.Context, filepath string) error
- func (c *Client) DumpSave(filepath string) (string, error)
- func (c *Client) DumpSaveAndWait(filepath string) (string, error)
- func (c *Client) DumpSaveAndWaitContext(ctx context.Context, filepath string) (string, error)
- func (c *Client) DumpSaveContext(ctx context.Context, filepath string) (string, error)
- func (c *Client) DumpStatus() (*DumpStatus, error)
- func (c *Client) DumpStatusContext(ctx context.Context) (*DumpStatus, error)
- func (c *Client) DumpVerify(filepath string) (string, error)
- func (c *Client) DumpVerifyContext(ctx context.Context, filepath string) (string, error)
- func (c *Client) EnableDebug() error
- func (c *Client) EnableDebugContext(ctx context.Context) error
- func (c *Client) Facet(table, column string, opts FacetOptions) (*FacetResponse, error)
- func (c *Client) FacetContext(ctx context.Context, table, column string, opts FacetOptions) (*FacetResponse, error)
- func (c *Client) Get(table, primaryKey string) (*Document, error)
- func (c *Client) GetConfig() (string, error)
- func (c *Client) GetConfigContext(ctx context.Context) (string, error)
- func (c *Client) GetContext(ctx context.Context, table, primaryKey string) (*Document, error)
- func (c *Client) GetReplicationStatus() (*ReplicationStatus, error)
- func (c *Client) GetReplicationStatusContext(ctx context.Context) (*ReplicationStatus, error)
- func (c *Client) Info() (*ServerInfo, error)
- func (c *Client) InfoContext(ctx context.Context) (*ServerInfo, error)
- func (c *Client) IsConnected() bool
- func (c *Client) Optimize(table string) error
- func (c *Client) OptimizeContext(ctx context.Context, table string) error
- func (c *Client) Search(table, query string, opts SearchOptions) (*SearchResponse, error)
- func (c *Client) SearchContext(ctx context.Context, table, query string, opts SearchOptions) (*SearchResponse, error)
- func (c *Client) SearchRaw(table, rawQuery string, opts SearchRawOptions) (*SearchResponse, error)
- func (c *Client) SearchRawContext(ctx context.Context, table, rawQuery string, opts SearchRawOptions) (*SearchResponse, error)
- func (c *Client) SearchRawWithHighlights(table, rawQuery string, opts SearchRawOptions) (*SearchResponse, error)
- func (c *Client) SearchRawWithHighlightsContext(ctx context.Context, table, rawQuery string, opts SearchRawOptions) (*SearchResponse, error)
- func (c *Client) SearchWithHighlights(table, query string, opts SearchOptions) (*SearchResponse, error)
- func (c *Client) SearchWithHighlightsContext(ctx context.Context, table, query string, opts SearchOptions) (*SearchResponse, error)
- func (c *Client) SendCommand(command string) (string, error)
- func (c *Client) SendCommandContext(ctx context.Context, command string) (string, error)
- func (c *Client) SetVariable(name, value string) error
- func (c *Client) SetVariableContext(ctx context.Context, name, value string) error
- func (c *Client) ShowVariables(likePattern string) (string, error)
- func (c *Client) ShowVariablesContext(ctx context.Context, likePattern string) (string, error)
- func (c *Client) StartReplication() error
- func (c *Client) StartReplicationContext(ctx context.Context) error
- func (c *Client) StopReplication() error
- func (c *Client) StopReplicationContext(ctx context.Context) error
- func (c *Client) Sync(table string) (string, error)
- func (c *Client) SyncContext(ctx context.Context, table string) (string, error)
- func (c *Client) SyncStatus() (string, error)
- func (c *Client) SyncStatusContext(ctx context.Context) (string, error)
- func (c *Client) SyncStop(table string) (string, error)
- func (c *Client) SyncStopContext(ctx context.Context, table string) (string, error)
- type ClientConfig
- type ConnectionError
- type CountOptions
- type CountResponse
- type DebugInfo
- type Document
- type DumpStatus
- type ErrorCode
- type FacetOptions
- type FacetResponse
- type FacetValue
- type FilterCondition
- type FilterOp
- type HighlightOptions
- type Pool
- func (p *Pool) CacheClear(table string) error
- func (p *Pool) CacheClearContext(ctx context.Context, table string) error
- func (p *Pool) CacheDisable() error
- func (p *Pool) CacheDisableContext(ctx context.Context) error
- func (p *Pool) CacheEnable() error
- func (p *Pool) CacheEnableContext(ctx context.Context) error
- func (p *Pool) CacheStats() (*CacheStats, error)
- func (p *Pool) CacheStatsContext(ctx context.Context) (*CacheStats, error)
- func (p *Pool) Close() error
- func (p *Pool) Count(table, query string, opts CountOptions) (*CountResponse, error)
- func (p *Pool) CountContext(ctx context.Context, table, query string, opts CountOptions) (*CountResponse, error)
- func (p *Pool) DisableDebug() error
- func (p *Pool) DisableDebugContext(ctx context.Context) error
- func (p *Pool) DumpInfo(filepath string) (string, error)
- func (p *Pool) DumpInfoContext(ctx context.Context, filepath string) (string, error)
- func (p *Pool) DumpLoad(filepath string) error
- func (p *Pool) DumpLoadContext(ctx context.Context, filepath string) error
- func (p *Pool) DumpSave(filepath string) (string, error)
- func (p *Pool) DumpSaveAndWait(filepath string) (string, error)
- func (p *Pool) DumpSaveAndWaitContext(ctx context.Context, filepath string) (string, error)
- func (p *Pool) DumpSaveContext(ctx context.Context, filepath string) (string, error)
- func (p *Pool) DumpStatus() (*DumpStatus, error)
- func (p *Pool) DumpStatusContext(ctx context.Context) (*DumpStatus, error)
- func (p *Pool) DumpVerify(filepath string) (string, error)
- func (p *Pool) DumpVerifyContext(ctx context.Context, filepath string) (string, error)
- func (p *Pool) EnableDebug() error
- func (p *Pool) EnableDebugContext(ctx context.Context) error
- func (p *Pool) Facet(table, column string, opts FacetOptions) (*FacetResponse, error)
- func (p *Pool) FacetContext(ctx context.Context, table, column string, opts FacetOptions) (*FacetResponse, error)
- func (p *Pool) Get(table, primaryKey string) (*Document, error)
- func (p *Pool) GetConfig() (string, error)
- func (p *Pool) GetConfigContext(ctx context.Context) (string, error)
- func (p *Pool) GetContext(ctx context.Context, table, primaryKey string) (*Document, error)
- func (p *Pool) GetReplicationStatus() (*ReplicationStatus, error)
- func (p *Pool) GetReplicationStatusContext(ctx context.Context) (*ReplicationStatus, error)
- func (p *Pool) Info() (*ServerInfo, error)
- func (p *Pool) InfoContext(ctx context.Context) (*ServerInfo, error)
- func (p *Pool) Optimize(table string) error
- func (p *Pool) OptimizeContext(ctx context.Context, table string) error
- func (p *Pool) Search(table, query string, opts SearchOptions) (*SearchResponse, error)
- func (p *Pool) SearchContext(ctx context.Context, table, query string, opts SearchOptions) (*SearchResponse, error)
- func (p *Pool) SearchRaw(table, rawQuery string, opts SearchRawOptions) (*SearchResponse, error)
- func (p *Pool) SearchRawContext(ctx context.Context, table, rawQuery string, opts SearchRawOptions) (*SearchResponse, error)
- func (p *Pool) SearchRawWithHighlights(table, rawQuery string, opts SearchRawOptions) (*SearchResponse, error)
- func (p *Pool) SearchRawWithHighlightsContext(ctx context.Context, table, rawQuery string, opts SearchRawOptions) (*SearchResponse, error)
- func (p *Pool) SearchWithHighlights(table, query string, opts SearchOptions) (*SearchResponse, error)
- func (p *Pool) SearchWithHighlightsContext(ctx context.Context, table, query string, opts SearchOptions) (*SearchResponse, error)
- func (p *Pool) SendCommand(command string) (string, error)
- func (p *Pool) SendCommandContext(ctx context.Context, command string) (string, error)
- func (p *Pool) SetVariable(name, value string) error
- func (p *Pool) SetVariableContext(ctx context.Context, name, value string) error
- func (p *Pool) ShowVariables(likePattern string) (string, error)
- func (p *Pool) ShowVariablesContext(ctx context.Context, likePattern string) (string, error)
- func (p *Pool) StartReplication() error
- func (p *Pool) StartReplicationContext(ctx context.Context) error
- func (p *Pool) Stats() PoolStats
- func (p *Pool) StopReplication() error
- func (p *Pool) StopReplicationContext(ctx context.Context) error
- func (p *Pool) Sync(table string) (string, error)
- func (p *Pool) SyncContext(ctx context.Context, table string) (string, error)
- func (p *Pool) SyncStatus() (string, error)
- func (p *Pool) SyncStatusContext(ctx context.Context) (string, error)
- func (p *Pool) SyncStop(table string) (string, error)
- func (p *Pool) SyncStopContext(ctx context.Context, table string) (string, error)
- func (p *Pool) WithConn(ctx context.Context, fn func(c *Client) error) error
- type PoolConfig
- type PoolEvent
- type PoolStats
- type PrimaryKeySort
- type ProtocolError
- type QueryMode
- type ReplicationStatus
- type RetryPolicy
- type SearchExpression
- type SearchOptions
- type SearchRawOptions
- type SearchResponse
- type SearchResult
- type ServerError
- type ServerInfo
- type SimplifiedExpression
- type TimeoutError
- type ValidationError
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func ConvertSearchExpression ¶
ConvertSearchExpression converts a search expression to a MygramDB query string.
func HasComplexExpression ¶
func HasComplexExpression(expr *SearchExpression) bool
HasComplexExpression returns whether the expression contains OR or grouping: a non-empty RawExpression, or a RequiredTerms/ExcludedTerms entry that is itself a parenthesized sub-expression (from "+(...)" or "-(...)").
func ParseTableIdentity ¶ added in v0.3.0
ParseTableIdentity splits a (possibly database-qualified) table identity into its parts.
Bare names return an empty database and the table name; qualified names are split on the first '.' so "app_db.articles" yields ("app_db", "articles"). The identity is validated as a protocol identifier first.
func QualifyTableIdentity ¶ added in v0.3.0
QualifyTableIdentity builds a database-qualified table identity ("database.table") for MygramDB v1.7+ multi-database deployments.
A single-database deployment continues to accept a bare table name, so an empty database returns just the validated table name. When a database is supplied, both parts are validated as identifiers and must not themselves contain a '.' separator; they are then joined as "database.table".
func ToQueryString ¶
func ToQueryString(expr *SearchExpression) string
ToQueryString converts a SearchExpression to a MygramDB query string, applying the shared wire-quoting decision (wire_quoting.go) to every plain term so a literal term colliding with a reserved keyword, or containing whitespace, reaches the server as the search text it was written as.
Types ¶
type CacheStats ¶
type CacheStats struct {
// Enabled reports whether the query cache is currently serving.
Enabled bool
// TotalQueries is the number of cache lookups, so Hits+Misses.
TotalQueries int
Hits int
Misses int
HitRate float64
// CurrentEntries is the number of cached results held right now.
CurrentEntries int
// MemoryBytes is the cached payload size (the server's
// current_memory_bytes).
MemoryBytes int
// InvalidationIndexMemoryBytes and InvalidationQueueMemoryBytes are the
// reverse indexes that map a row event to the entries it invalidates, and
// the pending-invalidation queue. Both are charged to the cache budget.
InvalidationIndexMemoryBytes int
InvalidationQueueMemoryBytes int
// AccountedMemoryBytes is the total charged against the cache memory
// budget: the payloads plus the invalidation structures.
AccountedMemoryBytes int
// Evictions and TTLExpirations count entries dropped to stay within the
// capacity budget and entries dropped for age.
Evictions int
TTLExpirations int
// The rejection counters are four independent reasons a result was not
// admitted, not a total and its parts: RejectionCount is specifically the
// count of queries cheaper than the server's min_query_cost_ms threshold,
// which is why a healthy cache reports it while the other three stay zero.
RejectionCount int // below the min_query_cost_ms threshold
RejectionOversize int // the entry alone exceeds max_memory_bytes
RejectionMemoryBudget int // the shared budget could not retain it
RejectionDuplicate int // the cache key was already present
// StaleEntryRemovals counts entries discarded because a staleness check
// failed on lookup; DecompressionFailures counts entries dropped because
// their payload could not be restored; StaleLRUEntries counts LRU nodes
// found without a live entry behind them.
StaleEntryRemovals int
DecompressionFailures int
StaleLRUEntries int
// InvalidationsImmediate and InvalidationsDeferred split invalidations by
// whether the row event applied them inline or queued them;
// InvalidationsBatches counts the queue drains.
InvalidationsImmediate int
InvalidationsDeferred int
InvalidationsBatches int
// AvgHitTimeMs and AvgMissTimeMs are nil when the server omitted them,
// which it does while the corresponding counter is still zero. A pointer
// keeps "not reported" distinct from a measured 0.
AvgHitTimeMs *float64
AvgMissTimeMs *float64
// TotalTimeSavedMs is the cumulative query time avoided by cache hits.
TotalTimeSavedMs float64
}
CacheStats represents cache statistics.
A field the server does not report keeps its zero value, so the struct also describes an older server: the counters below the memory block were added over the v1.9 and v1.10 lines.
type CircuitBreakerConfig ¶ added in v0.4.0
type CircuitBreakerConfig struct {
// FailureThreshold is the number of consecutive network failures that open
// the breaker. 0 or negative selects the default (5).
FailureThreshold int
// ResetTimeout is how long the breaker stays open before admitting a trial.
// 0 or negative selects the default (10s).
ResetTimeout time.Duration
}
CircuitBreakerConfig configures a Pool's circuit breaker. Consecutive connect/timeout failures up to FailureThreshold open the breaker; it stays open for ResetTimeout, then admits a single trial (half-open) before closing on success or re-opening on failure. Set PoolConfig.CircuitBreaker to enable it; a nil pointer disables it.
type CircuitOpenError ¶ added in v0.4.0
type CircuitOpenError struct {
Message string
}
CircuitOpenError is returned by a Pool whose circuit breaker is open (or half-open with a trial already in flight). It is raised without touching the network so a caller fails fast instead of piling requests onto a server that is already unreachable. It is not classified as a network failure, so it does not itself drive the breaker.
func (*CircuitOpenError) Error ¶ added in v0.4.0
func (e *CircuitOpenError) Error() string
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client is a MygramDB client.
A Client wraps a single connection and serializes every command with an internal mutex, so it is safe for concurrent use but processes at most one request at a time. For concurrent workloads use a Pool, which lends out many Clients and adds reconnection and retry.
func NewClient ¶
NewClient creates a new client for the given address. addr should be in "host:port" form; an address that does not parse as host:port is treated as a Unix socket path (so a bare "localhost" without a port becomes a socket path, not a TCP host).
The returned Client owns a single connection and must be connected with Connect (or ConnectContext) before issuing commands. Most applications should use NewPool instead, which manages many connections with reconnection and retry; use Client directly only to own and control a single connection.
func NewClientWithConfig ¶
func NewClientWithConfig(config ClientConfig) *Client
NewClientWithConfig creates a new client with the given configuration.
func (*Client) Authenticate ¶ added in v0.5.0
Authenticate authorizes the connection for administrative commands (MygramDB >= v1.10).
func (*Client) AuthenticateContext ¶ added in v0.5.0
AuthenticateContext authorizes the connection for administrative commands with the given context.
A server configured with api.admin_token gates DUMP, SYNC, REPLICATION, CONFIG, CACHE, OPTIMIZE, DEBUG, SET and SHOW VARIABLES behind AUTH, and the grant is per-connection. The token is remembered on the client so a reconnect re-authenticates before the next command runs; setting ClientConfig.AdminToken up front does the same thing without an explicit call, and is the only way to authenticate the connections a Pool opens.
func (*Client) CacheClear ¶
CacheClear clears the cache. If table is specified, only that table's cache is cleared.
func (*Client) CacheClearContext ¶
CacheClearContext clears the cache with the given context.
func (*Client) CacheDisable ¶
CacheDisable disables the cache.
func (*Client) CacheDisableContext ¶
CacheDisableContext disables the cache with the given context.
func (*Client) CacheEnableContext ¶
CacheEnableContext enables the cache with the given context.
func (*Client) CacheStats ¶
func (c *Client) CacheStats() (*CacheStats, error)
CacheStats retrieves cache statistics.
func (*Client) CacheStatsContext ¶
func (c *Client) CacheStatsContext(ctx context.Context) (*CacheStats, error)
CacheStatsContext retrieves cache statistics with the given context.
func (*Client) ConnectContext ¶
ConnectContext establishes a connection to the server with the given context.
func (*Client) Count ¶
func (c *Client) Count(table, query string, opts CountOptions) (*CountResponse, error)
Count returns the number of matching documents.
func (*Client) CountContext ¶
func (c *Client) CountContext(ctx context.Context, table, query string, opts CountOptions) (*CountResponse, error)
CountContext performs a count query with the given context.
func (*Client) DisableDebug ¶
DisableDebug disables debug mode.
func (*Client) DisableDebugContext ¶
DisableDebugContext disables debug mode with the given context.
func (*Client) DumpInfoContext ¶
DumpInfoContext retrieves metadata of a dump file with the given context.
func (*Client) DumpLoadContext ¶
DumpLoadContext loads the index from a file with the given context.
func (*Client) DumpSaveAndWait ¶ added in v0.5.0
DumpSaveAndWait saves the index and blocks until the dump has finished.
func (*Client) DumpSaveAndWaitContext ¶ added in v0.5.0
DumpSaveAndWaitContext saves the index and blocks until the dump has finished, returning the path the server actually wrote.
A large dump is executed asynchronously: the server acknowledges with "OK DUMP_STARTED <path>" and reports progress through DUMP STATUS. DumpSave returns that acknowledgement as-is; this variant polls DUMP STATUS until the operation reaches COMPLETED (returning the path) or FAILED (returning the server's message as a ServerError). A dump small enough to finish inline is acknowledged with "OK SAVED <path>" and returns without polling.
The wait is bounded by ClientConfig.DumpSaveTimeoutMs, or by ctx if its deadline is sooner. Timing out does not stop the dump — the server keeps writing, and DumpStatus still reports the outcome.
func (*Client) DumpSaveContext ¶
DumpSaveContext saves the index to a file with the given context.
func (*Client) DumpStatus ¶
func (c *Client) DumpStatus() (*DumpStatus, error)
DumpStatus retrieves the status of a dump operation.
func (*Client) DumpStatusContext ¶
func (c *Client) DumpStatusContext(ctx context.Context) (*DumpStatus, error)
DumpStatusContext retrieves the status of a dump operation with the given context.
func (*Client) DumpVerify ¶
DumpVerify verifies the integrity of a dump file.
func (*Client) DumpVerifyContext ¶
DumpVerifyContext verifies the integrity of a dump file with the given context.
func (*Client) EnableDebugContext ¶
EnableDebugContext enables debug mode with the given context.
func (*Client) Facet ¶ added in v0.2.0
func (c *Client) Facet(table, column string, opts FacetOptions) (*FacetResponse, error)
Facet aggregates distinct values of a filter column with their document counts. Optionally scoped to a search result set via opts.Query and related options. Available on MygramDB >= v1.6.
func (*Client) FacetContext ¶ added in v0.2.0
func (c *Client) FacetContext(ctx context.Context, table, column string, opts FacetOptions) (*FacetResponse, error)
FacetContext is the context-aware variant of Facet.
func (*Client) GetConfigContext ¶
GetConfigContext retrieves server configuration with the given context.
func (*Client) GetContext ¶
GetContext retrieves a document by its primary key with the given context.
func (*Client) GetReplicationStatus ¶
func (c *Client) GetReplicationStatus() (*ReplicationStatus, error)
GetReplicationStatus retrieves the replication status.
func (*Client) GetReplicationStatusContext ¶
func (c *Client) GetReplicationStatusContext(ctx context.Context) (*ReplicationStatus, error)
GetReplicationStatusContext retrieves the replication status with the given context.
func (*Client) Info ¶
func (c *Client) Info() (*ServerInfo, error)
Info retrieves server information.
func (*Client) InfoContext ¶
func (c *Client) InfoContext(ctx context.Context) (*ServerInfo, error)
InfoContext retrieves server information with the given context.
func (*Client) IsConnected ¶
IsConnected returns whether the client is currently connected.
func (*Client) Optimize ¶
Optimize optimizes the index. If table is specified, only that table's index is optimized.
func (*Client) OptimizeContext ¶
OptimizeContext optimizes the index with the given context.
func (*Client) Search ¶
func (c *Client) Search(table, query string, opts SearchOptions) (*SearchResponse, error)
Search performs a full-text search.
func (*Client) SearchContext ¶
func (c *Client) SearchContext(ctx context.Context, table, query string, opts SearchOptions) (*SearchResponse, error)
SearchContext performs a full-text search with the given context.
func (*Client) SearchRaw ¶ added in v0.3.0
func (c *Client) SearchRaw(table, rawQuery string, opts SearchRawOptions) (*SearchResponse, error)
SearchRaw searches using a pre-built boolean expression (MygramDB >= v1.8).
The expression is sent verbatim (unquoted) so the server tokenizes it and its AST parser can interpret AND / OR / NOT / parentheses, including OR groups nested under AND such as "alpha AND (beta OR gamma)". A quoted expression would be treated by a v1.8 server as a single literal phrase, so quoting is intentionally not applied. Pair this with ConvertSearchExpression to preserve OR / grouping semantics that Search's AND/NOT decomposition cannot express.
func (*Client) SearchRawContext ¶ added in v0.3.0
func (c *Client) SearchRawContext(ctx context.Context, table, rawQuery string, opts SearchRawOptions) (*SearchResponse, error)
SearchRawContext is the context-aware variant of SearchRaw.
func (*Client) SearchRawWithHighlights ¶ added in v0.3.0
func (c *Client) SearchRawWithHighlights(table, rawQuery string, opts SearchRawOptions) (*SearchResponse, error)
SearchRawWithHighlights is a SearchRaw variant that requests highlighted snippets. Any highlight options passed in opts are preserved; otherwise server defaults are used.
func (*Client) SearchRawWithHighlightsContext ¶ added in v0.3.0
func (c *Client) SearchRawWithHighlightsContext(ctx context.Context, table, rawQuery string, opts SearchRawOptions) (*SearchResponse, error)
SearchRawWithHighlightsContext is the context-aware variant of SearchRawWithHighlights.
func (*Client) SearchWithHighlights ¶ added in v0.3.0
func (c *Client) SearchWithHighlights(table, query string, opts SearchOptions) (*SearchResponse, error)
SearchWithHighlights is a Search variant that requests highlighted snippets. Any highlight options passed in opts are preserved; otherwise server defaults are used. Snippets are returned in SearchResult.Snippet. Requires MygramDB >= v1.6.
func (*Client) SearchWithHighlightsContext ¶ added in v0.3.0
func (c *Client) SearchWithHighlightsContext(ctx context.Context, table, query string, opts SearchOptions) (*SearchResponse, error)
SearchWithHighlightsContext is the context-aware variant of SearchWithHighlights.
func (*Client) SendCommand ¶
SendCommand sends a raw command to the server and returns the response.
func (*Client) SendCommandContext ¶
SendCommandContext sends a raw command to the server with the given context.
The context bounds how long the call waits: its deadline, if any, caps the I/O timeout, and a context that is already canceled or past its deadline fails fast before anything is sent. Once the request is in flight, cancellation of a deadline-less context does not interrupt it; the command still completes or hits TimeoutMs.
func (*Client) SetVariable ¶ added in v0.3.0
SetVariable sets a runtime variable (MygramDB >= v1.7, MySQL-compatible SET).
func (*Client) SetVariableContext ¶ added in v0.3.0
SetVariableContext sets a runtime variable with the given context.
func (*Client) ShowVariables ¶ added in v0.3.0
ShowVariables shows runtime variables (MygramDB >= v1.7, MySQL-compatible SHOW VARIABLES). An empty likePattern lists every variable; a non-empty pattern is matched MySQL-style (e.g. "logging%"). The raw server response is returned unparsed.
func (*Client) ShowVariablesContext ¶ added in v0.3.0
ShowVariablesContext is the context-aware variant of ShowVariables.
func (*Client) StartReplication ¶
StartReplication starts replication.
func (*Client) StartReplicationContext ¶
StartReplicationContext starts replication with the given context.
func (*Client) StopReplication ¶
StopReplication stops replication.
func (*Client) StopReplicationContext ¶
StopReplicationContext stops replication with the given context.
func (*Client) Sync ¶ added in v0.3.0
Sync starts an on-demand sync (full reload) of a table (MygramDB >= v1.7). The raw server acknowledgement is returned.
func (*Client) SyncContext ¶ added in v0.3.0
SyncContext is the context-aware variant of Sync.
func (*Client) SyncStatus ¶ added in v0.3.0
SyncStatus retrieves the status of in-flight and recent sync operations (MygramDB >= v1.7). The raw SYNC_STATUS report is returned unparsed.
func (*Client) SyncStatusContext ¶ added in v0.3.0
SyncStatusContext is the context-aware variant of SyncStatus.
type ClientConfig ¶
type ClientConfig struct {
// Host is the server hostname or IP address. Default is "127.0.0.1".
Host string
// Port is the server port number. Default is 11016.
Port int
// SocketPath is the Unix domain socket path. When specified, it takes priority over TCP.
SocketPath string
// TimeoutMs is the command timeout in milliseconds. Default is 5000.
//
// This field is milliseconds (an int) for parity with the other language
// clients. The pool-level limits (PoolConfig.ConnMaxLifetime and friends)
// are time.Duration; mind the difference when configuring both.
TimeoutMs int
// ConnectTimeoutMs bounds the dial (and the AUTH handshake that follows it)
// separately from a command. 0 falls back to TimeoutMs, which is the
// historical behavior. Raise it when the server is reachable only over a
// slow path but commands themselves must still fail fast.
ConnectTimeoutMs int
// DumpSaveTimeoutMs bounds DumpSaveAndWait: the whole poll loop, from the
// DUMP SAVE request to the terminal DUMP STATUS, must finish inside it. It
// does not apply to DumpSave, which returns the server's immediate
// acknowledgement without waiting. 0 selects the default (300000).
//
// This and the three timeouts below cover the commands that rebuild or
// traverse the whole index. They are separate from TimeoutMs because an
// ordinary request timeout would abandon a command the server is still
// executing; set one equal to TimeoutMs to opt out. A caller-supplied
// context deadline still wins when it is the shorter of the two.
DumpSaveTimeoutMs int
// DumpLoadTimeoutMs bounds a DUMP LOAD command, which restores an entire
// index. 0 selects the default (300000).
DumpLoadTimeoutMs int
// DumpVerifyTimeoutMs bounds a DUMP VERIFY command, which streams and
// checksums every section of a dump. 0 selects the default (300000).
DumpVerifyTimeoutMs int
// OptimizeTimeoutMs bounds an OPTIMIZE command, which rebuilds posting
// lists. 0 selects the default (300000).
OptimizeTimeoutMs int
// RecvBufferSize is the receive buffer size. Default is 65536.
RecvBufferSize int
// MaxQueryLength is the maximum length of a query expression. 0 means unlimited. Default is 128.
MaxQueryLength int
// MaxResponseSize is the maximum accepted response size in bytes. When a
// response exceeds it, the read is aborted with a ProtocolError and the
// connection is closed (its stream position is no longer known). 0 means
// unlimited, which is the default for backward compatibility. A bounded
// value (for example 64<<20) is recommended to guard against a runaway or
// malformed response exhausting memory.
MaxResponseSize int
// AutoReconnect transparently re-establishes a dropped connection. When
// enabled, SendCommandContext reconnects once and resends the command if
// the socket is found dead *before* the request is written. A disconnect
// that occurs *after* the request was sent is surfaced as a ConnectionError
// without resending, since the command may already have been applied
// server-side. Default is false (legacy behavior). A Pool always enables it
// on the connections it owns so a transient drop is absorbed on the slot.
AutoReconnect bool
// DisableTCPKeepAlive turns off the client's SO_KEEPALIVE idle override on
// TCP connections. The zero value keeps keep-alive enabled with the
// TCPKeepAliveIdle period, so a silently dropped peer is detected without
// waiting for the next command's read timeout. Set it to true to leave the
// dialer's built-in keep-alive default in place instead. Ignored for
// Unix-socket connections. Defaulting keep-alive on this way keeps the
// behavior identical whether a client is built with NewClient or with
// NewClientWithConfig/NewPool.
DisableTCPKeepAlive bool
// TCPKeepAliveIdle is the idle period before keep-alive probing begins.
// Applies unless DisableTCPKeepAlive is set. 0 selects the default (60s).
TCPKeepAliveIdle time.Duration
// AdminToken authenticates administrative commands on a server that sets
// api.admin_token (MygramDB >= v1.10). When non-empty, the client sends
// AUTH as soon as a connection is established — including the connections
// opened by a reconnect or by a Pool — so administrative commands are
// authorized without a per-command handshake. A rejected token surfaces as
// a ServerError from Connect. Empty (the default) sends no AUTH, which is
// correct for a server with no admin token and for search-only workloads.
AdminToken string
}
ClientConfig holds connection settings for the MygramDB server.
func DefaultConfig ¶
func DefaultConfig() ClientConfig
DefaultConfig returns the default configuration.
type ConnectionError ¶
ConnectionError is an error returned when a connection fails.
func (*ConnectionError) Error ¶
func (e *ConnectionError) Error() string
func (*ConnectionError) Unwrap ¶
func (e *ConnectionError) Unwrap() error
type CountOptions ¶
type CountOptions struct {
// AndTerms is a list of additional keywords combined with AND.
AndTerms []string
// NotTerms is a list of keywords to exclude with NOT.
NotTerms []string
// Filters is a map of column filter conditions (key=value). Entries are
// sent in sorted key order.
Filters map[string]string
// FilterConditions holds filters with an explicit comparison operator
// (MygramDB >= v1.9), appended after the Filters entries.
FilterConditions []FilterCondition
// QueryMode selects literal (default) or boolean interpretation of the
// count text.
QueryMode QueryMode
}
CountOptions holds options for a count request.
type CountResponse ¶
type CountResponse struct {
// Count is the number of matched documents.
Count int
// Debug contains debug information (only available when debug mode is enabled).
Debug *DebugInfo
}
CountResponse represents a count response.
type DebugInfo ¶
type DebugInfo struct {
QueryTimeMs float64
IndexTimeMs float64
FilterTimeMs float64
Terms int
Ngrams int
Candidates int
AfterIntersection int
AfterNot int
AfterFilters int
Final int
Optimization string
Sort string
Cache string
CacheAgeMs float64
CacheSavedMs float64
Limit int
Offset int
}
DebugInfo holds query metrics from debug mode.
type Document ¶
type Document struct {
// PrimaryKey is the document's primary key.
PrimaryKey string
// Fields is a map of filter column key-value pairs. A string-typed
// value quoted per spec/tcp-commands.md §11.1 (whitespace, a quote,
// a backslash or a control character) is decoded before it lands here.
Fields map[string]string
}
Document represents a document retrieved by GET.
type DumpStatus ¶
type DumpStatus struct {
SaveInProgress bool
LoadInProgress bool
Status string
Filepath string
TablesProcessed int
TablesTotal int
CurrentTable string
ElapsedSeconds float64
ResultFilepath string
Error string
}
DumpStatus represents the status of a dump operation.
type ErrorCode ¶ added in v0.5.0
type ErrorCode uint16
ErrorCode is the numeric code carried by a MygramDB ERROR frame.
Since MygramDB v1.10 every TCP ERROR frame is "ERROR <code> <message>", where <code> is a decimal uint16 drawn from the server's shared error-code space. Older servers send an uncoded "ERROR <message>" frame; those are reported as ErrCodeNone so a client can tell "no code" from a real code.
The constants below name the codes a client can act on. Any uint16 may appear on the wire, so treat an unrecognized value as an opaque server error rather than an unexpected condition.
const ( // ErrCodeNone means the ERROR frame carried no numeric code, which is how // a pre-v1.10 server reports every failure. ErrCodeNone ErrorCode = 0 ErrCodeUnknown ErrorCode = 1 ErrCodeInvalidArgument ErrorCode = 2 ErrCodeOutOfRange ErrorCode = 3 ErrCodeNotImplemented ErrorCode = 4 ErrCodeInternalError ErrorCode = 5 ErrCodeIOError ErrorCode = 6 // ErrCodePermissionDenied rejects an administrative command issued without // a successful AUTH, and a failed AUTH itself (MygramDB >= v1.10). ErrCodePermissionDenied ErrorCode = 7 ErrCodeNotFound ErrorCode = 8 ErrCodeAlreadyExists ErrorCode = 9 ErrCodeTimeout ErrorCode = 10 ErrCodeCancelled ErrorCode = 11 )
General codes (0-999).
const ( ErrCodeQuerySyntaxError ErrorCode = 3000 ErrCodeQueryInvalidToken ErrorCode = 3001 ErrCodeQueryUnexpectedToken ErrorCode = 3002 ErrCodeQueryMissingOperand ErrorCode = 3003 ErrCodeQueryInvalidOperator ErrorCode = 3004 ErrCodeQueryTooLong ErrorCode = 3005 ErrCodeQueryInvalidFilter ErrorCode = 3006 ErrCodeQueryInvalidSort ErrorCode = 3007 ErrCodeQueryInvalidLimit ErrorCode = 3008 ErrCodeQueryInvalidOffset ErrorCode = 3009 ErrCodeQueryExpressionParseError ErrorCode = 3010 ErrCodeQueryASTBuildError ErrorCode = 3011 )
Query codes (3000-3999).
const ( ErrCodeIndexDocumentNotFound ErrorCode = 4004 ErrCodeTableNotFound ErrorCode = 4007 ErrCodeCatalogNotInitialized ErrorCode = 4008 ErrCodeSyncTableNotFound ErrorCode = 4010 ErrCodeSyncAlreadyInProgress ErrorCode = 4011 ErrCodeSyncMemoryCritical ErrorCode = 4012 )
Index and catalog codes (4000-4999).
const ( ErrCodeNetworkInvalidRequest ErrorCode = 6007 ErrCodeNetworkProtocolError ErrorCode = 6008 // ErrCodeServerShuttingDown rejects a new long-running operation while the // server is stopping. Retrying against the same server will not help. ErrCodeServerShuttingDown ErrorCode = 6027 // ErrCodeServerLoading means the server is restoring a dump and is // temporarily unavailable. The command was not executed. ErrCodeServerLoading ErrorCode = 6028 // ErrCodeServerNotReady means the server has not finished building the // state the command needs. The command was not executed. ErrCodeServerNotReady ErrorCode = 6029 // ErrCodeServerBusy means request capacity is temporarily exhausted (for // example the rate limiter denied the request). The command was not // executed. ErrCodeServerBusy ErrorCode = 6030 )
Network and server codes (6000-6999).
const (
ErrCodeCacheDisabled ErrorCode = 8001
)
Cache codes (8000-8999).
func ServerErrorCode ¶ added in v0.5.0
ServerErrorCode reports the numeric code of a server ERROR frame. It returns (ErrCodeNone, false) for any error that is not a *ServerError, and (ErrCodeNone, true) for an uncoded frame from a pre-v1.10 server. The error chain is unwrapped, so a *ServerError still reports its code after a caller has wrapped it with fmt.Errorf and %w.
func (ErrorCode) Retryable ¶ added in v0.5.0
Retryable reports whether the code names a transient server condition that rejected the command before executing it, so re-issuing the same command (after a backoff) is both safe and worth doing. Every other code describes a deterministic failure that a retry would only repeat.
type FacetOptions ¶ added in v0.2.0
type FacetOptions struct {
// Query, when non-empty, scopes the facet aggregation to documents
// matching the given search text (same semantics as SEARCH).
Query string
// AndTerms is a list of additional keywords combined with AND.
AndTerms []string
// NotTerms is a list of keywords to exclude with NOT.
NotTerms []string
// Filters is a map of column filter conditions (key=value). Entries are
// sent in sorted key order.
Filters map[string]string
// FilterConditions holds filters with an explicit comparison operator
// (MygramDB >= v1.9), appended after the Filters entries.
FilterConditions []FilterCondition
// Limit bounds the number of returned (value, count) pairs.
// 0 means "no limit".
Limit int
// Offset is the number of distinct values to skip, so Limit and Offset
// together page through a facet (MygramDB >= v1.9). Use
// FacetResponse.TotalCount to size the pagination.
Offset int
}
FacetOptions holds options for a FACET request. Introduced in MygramDB v1.6.
type FacetResponse ¶ added in v0.2.0
type FacetResponse struct {
// Results is the list of (value, count) pairs ordered by count
// descending. With FacetOptions.Offset or Limit set, it is one page.
Results []FacetValue
// TotalCount is the number of distinct values before OFFSET and LIMIT
// (MygramDB >= v1.9). A server that predates paginated facets reports only
// the page size, so this falls back to len(Results).
TotalCount int64
}
FacetResponse is the response to a FACET command.
type FacetValue ¶ added in v0.2.0
type FacetValue struct {
// Value is the facet column's distinct value as a string.
Value string
// Count is the number of documents that have this value.
Count int64
}
FacetValue is a single aggregated (value, count) pair returned by the FACET command.
type FilterCondition ¶ added in v0.5.0
type FilterCondition struct {
// Key is the filter column name. It is sent unquoted, so it must be a
// valid identifier.
Key string
// Op is the comparison operator. The zero value is FilterEqual.
Op FilterOp
// Value is the compared value. It is quoted on the wire as needed.
Value string
}
FilterCondition is a filter with an explicit comparison operator (MygramDB >= v1.9). Use it where the Filters map cannot express the predicate; the two forms may be combined on one request.
type FilterOp ¶ added in v0.5.0
type FilterOp uint8
FilterOp is the comparison operator of a typed filter condition (MygramDB >= v1.9).
type HighlightOptions ¶ added in v0.2.0
type HighlightOptions struct {
// OpenTag is the tag inserted before each matched term. When empty
// the server default ("<em>") is used. Sent on the wire through the
// same quoting decision as a search term, so whitespace or a clause
// keyword in the tag reaches the server as the literal tag it is.
OpenTag string
// CloseTag is the tag inserted after each matched term. When empty
// the server default ("</em>") is used.
//
// OpenTag and CloseTag must be set (or unset) together.
CloseTag string
// SnippetLen is the maximum number of code points per snippet
// fragment. Valid range is 1..10000. 0 means "use server default"
// (100).
SnippetLen int
// MaxFragments is the maximum number of snippet fragments joined by
// ellipsis. Valid range is 1..100. 0 means "use server default" (3).
MaxFragments int
}
HighlightOptions configures the HIGHLIGHT clause introduced in MygramDB v1.6. A zero-value HighlightOptions requests default highlighting ("<em>"/"</em>" tags, 100 code point snippets, up to 3 fragments).
type Pool ¶ added in v0.4.0
type Pool struct {
// contains filtered or unexported fields
}
Pool is a bounded pool of MygramDB connections. It exposes the same command methods as Client; for each call it borrows a connection, runs the request, and returns the connection to the pool, transparently reconnecting and retrying where it is safe to do so. A Pool is safe for concurrent use.
The token accounting maintains the invariant that the number of open connections (idle plus in use) never exceeds MaxOpenConns: every connection holds exactly one slot in sem from the moment it is dialed until it is closed. Idle connections keep their slot while parked in the idle channel.
func NewPool ¶ added in v0.4.0
func NewPool(cfg PoolConfig) *Pool
NewPool creates a pool with the given configuration. It performs no I/O; connections are opened lazily on first use.
func (*Pool) CacheClear ¶ added in v0.4.0
CacheClear clears the cache.
func (*Pool) CacheClearContext ¶ added in v0.4.0
CacheClearContext clears the cache with the given context.
func (*Pool) CacheDisable ¶ added in v0.4.0
CacheDisable disables the cache.
func (*Pool) CacheDisableContext ¶ added in v0.4.0
CacheDisableContext disables the cache with the given context.
func (*Pool) CacheEnable ¶ added in v0.4.0
CacheEnable enables the cache.
func (*Pool) CacheEnableContext ¶ added in v0.4.0
CacheEnableContext enables the cache with the given context.
func (*Pool) CacheStats ¶ added in v0.4.0
func (p *Pool) CacheStats() (*CacheStats, error)
CacheStats retrieves cache statistics.
func (*Pool) CacheStatsContext ¶ added in v0.4.0
func (p *Pool) CacheStatsContext(ctx context.Context) (*CacheStats, error)
CacheStatsContext retrieves cache statistics with the given context.
func (*Pool) Close ¶ added in v0.4.0
Close closes the pool. Idle connections are closed immediately; connections currently in use are closed when they are returned. After Close, command methods return a ConnectionError. Close is idempotent.
func (*Pool) Count ¶ added in v0.4.0
func (p *Pool) Count(table, query string, opts CountOptions) (*CountResponse, error)
Count returns the number of matching documents.
func (*Pool) CountContext ¶ added in v0.4.0
func (p *Pool) CountContext(ctx context.Context, table, query string, opts CountOptions) (*CountResponse, error)
CountContext performs a count query with the given context.
func (*Pool) DisableDebug ¶ added in v0.4.0
DisableDebug disables debug mode.
func (*Pool) DisableDebugContext ¶ added in v0.4.0
DisableDebugContext disables debug mode with the given context.
func (*Pool) DumpInfoContext ¶ added in v0.4.0
DumpInfoContext retrieves metadata of a dump file with the given context.
func (*Pool) DumpLoadContext ¶ added in v0.4.0
DumpLoadContext loads the index from a file with the given context.
func (*Pool) DumpSaveAndWait ¶ added in v0.5.0
DumpSaveAndWait saves the index and blocks until the dump has finished.
func (*Pool) DumpSaveAndWaitContext ¶ added in v0.5.0
DumpSaveAndWaitContext saves the index and blocks until the dump has finished. The DUMP STATUS polling runs on the borrowed connection, so the slot stays checked out for the whole operation.
func (*Pool) DumpSaveContext ¶ added in v0.4.0
DumpSaveContext saves the index to a file with the given context.
func (*Pool) DumpStatus ¶ added in v0.4.0
func (p *Pool) DumpStatus() (*DumpStatus, error)
DumpStatus retrieves the status of a dump operation.
func (*Pool) DumpStatusContext ¶ added in v0.4.0
func (p *Pool) DumpStatusContext(ctx context.Context) (*DumpStatus, error)
DumpStatusContext retrieves the status of a dump operation with the given context.
func (*Pool) DumpVerify ¶ added in v0.4.0
DumpVerify verifies the integrity of a dump file.
func (*Pool) DumpVerifyContext ¶ added in v0.4.0
DumpVerifyContext verifies the integrity of a dump file with the given context.
func (*Pool) EnableDebug ¶ added in v0.4.0
EnableDebug enables debug mode.
func (*Pool) EnableDebugContext ¶ added in v0.4.0
EnableDebugContext enables debug mode with the given context.
func (*Pool) Facet ¶ added in v0.4.0
func (p *Pool) Facet(table, column string, opts FacetOptions) (*FacetResponse, error)
Facet aggregates distinct values of a filter column with their document counts.
func (*Pool) FacetContext ¶ added in v0.4.0
func (p *Pool) FacetContext(ctx context.Context, table, column string, opts FacetOptions) (*FacetResponse, error)
FacetContext is the context-aware variant of Facet.
func (*Pool) GetConfigContext ¶ added in v0.4.0
GetConfigContext retrieves server configuration with the given context.
func (*Pool) GetContext ¶ added in v0.4.0
GetContext retrieves a document by its primary key with the given context.
func (*Pool) GetReplicationStatus ¶ added in v0.4.0
func (p *Pool) GetReplicationStatus() (*ReplicationStatus, error)
GetReplicationStatus retrieves the replication status.
func (*Pool) GetReplicationStatusContext ¶ added in v0.4.0
func (p *Pool) GetReplicationStatusContext(ctx context.Context) (*ReplicationStatus, error)
GetReplicationStatusContext retrieves the replication status with the given context.
func (*Pool) Info ¶ added in v0.4.0
func (p *Pool) Info() (*ServerInfo, error)
Info retrieves server information.
func (*Pool) InfoContext ¶ added in v0.4.0
func (p *Pool) InfoContext(ctx context.Context) (*ServerInfo, error)
InfoContext retrieves server information with the given context.
func (*Pool) OptimizeContext ¶ added in v0.4.0
OptimizeContext optimizes the index with the given context.
func (*Pool) Search ¶ added in v0.4.0
func (p *Pool) Search(table, query string, opts SearchOptions) (*SearchResponse, error)
Search performs a full-text search.
func (*Pool) SearchContext ¶ added in v0.4.0
func (p *Pool) SearchContext(ctx context.Context, table, query string, opts SearchOptions) (*SearchResponse, error)
SearchContext performs a full-text search with the given context.
func (*Pool) SearchRaw ¶ added in v0.4.0
func (p *Pool) SearchRaw(table, rawQuery string, opts SearchRawOptions) (*SearchResponse, error)
SearchRaw searches using a pre-built boolean expression.
func (*Pool) SearchRawContext ¶ added in v0.4.0
func (p *Pool) SearchRawContext(ctx context.Context, table, rawQuery string, opts SearchRawOptions) (*SearchResponse, error)
SearchRawContext is the context-aware variant of SearchRaw.
func (*Pool) SearchRawWithHighlights ¶ added in v0.4.0
func (p *Pool) SearchRawWithHighlights(table, rawQuery string, opts SearchRawOptions) (*SearchResponse, error)
SearchRawWithHighlights is a SearchRaw variant that requests highlighted snippets.
func (*Pool) SearchRawWithHighlightsContext ¶ added in v0.4.0
func (p *Pool) SearchRawWithHighlightsContext(ctx context.Context, table, rawQuery string, opts SearchRawOptions) (*SearchResponse, error)
SearchRawWithHighlightsContext is the context-aware variant of SearchRawWithHighlights.
func (*Pool) SearchWithHighlights ¶ added in v0.4.0
func (p *Pool) SearchWithHighlights(table, query string, opts SearchOptions) (*SearchResponse, error)
SearchWithHighlights is a Search variant that requests highlighted snippets.
func (*Pool) SearchWithHighlightsContext ¶ added in v0.4.0
func (p *Pool) SearchWithHighlightsContext(ctx context.Context, table, query string, opts SearchOptions) (*SearchResponse, error)
SearchWithHighlightsContext is the context-aware variant of SearchWithHighlights.
func (*Pool) SendCommand ¶ added in v0.4.0
SendCommand sends a raw command to the server and returns the response.
func (*Pool) SendCommandContext ¶ added in v0.4.0
SendCommandContext sends a raw command with the given context. Raw commands are treated as state-changing and are never retried after they reach the server.
func (*Pool) SetVariable ¶ added in v0.4.0
SetVariable sets a runtime variable.
func (*Pool) SetVariableContext ¶ added in v0.4.0
SetVariableContext sets a runtime variable with the given context.
func (*Pool) ShowVariables ¶ added in v0.4.0
ShowVariables shows runtime variables.
func (*Pool) ShowVariablesContext ¶ added in v0.4.0
ShowVariablesContext is the context-aware variant of ShowVariables.
func (*Pool) StartReplication ¶ added in v0.4.0
StartReplication starts replication.
func (*Pool) StartReplicationContext ¶ added in v0.4.0
StartReplicationContext starts replication with the given context.
func (*Pool) StopReplication ¶ added in v0.4.0
StopReplication stops replication.
func (*Pool) StopReplicationContext ¶ added in v0.4.0
StopReplicationContext stops replication with the given context.
func (*Pool) SyncContext ¶ added in v0.4.0
SyncContext is the context-aware variant of Sync.
func (*Pool) SyncStatus ¶ added in v0.4.0
SyncStatus retrieves the status of in-flight and recent sync operations.
func (*Pool) SyncStatusContext ¶ added in v0.4.0
SyncStatusContext is the context-aware variant of SyncStatus.
func (*Pool) SyncStopContext ¶ added in v0.4.0
SyncStopContext is the context-aware variant of SyncStop.
func (*Pool) WithConn ¶ added in v0.4.0
WithConn borrows a single connection and runs fn against it. Use it to run a sequence of requests on one connection, or a request whose retry semantics you want to control yourself. The pool applies no retries around fn. The connection is returned to the pool afterwards, or discarded if fn reports a connection-level failure.
type PoolConfig ¶ added in v0.4.0
type PoolConfig struct {
ClientConfig
// MaxOpenConns bounds the total number of connections (idle plus in use).
// A borrow that would exceed it blocks until a connection is returned or
// the context is canceled. 0 or negative means the default (10). There is
// deliberately no "unlimited" option: an explicit cap is the point.
MaxOpenConns int
// MaxIdleConns bounds how many idle connections are retained for reuse.
// 0 or negative means "same as MaxOpenConns". Values above MaxOpenConns are
// clamped to MaxOpenConns.
MaxIdleConns int
// ConnMaxLifetime is the maximum age of a connection measured from when it
// was opened. Expired connections are discarded on borrow, and a background
// reaper also sweeps idle ones so a quiet pool does not keep them open. 0
// means no limit.
ConnMaxLifetime time.Duration
// ConnMaxIdleTime is the maximum time a connection may sit idle before it
// is discarded. It is enforced both on borrow and by the background reaper.
// 0 means no limit.
ConnMaxIdleTime time.Duration
// Retry is the retry policy for idempotent and never-sent commands. A zero
// value selects the default policy.
Retry RetryPolicy
// CircuitBreaker configures a circuit breaker around the command API. It
// sits outside the retry policy, so an open breaker fails fast without
// retrying or touching the network. A nil pointer disables it.
CircuitBreaker *CircuitBreakerConfig
// OnEvent, when set, receives observability events (see PoolEvent). It is
// called synchronously on the pool's hot path, so it must not block; a
// panic in the callback is recovered and ignored.
OnEvent func(event PoolEvent, payload map[string]any)
}
PoolConfig configures a Pool. The embedded ClientConfig is applied to every connection the pool opens. Time-based limits use time.Duration (the pool is Go-native), whereas the embedded ClientConfig keeps its millisecond fields for parity with the other language clients.
type PoolEvent ¶ added in v0.4.0
type PoolEvent string
PoolEvent identifies an observability event emitted by a Pool through PoolConfig.OnEvent. The payload map varies by event; see each constant.
const ( // EventAcquire is emitted when a connection is handed out. Payload: // {"wait_seconds": float64} — time the borrow spent waiting (0 if it did // not wait). EventAcquire PoolEvent = "acquire" // EventConnectionDiscarded is emitted when a connection is dropped after // failing validation, expiring, or overflowing the idle limit. Empty payload. EventConnectionDiscarded PoolEvent = "connection_discarded" // EventRetry is emitted before a request retry's backoff. Payload: // {"attempt": int, "error": string}. EventRetry PoolEvent = "retry" // EventBreakerStateChange is emitted when the circuit breaker changes state. // Payload: {"state": string} — one of "closed", "open", "half_open". EventBreakerStateChange PoolEvent = "breaker_state_change" )
type PoolStats ¶ added in v0.4.0
type PoolStats struct {
// Open is the number of open connections (idle plus in use).
Open int
// Idle is the number of connections currently available for reuse.
Idle int
// InUse is the number of connections currently borrowed.
InUse int
// WaitCount is the approximate number of borrows that had to wait for a
// connection. It counts entries into the waiting path, some of which may
// then complete without actually blocking, so it slightly overstates
// contention.
WaitCount int64
// WaitDuration is the cumulative time borrows spent in the waiting path.
WaitDuration time.Duration
// Discarded is the number of connections closed instead of being reused
// (unhealthy, expired, or beyond the idle limit).
Discarded int64
// Retries is the number of request retries performed.
Retries int64
}
PoolStats is a snapshot of a Pool's runtime statistics.
type PrimaryKeySort ¶ added in v0.5.0
type PrimaryKeySort uint8
PrimaryKeySort selects an explicit primary-key ordering for a search that names no sort column. The protocol's shorthand `SORT ASC` / `SORT DESC` orders by primary key; omitting the clause entirely leaves the server on its own default, which is descending.
const ( // PrimaryKeySortDefault omits the SORT clause, leaving the ordering to the // server (primary key, descending). It is the zero value, so the wire form // of an existing request is unchanged. PrimaryKeySortDefault PrimaryKeySort = iota // PrimaryKeySortAsc requests primary key ascending. This ordering is not // reachable any other way: SortDesc only chooses the direction of an // explicit SortColumn. PrimaryKeySortAsc // PrimaryKeySortDesc requests primary key descending explicitly. It selects // the same ordering as PrimaryKeySortDefault but states it on the wire. PrimaryKeySortDesc )
type ProtocolError ¶
type ProtocolError struct {
Message string
}
ProtocolError is an error returned when a protocol violation occurs.
func (*ProtocolError) Error ¶
func (e *ProtocolError) Error() string
type QueryMode ¶ added in v0.5.0
type QueryMode uint8
QueryMode selects how the search text of a SEARCH or COUNT is interpreted (MygramDB >= v1.9).
const ( // QueryLiteral treats the text as literal user input: it is quoted on the // wire, so reserved words such as AND or LIMIT stay data. This is the zero // value, so search semantics do not change unless a caller opts in. QueryLiteral QueryMode = iota // QueryBoolean sends the text verbatim so the server's AST parser reads // its AND / OR / NOT operators and parentheses. Use it to combine an // expression such as `alpha AND (beta OR gamma)` with typed filters, // sorting, fuzzy matching or highlights; SearchRaw remains the compact // expression-only entry point. QueryBoolean )
type ReplicationStatus ¶
type ReplicationStatus struct {
// Running is true when replication is active.
Running bool
// GTID is the current GTID position.
GTID string
// StatusStr is the raw response string.
StatusStr string
// ProcessedEvents is the total number of binlog events processed since
// startup. Populated only by the multi-line REPLICATION STATUS response.
ProcessedEvents int
// QueueSize is the number of events currently pending in the
// replication apply queue. Populated only by the multi-line response.
QueueSize int
// State is the reported state: "running", "stopped", "failed" or
// "not_configured" (MygramDB >= v1.10). It distinguishes a reader that
// stopped on an error from one stopped on request, which Running alone
// cannot. An unrecognized value is passed through rather than dropped, so
// a state a future server adds stays visible. Empty for the single-line
// response and for a server that omits the field.
State string
// CRCErrors counts binlog events whose checksum did not verify
// (MygramDB >= v1.10).
CRCErrors int
// SchemaIncompatible reports that replication stopped because the MySQL
// schema no longer matches the configured columns (MygramDB >= v1.10).
SchemaIncompatible bool
// LastErrorCode is the code of the last replication failure
// (MygramDB >= v1.10), drawn from the same space as ErrorCode. It is
// ErrCodeNone while no failure is recorded; the server clears it once a
// start succeeds.
LastErrorCode ErrorCode
// LastError is the message belonging to LastErrorCode
// (MygramDB >= v1.10). Empty while no failure is recorded.
LastError string
// LastAppliedUnixtime is the Unix time at which the last event was
// applied (MygramDB >= v1.10). The server stamps it where the replication
// position advances, so it tracks applied progress rather than mere
// connectivity. It is 0 while no event has been applied yet, which is the
// normal state of a server that has just started.
LastAppliedUnixtime int64
// SecondsSinceLastApplied is the replication lag derived from
// LastAppliedUnixtime (MygramDB >= v1.10) — the field to alert on.
//
// The server reports -1 while no event has been applied, so a lag
// threshold must exclude the negative sentinel rather than treat it as a
// lag of zero. Use LastAppliedUnixtime != 0 to tell "no data yet" from a
// genuinely current replica.
SecondsSinceLastApplied int64
}
ReplicationStatus represents the replication state.
type RetryPolicy ¶ added in v0.4.0
type RetryPolicy struct {
// MaxRetries is the maximum number of additional attempts after the first.
// The zero value selects the default of 1 (so up to two total attempts). A
// negative value explicitly disables retries (zero additional attempts);
// use it when a workload must never re-issue a command, even a safe one.
MaxRetries int
// BaseBackoff is the base delay for the exponential-with-full-jitter
// backoff between attempts. Default is 50ms.
BaseBackoff time.Duration
}
RetryPolicy controls how the pool retries failed commands. Only failures that are safe to retry are ever retried: a command whose write never reached the server (any command), or a read-phase failure of an idempotent command. Server errors, validation errors and timeouts are never retried.
type SearchExpression ¶
type SearchExpression struct {
// RequiredTerms contains every term that must match: those with a '+'
// prefix and every unprefixed term (implicit AND), in the order they
// appeared. An entry may itself be a parenthesized sub-expression (see
// isParenthesizedSubexpression) captured from "+(...)".
RequiredTerms []string
// ExcludedTerms contains keywords marked for exclusion with '-'.
ExcludedTerms []string
// OptionalTerms is unused; kept for source compatibility. Every
// unprefixed term is required (implicit AND) and lives in RequiredTerms.
OptionalTerms []string
// RawExpression holds AST-syntax text reconstructed from any bare OR
// chain or parenthesized group not immediately preceded by '+'/'-',
// with the shared wire-quoting decision already applied to each of its
// terms.
RawExpression string
}
SearchExpression represents a parsed search expression.
func ParseSearchExpression ¶
func ParseSearchExpression(expression string) (*SearchExpression, error)
ParseSearchExpression parses a web-search-style search expression.
Supported syntax:
- +term: required keyword
- -term: excluded keyword
- "phrase": phrase search
- OR (case-insensitive, as a whole word): logical OR
- (expr): grouping
type SearchOptions ¶
type SearchOptions struct {
// Limit is the maximum number of results to return. Default is 1000.
Limit int
// Offset is the number of results to skip. Default is 0.
Offset int
// AndTerms is a list of additional keywords combined with AND.
AndTerms []string
// NotTerms is a list of keywords to exclude with NOT.
NotTerms []string
// Filters is a map of column filter conditions (key=value). Entries are
// sent in sorted key order so one set of options always produces the same
// command.
Filters map[string]string
// FilterConditions holds filters with an explicit comparison operator
// (MygramDB >= v1.9). They are appended after the Filters entries, in
// order.
FilterConditions []FilterCondition
// QueryMode selects literal (default) or boolean interpretation of the
// search text. Requires MygramDB >= v1.9 for a boolean query combined with
// filters, sorting, fuzzy matching or highlights.
QueryMode QueryMode
// SortColumn is the column name to sort by.
//
// Use the special value "_score" to sort by BM25 relevance score
// (requires verify_text=ascii|all on the server, MygramDB >= v1.6).
SortColumn string
// SortDesc indicates descending sort order when true. It applies to
// SortColumn; with no sort column, use SortPrimaryKey instead.
SortDesc bool
// SortPrimaryKey orders by primary key without naming a column. It is only
// meaningful when SortColumn is empty — setting both is rejected, since the
// protocol carries a single SORT clause. The zero value omits the clause,
// which leaves the server on its default primary-key descending order.
SortPrimaryKey PrimaryKeySort
// Fuzzy enables fuzzy (Levenshtein) matching with the given edit
// distance. Valid values are 0 (disabled), 1 and 2. Requires
// MygramDB >= v1.6.
Fuzzy int
// Highlight, when non-nil, enables the HIGHLIGHT clause so that
// matching snippets are returned alongside each primary key.
// Requires verify_text=ascii|all on the server and MygramDB >= v1.6.
Highlight *HighlightOptions
}
SearchOptions holds options for a search request.
type SearchRawOptions ¶ added in v0.3.0
type SearchRawOptions struct {
// Limit is the maximum number of results to return. 0 means the server
// default.
Limit int
// Offset is the number of results to skip. Default is 0.
Offset int
// Highlight, when non-nil, enables the HIGHLIGHT clause so that matching
// snippets are returned alongside each primary key.
Highlight *HighlightOptions
}
SearchRawOptions holds options for a raw search request that sends a pre-built boolean expression. Introduced in MygramDB v1.7; since v1.8 the expression is sent verbatim (unquoted) so the server's AST parser interprets AND/OR/NOT and grouping (see Client.SearchRaw). Unlike SearchOptions, a raw search exposes only pagination and highlight controls — AND/NOT/FILTER refinements belong inside the expression itself.
type SearchResponse ¶
type SearchResponse struct {
// Results is the list of search results.
Results []SearchResult
// TotalCount is the total number of matches after filtering.
TotalCount int
// Debug contains debug information (only available when debug mode is enabled).
Debug *DebugInfo
}
SearchResponse represents a search response.
type SearchResult ¶
type SearchResult struct {
// PrimaryKey is the document's primary key.
PrimaryKey string
// Snippet contains the highlighted text fragment for this result,
// populated only when SearchOptions.Highlight was set (MygramDB
// >= v1.6). Empty otherwise.
Snippet string
}
SearchResult represents a single search result.
type ServerError ¶
type ServerError struct {
// Message is the human-readable part of the frame, with the numeric code
// prefix removed.
Message string
// Code is the numeric error code carried by the frame (MygramDB >= v1.10).
// It is ErrCodeNone for an uncoded frame from an older server.
Code ErrorCode
}
ServerError is an error returned when the server responds with ERROR.
func (*ServerError) Error ¶
func (e *ServerError) Error() string
func (*ServerError) Retryable ¶ added in v0.5.0
func (e *ServerError) Retryable() bool
Retryable reports whether the server rejected the command with a transient condition that did not execute it, so a retry after a backoff is safe. It is always false for an uncoded frame, whose message is not a reliable signal.
type ServerInfo ¶
type ServerInfo struct {
// Version is the server version.
Version string
// UptimeSeconds is the number of seconds since server startup.
UptimeSeconds int
// TotalRequests is the total number of processed requests.
TotalRequests int
// ActiveConnections is the current number of client connections.
ActiveConnections int
// IndexSizeBytes is the memory used by the index in bytes.
IndexSizeBytes int
// DocCount is the total number of documents in the index.
DocCount int
// Tables is the list of table names.
Tables []string
// DataInitialized reports whether the server has finished building its
// initial index state (MygramDB >= v1.10). It is false on older servers,
// which do not report the field.
DataInitialized bool
// Readiness is the server's readiness verdict, "ready" or "not_ready"
// (MygramDB >= v1.10), evaluated from the same inputs as the HTTP
// readiness endpoint. It is empty on older servers.
Readiness string
}
ServerInfo represents server information.
func (*ServerInfo) Ready ¶ added in v0.5.0
func (i *ServerInfo) Ready() bool
Ready reports whether the server declared itself ready to serve requests. It is false on a server that predates the readiness field, so use it to gate traffic only when the deployment is known to run MygramDB >= v1.10.
type SimplifiedExpression ¶
type SimplifiedExpression struct {
// MainTerm is the main search keyword.
MainTerm string
// AndTerms is a list of additional keywords combined with AND.
AndTerms []string
// NotTerms is a list of keywords to exclude with NOT.
NotTerms []string
}
SimplifiedExpression represents a simplified search expression.
func SimplifySearchExpression ¶
func SimplifySearchExpression(expression string) (*SimplifiedExpression, error)
SimplifySearchExpression decomposes a search expression into MainTerm/AndTerms/NotTerms. The result maps directly to the MygramDB SEARCH command's AND/NOT term list.
An expression containing OR or grouping is refused: the legacy MainTerm/AndTerms/NotTerms shape has no way to represent it, and every consumer of those fields re-applies wire quoting to each one, which would wrap an already-formatted "(a OR b)" as one opaque literal-phrase term instead of parsing it as boolean OR. Use ConvertSearchExpression with Client.SearchRaw for an expression containing OR or grouping.
type TimeoutError ¶
type TimeoutError struct {
Message string
// Err is the underlying cause, if any (for example context.DeadlineExceeded
// when the caller's context deadline elapsed). It is nil for a timeout
// driven purely by the configured TimeoutMs.
Err error
// contains filtered or unexported fields
}
TimeoutError is an error returned when an operation times out.
It satisfies net.Error (Timeout reports true), so existing code that checks for timeouts via net.Error keeps working. When the timeout was caused by the caller's context deadline, Err is context.DeadlineExceeded and is exposed via Unwrap, so errors.Is(err, context.DeadlineExceeded) matches.
func (*TimeoutError) Error ¶
func (e *TimeoutError) Error() string
func (*TimeoutError) Temporary ¶ added in v0.4.0
func (e *TimeoutError) Temporary() bool
Temporary satisfies net.Error. A command timeout is not treated as a transient condition (matching os.ErrDeadlineExceeded), so it returns false.
func (*TimeoutError) Timeout ¶ added in v0.4.0
func (e *TimeoutError) Timeout() bool
Timeout reports that this error represents a timeout, satisfying net.Error.
func (*TimeoutError) Unwrap ¶ added in v0.4.0
func (e *TimeoutError) Unwrap() error
type ValidationError ¶
type ValidationError struct {
Message string
}
ValidationError is an error returned when input validation fails.
func (*ValidationError) Error ¶
func (e *ValidationError) Error() string