mygram

package module
v0.8.0 Latest Latest
Warning

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

Go to latest
Published: Nov 30, 2026 License: MIT Imports: 12 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

go-mygram-client

CI Go Reference codecov License Go golangci-lint Zero Dependencies

Go client library for MygramDB — a high-performance in-memory full-text search engine with MySQL replication support.

Server compatibility: MygramDB 1.6 or later, with the protocol implemented through 1.14.0. A server rejects options it predates, and an older server's ERROR frames carry no numeric code; the API reference marks each option that needs a newer server.

A search call passing from the application through the client's validation and wire-quoting steps to the MygramDB server over TCP, with the response decoded on the way back and MySQL feeding the server through binlog replication.

Overview

MygramDB answers full-text queries from memory instead of an on-disk MySQL FULLTEXT index. How much that gains depends on the query and the dataset; the published benchmarks give the numbers together with the conditions they were measured under. This client communicates via MygramDB's TCP text protocol (memcached-style) with zero external dependencies.

MySQL FULLTEXT MygramDB
Search Speed Baseline Measured
Storage On-disk In-memory
Replication — MySQL binlog
Protocol MySQL TCP (memcached-style)
Features
  • Zero Dependencies — Standard library only
  • Context Support — All methods have context.Context variants
  • Search Expression Parser — Web-style search syntax (+required, -excluded, "phrase", OR, grouping)
  • Full Protocol Support — All MygramDB commands (SEARCH, COUNT, GET, INFO, etc.)
  • Input Validation — Built-in protection against control character and protocol-delimiter injection
  • Typed Errors — Server ERROR frames carry a numeric ErrorCode; transient codes drive pool retries
  • Thread Safe — Safe for concurrent use
  • Connection Pooling — Bounded Pool with reconnection and retry for high-throughput workloads
  • Resilience — Pool circuit breaker, observability events, TCP keep-alive, and client-level auto-reconnect
  • IPv4 and IPv6 — Connects to IPv6 literals ("[::1]:11016") and to hostnames that resolve only to an AAAA record

Installation

go get github.com/libraz/go-mygram-client

Quick Start

package main

import (
	"fmt"
	"log"

	mygram "github.com/libraz/go-mygram-client"
)

func main() {
	client := mygram.NewClient("localhost:11016")
	defer client.Close()

	if err := client.Connect(); err != nil {
		log.Fatal(err)
	}

	// Search
	resp, err := client.Search("articles", "hello", mygram.SearchOptions{
		Limit:      100,
		SortColumn: "created_at",
		SortDesc:   true,
	})
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("Found %d results\n", resp.TotalCount)

	// Count
	count, err := client.Count("articles", "technology", mygram.CountOptions{})
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("Count: %d\n", count.Count)

	// Get document by ID
	doc, err := client.Get("articles", "12345")
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("Doc: %s %v\n", doc.PrimaryKey, doc.Fields)
}

Connection Pooling

A single Client wraps one connection and serializes commands, so it handles one request at a time. For concurrent workloads use a Pool, which lends out many connections up to a fixed cap and adds transparent reconnection and retry. It exposes the same command methods as Client, so it is a drop-in replacement.

pool := mygram.NewPool(mygram.PoolConfig{
	ClientConfig:    mygram.ClientConfig{Host: "localhost", Port: 11016},
	MaxOpenConns:    16,               // hard cap on total connections
	MaxIdleConns:    8,                // connections kept for reuse
	ConnMaxLifetime: 30 * time.Minute, // recycle old connections
})
defer pool.Close()

// Safe to call from many goroutines; each call borrows a connection.
resp, err := pool.Search("articles", "hello", mygram.SearchOptions{Limit: 100})

When every connection is busy, a call blocks until one is returned or its context is canceled — a natural backpressure signal. See Connection Pooling for sizing, retry semantics, and monitoring.

Search Expressions

ConvertSearchExpression turns web-style input into a server boolean query: unprefixed terms and + terms are joined with AND, - terms become AND NOT, and an OR chain stays in parentheses.

Search sends its query as literal text, so a boolean expression goes through SearchRaw, or through Search with QueryMode: mygram.QueryBoolean when it also needs filters, sorting, fuzzy matching or highlighting:

raw, err := mygram.ConvertSearchExpression(`golang "machine learning" -php +(tutorial OR guide)`)
// raw == `golang AND "machine learning" AND (tutorial OR guide) AND NOT php`

resp, err := client.SearchRaw("articles", raw, mygram.SearchRawOptions{Limit: 50})

resp, err = client.Search("articles", raw, mygram.SearchOptions{
	QueryMode:  mygram.QueryBoolean,
	SortColumn: "created_at",
	SortDesc:   true,
	Highlight:  &mygram.HighlightOptions{},
})

In the default literal mode, plain user text keeps matching as a phrase. For input without OR or grouping, SimplifySearchExpression splits it into a main term plus AND/NOT terms for Search; it returns an error on OR or grouping, so check with HasComplexExpression first when the input may contain either:

parsed, err := mygram.ParseSearchExpression(userInput)
if err != nil {
	return err
}
if mygram.HasComplexExpression(parsed) {
	raw, _ := mygram.ConvertSearchExpression(userInput)
	resp, err = client.SearchRaw("articles", raw, mygram.SearchRawOptions{})
} else {
	expr, _ := mygram.SimplifySearchExpression(userInput)
	resp, err = client.Search("articles", expr.MainTerm, mygram.SearchOptions{
		AndTerms: expr.AndTerms,
		NotTerms: expr.NotTerms,
		Limit:    100,
		Filters:  map[string]string{"status": "published", "lang": "en"},
	})
}

Search Features

BM25 Relevance Scoring

Sort by relevance using the special _score sort column (requires verify_text: ascii|all on the server):

resp, _ := client.Search("articles", "machine learning", mygram.SearchOptions{
	SortColumn: "_score",
	SortDesc:   true,
	Limit:      10,
})
Fuzzy Search (Levenshtein)
resp, _ := client.Search("articles", "machne", mygram.SearchOptions{
	Fuzzy: 1, // match within 1 edit (or 2)
	Limit: 10,
})
Highlighting
resp, _ := client.Search("articles", "golang", mygram.SearchOptions{
	Highlight: &mygram.HighlightOptions{
		OpenTag:      "<strong>",
		CloseTag:     "</strong>",
		SnippetLen:   200,
		MaxFragments: 3,
	},
	SortColumn: "_score",
	SortDesc:   true,
})
for _, r := range resp.Results {
	fmt.Println(r.PrimaryKey, r.Snippet)
}

A zero-value &mygram.HighlightOptions{} enables highlighting with server defaults (<em>/</em>, 100 code points, up to 3 fragments).

Comparison Filters

Filters expresses equality only. FilterConditions adds the comparison operators, and both forms may be combined on one request:

resp, _ := client.Search("articles", "golang", mygram.SearchOptions{
	Filters: map[string]string{"status": "1"},
	FilterConditions: []mygram.FilterCondition{
		{Key: "views", Op: mygram.FilterGreaterThanOrEqual, Value: "100"},
		{Key: "created_at", Op: mygram.FilterLessThan, Value: "2026-01-01"},
	},
})
Facets

Aggregate distinct filter-column values with document counts, optionally scoped to a search result set, and page through them with Limit/Offset:

// Top categories among documents matching "machine learning":
resp, _ := client.Facet("articles", "category", mygram.FacetOptions{
	Query:   "machine learning",
	Filters: map[string]string{"status": "1"},
	Limit:   10,
})
for _, v := range resp.Results {
	fmt.Printf("%s: %d\n", v.Value, v.Count)
}

page, _ := client.Facet("articles", "category", mygram.FacetOptions{Limit: 20, Offset: 40})
fmt.Printf("%d of %d categories\n", len(page.Results), page.TotalCount)
Multi-database Tables

A server can index tables from more than one database. Reference a table as database.table; bare names work on single-database servers.

resp, _ := client.Search("app_db.articles", "hello", mygram.SearchOptions{Limit: 10})

id, _ := mygram.QualifyTableIdentity("articles", "app_db")  // "app_db.articles"
db, tbl, _ := mygram.ParseTableIdentity("app_db.articles")  // "app_db", "articles"

Wire Quoting

Search terms, filter values, AND/NOT terms, highlight tags and primary keys all go through one quoting decision: a value is quoted when it is empty, a clause keyword (matched case-insensitively), or contains ASCII or Unicode whitespace, a control character, a quote, a backslash, or a parenthesis. Callers always pass raw, unquoted text; a highlight tag that needs quoting is quoted rather than rejected. See Search Expressions for the exact rule.

// The full-width space stays inside one term.
resp, _ := client.Search("articles", "機械学習 チュートリアル", mygram.SearchOptions{})

// A filter value equal to a reserved keyword still matches literally.
resp, _ = client.Search("articles", "q", mygram.SearchOptions{
	Filters: map[string]string{"status": "AND"},
})

Quoted primary keys and GET string values are decoded on the way back, so a SEARCH or GET result whose primary key or a string field contains a space round-trips intact.

Authentication and Error Codes

Administrative Authentication

The server gates administrative commands (DUMP, SYNC, REPLICATION, CONFIG, CACHE, OPTIMIZE, DEBUG, SET, SHOW VARIABLES) behind AUTH. Set ClientConfig.AdminToken and the client sends AUTH on every connection, including the ones opened by an auto-reconnect and by a Pool:

pool := mygram.NewPool(mygram.PoolConfig{
	ClientConfig: mygram.ClientConfig{
		Host:       "localhost",
		Port:       11016,
		AdminToken: os.Getenv("MYGRAM_ADMIN_TOKEN"),
	},
})

A rejected token fails Connect with ErrCodePermissionDenied, so a misconfigured token surfaces at startup. Ordinary search traffic needs no token.

Typed Error Codes

Every ERROR frame carries a numeric code, exposed as ServerError.Code. The pool retries the transient codes (ErrCodeServerLoading, ErrCodeServerNotReady, ErrCodeServerBusy); others are returned as is:

if _, err := client.Search("ghosts", "x", mygram.SearchOptions{}); err != nil {
	if code, ok := mygram.ServerErrorCode(err); ok && code == mygram.ErrCodeTableNotFound {
		// the table is not in the server's catalog
	}
}
Readiness
info, _ := client.Info()
if !info.Ready() {
	// the server is up but not yet serving queries
}

Server Administration

Replication Lag and Operation Deadlines

GetReplicationStatus reports SecondsSinceLastApplied, stamped where the replication position advances, so it measures progress rather than connectivity; the server reports -1 until the first event is applied. It is an administrative command, so a server with a token configured needs AdminToken to answer it. DUMP LOAD, DUMP VERIFY and OPTIMIZE use their own budgets (DumpLoadTimeoutMs, DumpVerifyTimeoutMs, OptimizeTimeoutMs), leaving TimeoutMs short enough to detect a stalled query:

status, err := client.GetReplicationStatus()
if err == nil && status.SecondsSinceLastApplied > 60 {
	log.Printf("replication is %ds behind: %s", status.SecondsSinceLastApplied, status.LastError)
}
Runtime Variables and On-demand Sync
_ = client.SetVariable("logging.level", "info")
out, _ := client.ShowVariables("logging%")

_, _ = client.Sync("app_db.articles")
syncStatus, _ := client.SyncStatus()
_, _ = client.SyncStop("app_db.articles")

Documentation

Package-level API docs are on pkg.go.dev.

Development

make test       # Run unit tests
make test-race  # Run unit tests with race detector
make test-e2e   # Run e2e tests against a live MygramDB server
make test-e2e-docker # Spin up MySQL + MygramDB (docker compose), run e2e, tear down
make lint       # Run golangci-lint
make fmt        # Format code
make coverage   # Generate coverage report
End-to-end tests

make test-e2e exercises every public method against a running MygramDB instance. Tests are gated by the e2e build tag, so the default go test ./... (and CI) never connect to a server. The suite changes server state, so MYGRAM_PORT has no default and a run without it fails.

# Name the server under test (MYGRAM_HOST defaults to 127.0.0.1)
MYGRAM_PORT=11016 make test-e2e
MYGRAM_HOST=db.example.com MYGRAM_PORT=11016 make test-e2e

# Authenticate administrative commands (required by a server that
# binds to a non-loopback address)
MYGRAM_PORT=11016 MYGRAM_ADMIN_TOKEN=... make test-e2e

# Skip side-effect heavy suites
MYGRAM_PORT=11016 MYGRAM_E2E_SKIP_DUMP=1 MYGRAM_E2E_SKIP_REPLICATION=1 make test-e2e

If the server is unreachable, every e2e test is skipped (not failed). Suites that mutate global server state (replication start/stop, cache toggle, dump round-trip) restore the original state on exit.

Self-contained docker-compose stack

make test-e2e-docker brings up a throwaway MySQL + MygramDB stack (the server is pulled from ghcr.io/libraz/mygram-db), seeds it with a deterministic dataset, runs the e2e suite with MYGRAM_E2E_SEEDED=1, then tears everything down. No local server is required. See e2e/docker/ for knobs (MYGRAMDB_VERSION, MYGRAM_ADMIN_TOKEN, KEEP_UP, ports). The TestE2ESeeded block asserts exact result sets (database-qualified identity, phrase + required-filter visibility, Japanese ngram matching, SearchRaw OR, facet counts and pagination, comparison filters, boolean query mode).

License

MIT

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

Constants

This section is empty.

Variables

This section is empty.

Functions

func ConvertSearchExpression

func ConvertSearchExpression(expression string) (string, error)

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 flagged as a group (from "+(...)" or "-(...)").

func ParseTableIdentity added in v0.3.0

func ParseTableIdentity(identity string) (database, table string, err error)

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

func QualifyTableIdentity(table, database string) (string, error)

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

func NewClient(addr string) *Client

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

func (c *Client) Authenticate(token string) error

Authenticate authorizes the connection for administrative commands (MygramDB >= v1.10).

func (*Client) AuthenticateContext added in v0.5.0

func (c *Client) AuthenticateContext(ctx context.Context, token string) error

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

func (c *Client) CacheClear(table string) error

CacheClear clears the cache. If table is specified, only that table's cache is cleared.

func (*Client) CacheClearContext

func (c *Client) CacheClearContext(ctx context.Context, table string) error

CacheClearContext clears the cache with the given context.

func (*Client) CacheDisable

func (c *Client) CacheDisable() error

CacheDisable disables the cache.

func (*Client) CacheDisableContext

func (c *Client) CacheDisableContext(ctx context.Context) error

CacheDisableContext disables the cache with the given context.

func (*Client) CacheEnable

func (c *Client) CacheEnable() error

CacheEnable enables the cache.

func (*Client) CacheEnableContext

func (c *Client) CacheEnableContext(ctx context.Context) error

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) Close

func (c *Client) Close() error

Close closes the connection.

func (*Client) Connect

func (c *Client) Connect() error

Connect establishes a connection to the server.

func (*Client) ConnectContext

func (c *Client) ConnectContext(ctx context.Context) error

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

func (c *Client) DisableDebug() error

DisableDebug disables debug mode.

func (*Client) DisableDebugContext

func (c *Client) DisableDebugContext(ctx context.Context) error

DisableDebugContext disables debug mode with the given context.

func (*Client) DumpInfo

func (c *Client) DumpInfo(filepath string) (string, error)

DumpInfo retrieves metadata of a dump file.

func (*Client) DumpInfoContext

func (c *Client) DumpInfoContext(ctx context.Context, filepath string) (string, error)

DumpInfoContext retrieves metadata of a dump file with the given context.

func (*Client) DumpLoad

func (c *Client) DumpLoad(filepath string) error

DumpLoad loads the index from a file.

func (*Client) DumpLoadContext

func (c *Client) DumpLoadContext(ctx context.Context, filepath string) error

DumpLoadContext loads the index from a file with the given context.

func (*Client) DumpSave

func (c *Client) DumpSave(filepath string) (string, error)

DumpSave saves the index to a file.

func (*Client) DumpSaveAndWait added in v0.5.0

func (c *Client) DumpSaveAndWait(filepath string) (string, error)

DumpSaveAndWait saves the index and blocks until the dump has finished.

func (*Client) DumpSaveAndWaitContext added in v0.5.0

func (c *Client) DumpSaveAndWaitContext(ctx context.Context, filepath string) (string, error)

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

func (c *Client) DumpSaveContext(ctx context.Context, filepath string) (string, error)

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

func (c *Client) DumpVerify(filepath string) (string, error)

DumpVerify verifies the integrity of a dump file.

func (*Client) DumpVerifyContext

func (c *Client) DumpVerifyContext(ctx context.Context, filepath string) (string, error)

DumpVerifyContext verifies the integrity of a dump file with the given context.

func (*Client) EnableDebug

func (c *Client) EnableDebug() error

EnableDebug enables debug mode.

func (*Client) EnableDebugContext

func (c *Client) EnableDebugContext(ctx context.Context) error

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) Get

func (c *Client) Get(table, primaryKey string) (*Document, error)

Get retrieves a document by its primary key.

func (*Client) GetConfig

func (c *Client) GetConfig() (string, error)

GetConfig retrieves server configuration in YAML format.

func (*Client) GetConfigContext

func (c *Client) GetConfigContext(ctx context.Context) (string, error)

GetConfigContext retrieves server configuration with the given context.

func (*Client) GetContext

func (c *Client) GetContext(ctx context.Context, table, primaryKey string) (*Document, error)

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

func (c *Client) IsConnected() bool

IsConnected returns whether the client is currently connected.

func (*Client) Optimize

func (c *Client) Optimize(table string) error

Optimize optimizes the index. If table is specified, only that table's index is optimized.

func (*Client) OptimizeContext

func (c *Client) OptimizeContext(ctx context.Context, table string) error

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

func (c *Client) SendCommand(command string) (string, error)

SendCommand sends a raw command to the server and returns the response. OPTIMIZE, DUMP LOAD and DUMP VERIFY use their long-operation timeouts.

func (*Client) SendCommandContext

func (c *Client) SendCommandContext(ctx context.Context, command string) (string, error)

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

func (c *Client) SetVariable(name, value string) error

SetVariable sets a runtime variable (MygramDB >= v1.7, MySQL-compatible SET).

func (*Client) SetVariableContext added in v0.3.0

func (c *Client) SetVariableContext(ctx context.Context, name, value string) error

SetVariableContext sets a runtime variable with the given context.

func (*Client) ShowVariables added in v0.3.0

func (c *Client) ShowVariables(likePattern string) (string, error)

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

func (c *Client) ShowVariablesContext(ctx context.Context, likePattern string) (string, error)

ShowVariablesContext is the context-aware variant of ShowVariables.

func (*Client) StartReplication

func (c *Client) StartReplication() error

StartReplication starts replication.

func (*Client) StartReplicationContext

func (c *Client) StartReplicationContext(ctx context.Context) error

StartReplicationContext starts replication with the given context.

func (*Client) StopReplication

func (c *Client) StopReplication() error

StopReplication stops replication.

func (*Client) StopReplicationContext

func (c *Client) StopReplicationContext(ctx context.Context) error

StopReplicationContext stops replication with the given context.

func (*Client) Sync added in v0.3.0

func (c *Client) Sync(table string) (string, error)

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

func (c *Client) SyncContext(ctx context.Context, table string) (string, error)

SyncContext is the context-aware variant of Sync.

func (*Client) SyncStatus added in v0.3.0

func (c *Client) SyncStatus() (string, error)

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

func (c *Client) SyncStatusContext(ctx context.Context) (string, error)

SyncStatusContext is the context-aware variant of SyncStatus.

func (*Client) SyncStop added in v0.3.0

func (c *Client) SyncStop(table string) (string, error)

SyncStop stops a running sync (MygramDB >= v1.7). With an empty table, every in-flight sync is stopped; with a table, only that table's sync is stopped.

func (*Client) SyncStopContext added in v0.3.0

func (c *Client) SyncStopContext(ctx context.Context, table string) (string, error)

SyncStopContext is the context-aware variant of SyncStop.

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

type ConnectionError struct {
	Message string
	Err     error
	// contains filtered or unexported fields
}

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, or QueryMatchAll to count without text (MygramDB >= v1.14).
	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

func ServerErrorCode(err error) (ErrorCode, bool)

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

func (c ErrorCode) Retryable() bool

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. It
	// must be empty for FilterIsNull and FilterIsNotNull.
	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).

const (
	// FilterEqual is the zero value, so a FilterCondition without an explicit
	// operator behaves like the equality entries of the Filters map.
	FilterEqual FilterOp = iota
	FilterNotEqual
	FilterGreaterThan
	FilterGreaterThanOrEqual
	FilterLessThan
	FilterLessThanOrEqual

	// FilterIsNull matches a row with no stored value for the column, which
	// includes a value the server could not convert to the filter's type at
	// ingest (MygramDB >= v1.14). It takes no Value.
	FilterIsNull

	// FilterIsNotNull matches a row with a stored value for the column
	// (MygramDB >= v1.14). It takes no Value.
	FilterIsNotNull
)

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

func (p *Pool) CacheClear(table string) error

CacheClear clears the cache.

func (*Pool) CacheClearContext added in v0.4.0

func (p *Pool) CacheClearContext(ctx context.Context, table string) error

CacheClearContext clears the cache with the given context.

func (*Pool) CacheDisable added in v0.4.0

func (p *Pool) CacheDisable() error

CacheDisable disables the cache.

func (*Pool) CacheDisableContext added in v0.4.0

func (p *Pool) CacheDisableContext(ctx context.Context) error

CacheDisableContext disables the cache with the given context.

func (*Pool) CacheEnable added in v0.4.0

func (p *Pool) CacheEnable() error

CacheEnable enables the cache.

func (*Pool) CacheEnableContext added in v0.4.0

func (p *Pool) CacheEnableContext(ctx context.Context) error

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

func (p *Pool) Close() error

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

func (p *Pool) DisableDebug() error

DisableDebug disables debug mode.

func (*Pool) DisableDebugContext added in v0.4.0

func (p *Pool) DisableDebugContext(ctx context.Context) error

DisableDebugContext disables debug mode with the given context.

func (*Pool) DumpInfo added in v0.4.0

func (p *Pool) DumpInfo(filepath string) (string, error)

DumpInfo retrieves metadata of a dump file.

func (*Pool) DumpInfoContext added in v0.4.0

func (p *Pool) DumpInfoContext(ctx context.Context, filepath string) (string, error)

DumpInfoContext retrieves metadata of a dump file with the given context.

func (*Pool) DumpLoad added in v0.4.0

func (p *Pool) DumpLoad(filepath string) error

DumpLoad loads the index from a file.

func (*Pool) DumpLoadContext added in v0.4.0

func (p *Pool) DumpLoadContext(ctx context.Context, filepath string) error

DumpLoadContext loads the index from a file with the given context.

func (*Pool) DumpSave added in v0.4.0

func (p *Pool) DumpSave(filepath string) (string, error)

DumpSave saves the index to a file.

func (*Pool) DumpSaveAndWait added in v0.5.0

func (p *Pool) DumpSaveAndWait(filepath string) (string, error)

DumpSaveAndWait saves the index and blocks until the dump has finished.

func (*Pool) DumpSaveAndWaitContext added in v0.5.0

func (p *Pool) DumpSaveAndWaitContext(ctx context.Context, filepath string) (string, error)

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

func (p *Pool) DumpSaveContext(ctx context.Context, filepath string) (string, error)

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

func (p *Pool) DumpVerify(filepath string) (string, error)

DumpVerify verifies the integrity of a dump file.

func (*Pool) DumpVerifyContext added in v0.4.0

func (p *Pool) DumpVerifyContext(ctx context.Context, filepath string) (string, error)

DumpVerifyContext verifies the integrity of a dump file with the given context.

func (*Pool) EnableDebug added in v0.4.0

func (p *Pool) EnableDebug() error

EnableDebug enables debug mode.

func (*Pool) EnableDebugContext added in v0.4.0

func (p *Pool) EnableDebugContext(ctx context.Context) error

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) Get added in v0.4.0

func (p *Pool) Get(table, primaryKey string) (*Document, error)

Get retrieves a document by its primary key.

func (*Pool) GetConfig added in v0.4.0

func (p *Pool) GetConfig() (string, error)

GetConfig retrieves server configuration in YAML format.

func (*Pool) GetConfigContext added in v0.4.0

func (p *Pool) GetConfigContext(ctx context.Context) (string, error)

GetConfigContext retrieves server configuration with the given context.

func (*Pool) GetContext added in v0.4.0

func (p *Pool) GetContext(ctx context.Context, table, primaryKey string) (*Document, error)

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) Optimize added in v0.4.0

func (p *Pool) Optimize(table string) error

Optimize optimizes the index.

func (*Pool) OptimizeContext added in v0.4.0

func (p *Pool) OptimizeContext(ctx context.Context, table string) error

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

func (p *Pool) SendCommand(command string) (string, error)

SendCommand sends a raw command to the server and returns the response.

func (*Pool) SendCommandContext added in v0.4.0

func (p *Pool) SendCommandContext(ctx context.Context, command string) (string, error)

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

func (p *Pool) SetVariable(name, value string) error

SetVariable sets a runtime variable.

func (*Pool) SetVariableContext added in v0.4.0

func (p *Pool) SetVariableContext(ctx context.Context, name, value string) error

SetVariableContext sets a runtime variable with the given context.

func (*Pool) ShowVariables added in v0.4.0

func (p *Pool) ShowVariables(likePattern string) (string, error)

ShowVariables shows runtime variables.

func (*Pool) ShowVariablesContext added in v0.4.0

func (p *Pool) ShowVariablesContext(ctx context.Context, likePattern string) (string, error)

ShowVariablesContext is the context-aware variant of ShowVariables.

func (*Pool) StartReplication added in v0.4.0

func (p *Pool) StartReplication() error

StartReplication starts replication.

func (*Pool) StartReplicationContext added in v0.4.0

func (p *Pool) StartReplicationContext(ctx context.Context) error

StartReplicationContext starts replication with the given context.

func (*Pool) Stats added in v0.4.0

func (p *Pool) Stats() PoolStats

Stats returns a snapshot of the pool's current statistics.

func (*Pool) StopReplication added in v0.4.0

func (p *Pool) StopReplication() error

StopReplication stops replication.

func (*Pool) StopReplicationContext added in v0.4.0

func (p *Pool) StopReplicationContext(ctx context.Context) error

StopReplicationContext stops replication with the given context.

func (*Pool) Sync added in v0.4.0

func (p *Pool) Sync(table string) (string, error)

Sync starts an on-demand sync (full reload) of a table.

func (*Pool) SyncContext added in v0.4.0

func (p *Pool) SyncContext(ctx context.Context, table string) (string, error)

SyncContext is the context-aware variant of Sync.

func (*Pool) SyncStatus added in v0.4.0

func (p *Pool) SyncStatus() (string, error)

SyncStatus retrieves the status of in-flight and recent sync operations.

func (*Pool) SyncStatusContext added in v0.4.0

func (p *Pool) SyncStatusContext(ctx context.Context) (string, error)

SyncStatusContext is the context-aware variant of SyncStatus.

func (*Pool) SyncStop added in v0.4.0

func (p *Pool) SyncStop(table string) (string, error)

SyncStop stops a running sync.

func (*Pool) SyncStopContext added in v0.4.0

func (p *Pool) SyncStopContext(ctx context.Context, table string) (string, error)

SyncStopContext is the context-aware variant of SyncStop.

func (*Pool) WithConn added in v0.4.0

func (p *Pool) WithConn(ctx context.Context, fn func(c *Client) error) error

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). Outside QueryMatchAll, a query that is empty or only whitespace is rejected before it is sent.

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

	// QueryMatchAll sends no search text, so the request covers every indexed
	// row, narrowed by its filters and NOT terms (MygramDB >= v1.14). The
	// query must be empty, and Highlight, Fuzzy and a "_score" sort are
	// rejected because they need search text. AND terms, if given, act as the
	// search terms, as they do on the server.
	QueryMatchAll
)

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 flagged in RequiredIsGroup is a formatted
	// parenthesized sub-expression captured from "+(...)", already quoted.
	RequiredTerms []string

	// ExcludedTerms contains keywords marked for exclusion with '-'. An entry
	// flagged in ExcludedIsGroup is a formatted "-(...)" group.
	ExcludedTerms []string

	// RawExpression holds AST-syntax text reconstructed from any expression
	// with a top-level OR, or any parenthesized group not immediately
	// preceded by '+'/'-', with the shared wire-quoting decision already
	// applied to each of its terms.
	RawExpression string

	// RequiredIsGroup runs parallel to RequiredTerms: true where the entry is
	// a formatted (...) group rather than plain term text. A quoted phrase
	// shaped like a group stays plain text.
	RequiredIsGroup []bool

	// ExcludedIsGroup runs parallel to ExcludedTerms with the same meaning.
	ExcludedIsGroup []bool
}

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

Implicit AND binds tighter than OR, so an expression with a top-level OR is one group: "a OR b c" is "(a OR b c)". A '-' before a group excludes the whole group, and a quoted phrase is always a phrase, never a group.

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, or QueryMatchAll for a search without text. Requires
	// MygramDB >= v1.9 for a boolean query combined with filters, sorting,
	// fuzzy matching or highlights, and >= v1.14 for QueryMatchAll.
	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

	// ReadinessReason says why the server is not ready, such as "Initial load
	// is in progress" (MygramDB >= v1.13). It is the same text as the HTTP
	// readiness endpoint's reason, and empty when the server is ready or
	// predates the field.
	ReadinessReason 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

Jump to

Keyboard shortcuts

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