ha

package module
v0.18.3 Latest Latest
Warning

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

Go to latest
Published: Nov 23, 2026 License: Apache-2.0 Imports: 54 Imported by: 5 modules, 11 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-ha

Go Reference

A Go database/sql base driver providing high availability for SQLite databases through NATS-based (or kafka using https://github.com/litesql/go-kafka-ha) replication.

Features

  • High Availability: Ensure your SQLite databases remain accessible and consistent across multiple nodes.
  • Replication: Synchronize data across nodes using NATS messaging.
  • Flexible Conflict Resolution: Customize replication strategies and handle conflicts with ChangeSetInterceptor.
  • Cluster Modes:
    • Leaderless: Read/write from any node with last-writer-wins resolution.
    • Leader-based: Redirect writes to a leader to prevent conflicts.
    • Two-phase Commit: Read and write from any node using a 2PC strategy over gRPC streams to guarantee consistency across the cluster.
  • NATS Integration: Choose between embedded or external NATS servers.
  • Seamless Integration: Drop-in replacement for existing Go database/sql usage.
  • gRPC Support: Expose database operations via gRPC for remote access the sqlite database.
  • Snapshotting: Automatic database snapshots for efficient synchronization.
  • Cross-database Queries: Transparently execute cross-shard queries using SQL hints /*+ db=DSN */.
  • Transaction Undo: Revert already committed transactions.

Architecture

go-ha enables high availability for SQLite by replicating changes across multiple nodes using NATS as the messaging backbone. Each node maintains a local SQLite database and publishes changes to a NATS stream. Other nodes subscribe to this stream and apply the changes, ensuring data consistency.

The NATS publisher assigns a content-derived message ID to each changeset so JetStream can deduplicate identical publications within the stream's duplicate window. This does not deduplicate semantically equivalent changesets with different serialized content.

Comparison with SQLite Session Extension

go-ha provides a modern alternative to SQLite's session extension with enhanced capabilities:

Feature go-ha Session Extension
DDL Replication ✓ ✗
DML Replication ✓ ✓
Multi-node Cluster ✓ ✗
NATS Integration ✓ ✗
Conflict Resolution ✓ (Customizable) Limited
gRPC Support ✓ ✗
Cross-database Queries ✓ ✗

go-ha is designed for distributed systems requiring schema synchronization across nodes, while the session extension is suited for simpler peer-to-peer synchronization.

Installation

go get github.com/litesql/go-ha

Quick Start

Basic Usage
Instance 1
package main

import (
    "database/sql"
    "github.com/litesql/go-ha"
	sqlite3ha "github.com/litesql/go-sqlite3-ha"
)

func main() {
    slog.SetLogLoggerLevel(slog.LevelDebug)
    // Open a connection with HA enabled
    c, err := sqlite3ha.NewConnector("file:my.db?_journal=WAL&_timeout=5000",
		ha.WithName("instance1"),
        ha.WithReplicationID("example"),
		ha.WithGrpcPort(5000),		
		ha.WithEmbeddedNatsConfig(&ha.EmbeddedNatsConfig{
			Port: 4222,
		}))
	if err != nil {
		panic(err)
	}
	defer c.Close()

	db := sql.OpenDB(c)
	defer db.Close()

    // Use like any other database/sql driver
    _, err = db.Exec("CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, name TEXT)")
    if err != nil {
        panic(err)
    }

    // Insert data
    _, err = db.Exec("INSERT INTO users (name) VALUES (?)", "Alice")
    if err != nil {
        panic(err)
    }
}
Instance 2 (leader-based)
package main

import (
    "database/sql"
    "github.com/litesql/go-ha"
	sqlite3ha "github.com/litesql/go-sqlite3-ha"
)

func main() {
    slog.SetLogLoggerLevel(slog.LevelDebug)
    db, err := sql.Open("sqlite3-ha", "file:my2.db?_journal=WAL&_timeout=5000&replicationURL=nats://localhost:4222&replicationID=example&name=instance2&grpcInsecure=true&leaderProvider=static:localhost:5000")
	if err != nil {
		panic(err)
	}
	defer db.Close()

	_, err = db.Exec("INSERT INTO users(name) values('grpc leader redirect')")
	if err != nil {
		panic(err)
	}

	var name string
	err = db.QueryRowContext(context.Background(), "SELECT name FROM users ORDER BY rowid desc LIMIT 1").Scan(&name)
	if err != nil {
		panic(err)
	}

	fmt.Println("User:", name)
}
Cross-Database Queries

Execute queries across multiple databases using SQL hints:

// Query data from all loaded databases from the driver
rows, err := db.Query("/*+ db=.* */ SELECT * FROM users WHERE id = ?", 1)
if err != nil {
    panic(err)
}
defer rows.Close()
Conflict Resolution (ChangeSetInterceptor)

In leaderless / multi-master clusters, configure one of the built-in ChangeSetInterceptor implementations via ha.WithChangeSetInterceptor(...) (or the conflictResolution DSN parameter):

// 1. Schema-less Last-Writer-Wins (tracks per-row timestamps & tombstones in ha_lww_versions)
lww := ha.NewLastWriterWinsInterceptor()

// 2. Column-based Last-Writer-Wins / Monotonic Version (compares a column on the table itself)
colLWW := ha.NewColumnLWWInterceptor("updated_at",
    ha.WithTableVersionColumn("documents", "version"),
)

// 3. Filtering & Composition (e.g., ignore local-only tables, then resolve conflicts with LWW)
interceptor := ha.NewCompositeInterceptor(
    ha.NewIgnoreTablesInterceptor("local_sessions", "cache"),
    lww,
)

c, err := sqlite3ha.NewConnector("file:my.db?_journal=WAL",
    ha.WithName("node-1"),
    ha.WithChangeSetInterceptor(interceptor),
)

Built-in interceptors include:

  • NewLastWriterWinsInterceptor(opts...): Schema-less LWW using Change.TsNs / ChangeSet.Timestamp with deterministic node-name tie-breaking, local commit tracking, and delete tombstones.
  • NewColumnLWWInterceptor(column, opts...): Column-based LWW / version comparison supporting integers, floats, time.Time, RFC3339 / SQLite timestamps, and lexicographical HLC strings.
  • NewFilterInterceptor(fn), NewAllowTablesInterceptor(tables...), NewIgnoreTablesInterceptor(tables...), NewAllowOperationsInterceptor(ops...), NewIgnoreOperationsInterceptor(ops...): Declarative filtering by table, operation, or custom predicate.
  • NewCompositeInterceptor(interceptors...): Chains multiple interceptors (BeforeApply in order, AfterApply in reverse order).
  • ChangeSetInterceptorFuncs and NewNoopInterceptor(): Lightweight function adapter and embeddable no-op base.

Drivers

go-ha provides several driver implementations:

Configuration Options

DSN Parameter Description Default
asyncPublisher Enables asynchronous publishing of replication events using outbox pattern. false
autoStart Automatically starts publisher, subscriber and snapshotter on initialization. true
conflictResolution Built-in conflict resolution interceptor: lww, lww:<column>, column:<column>, or noop.
forcePublishBeforeStart Force publish data to stream before complete the start proccess false
replicationID Unique ID for this replication instance. [database filename]
deliverPolicy Delivery policy for replication events (all, last, etc.). all
disableSubscriber Disables the replication subscriber. false
disablePublisher Disables the replication publisher. false
disableDBSnapshotter Disables database snapshotter for initial sync. false
disableDDLSync Disables synchronization of DDL changes. false
grpcInsecure Use insecure gRPC connections. false
grpcPort TCP port for gRPC server.
grpcTimeout Timeout for gRPC operations. 5s
grpcToken Authentication token for gRPC server.
leaderProvider Leader election strategy (e.g., dynamic:local-host:port, static:remote-host:port).
name Node name in the cluster.
natsConfigFile Path to NATS server config file.
natsMaxPayload Maximum allowed payload size for embedded NATS messages (bytes).
natsName Name for embedded NATS server.
natsPort Port for embedded NATS server. 4222
natsUser Username for embedded NATS server.
natsPass Password for embedded NATS server.
natsStoreDir Data directory for embedded NATS server.
natsWebSocketPort WebSocket Port for embedded NATS server.
natsWebSocketNoTLS Disable WebSocket TLS for embedded NATS false
natsEnableLogs Enable embedded Nats logs false
otel Enable OpenTelemetry with global providers false
publisherTimeout Timeout for publishing replication events. 15s
replicationStream Name of the NATS stream for replication.
replicationURL NATS server URL for replication.
replicas Number of replicas for high availability (replication stream, snapshots and the leader election bucket). 1
rowIdentify Row identification strategy: pk, rowid, or full. pk
snapshotInterval Interval between database snapshots. 1m
streamMaxAge Maximum age of messages in replication stream.
metadataRetention Retention duration for internal metadata compaction (ha_lww_versions and COMMITTED ha_2pc_transactions). streamMaxAge
2pcPeers Comma-separated list of peer addresses participating in distributed two-phase commit coordination.
2pcTimeout Timeout for distributed two-phase commit coordination. 60s

Performance Considerations

  • Use embedded NATS for single-machine deployments to reduce latency.
  • Configure snapshotInterval based on your write frequency.
  • For high-throughput scenarios, consider leader-based clusters to avoid conflicts.
  • Monitor NATS stream size and adjust streamMaxAge to prevent unbounded growth.

Observability

Mount the connector's handlers on an HTTP server managed by your application:

mux := http.NewServeMux()
mux.Handle("/", connector.ObservabilityHandler())
log.Fatal(http.ListenAndServe(":8080", mux))

The handler exposes:

  • GET /healthz: liveness and current cluster status.
  • GET /readyz: readiness; returns 503 until startup completes, the database responds to Ping, the configured NATS connection is connected, and a dynamic leader is known.

Replication lag is reported in messages. For JetStream consumers it includes both pending and delivered-but-unacknowledged messages; other subscriber implementations report the local published/applied sequence difference. The health responses include the current leader target, NATS status, sequence numbers, lag by consumer node, and the last snapshot time when the snapshotter exposes it. Snapshotters can expose that timestamp by implementing LatestSnapshotTime() time.Time.

OpenTelemetry

OpenTelemetry instrumentation is optional. Configure the SDK and exporters in your application, then pass the providers to the connector:

connector, err := ha.NewConnector(
    dsn, driver, hooksFactory, backupFn,
    ha.WithOpenTelemetry(meterProvider, tracerProvider),
)

The connector records replication publish/apply and snapshot counts, failures, and durations, and HTTP request counts and durations for requests handled by ObservabilityHandler. It emits spans for publish, apply, snapshot, and observability HTTP operations; spans include operation identifiers and errors, and HTTP spans include route, method, and response status. When a global text-map propagator is configured, trace context is carried in replication changesets and extracted by subscribers so each apply span is linked to its publish span. OpenTelemetry metrics also report leadership, readiness, NATS connectivity, published/applied sequence, per-node replication lag, the last snapshot timestamp, and collection errors. Export metrics through the configured OpenTelemetry meter provider and exporter. Passing a nil provider uses the corresponding global OpenTelemetry provider. The application owns provider/exporter shutdown; the connector unregisters its metric callback when closed. The HTTP handler exposes only health and readiness endpoints.

Troubleshooting

Common Issues
  • Replication not working: Ensure NATS server is running and accessible via replicationURL.
  • Conflicts in leaderless mode: Implement a custom ChangeSetInterceptor for complex conflict resolution.
  • Slow synchronization: Check snapshotter configuration and network latency.
  • gRPC connection errors: Verify grpcPort and grpcToken settings.

Projects Using go-ha

  • HA: Highly available leaderless SQLite cluster with HTTP and PostgreSQL Wire Protocol
  • PocketBase HA: Highly available leaderless PocketBase cluster
  • PocketBase HC: Strictly consistent PocketBase cluster
  • sqlc-http: Generate net/http Go server from SQL

Contributing

We welcome contributions! Please:

  1. Fork the repository
  2. Create a feature branch
  3. Make your changes
  4. Add tests if applicable
  5. Submit a pull request

For major changes, please open an issue first to discuss the proposed changes.

License

This project is licensed under the MIT License. See the LICENSE file for details.

Documentation

Index

Constants

View Source
const (
	HealthPath    = "/healthz"
	ReadinessPath = "/readyz"
)
View Source
const (
	TypeExplain            = "EXPLAIN"
	TypeSelect             = "SELECT"
	TypeInsert             = "INSERT"
	TypeUpdate             = "UPDATE"
	TypeDelete             = "DELETE"
	TypeCreateTable        = "CREATE TABLE"
	TypeCreateIndex        = "CREATE INDEX"
	TypeCreateView         = "CREATE VIEW"
	TypeCreateTrigger      = "CREATE TRIGGER"
	TypeCreateVirtualTable = "CREATE VIRTUAL TABLE"
	TypeAlterTable         = "ALTER TABLE"
	TypeVacuum             = "VACUUM"
	TypeDrop               = "DROP"
	TypeAnalyze            = "ANALYZE"
	TypeBegin              = "BEGIN"
	TypeCommit             = "COMMIT"
	TypeRollback           = "ROLLBACK"
	TypeSavepoint          = "SAVEPOINT"
	TypeRelease            = "RELEASE"
	TypePragma             = "PRAGMA"
	TypeOther              = "OTHER"
)
View Source
const DefaultLWWTableName = "ha_lww_versions"

DefaultLWWTableName is the default local metadata table used by LastWriterWinsInterceptor to persist per-row version timestamps and tombstones.

View Source
const DefaultStream = "ha_replication"
View Source
const OutboxTable = "ha_outbox"

OutboxTable stores local changeset for async publishing.

View Source
const (
	TXCookieName = "_txseq"
)
View Source
const TwoPhaseCommitDecisionTable = "ha_2pc_decisions"

TwoPhaseCommitDecisionTable stores local commit decisions for crash recovery.

Variables

View Source
var (
	ErrInvalidSQL = fmt.Errorf("invalid SQL")
)
View Source
var ErrSnapshotterNotConfigured = errors.New("snapshotter not configured")
View Source
var ErrTimedOut = errors.New("Timed out")
View Source
var ErrTwoPhaseCommitPending = errors.New("two-phase commit is committed locally and pending remote recovery")

ErrTwoPhaseCommitPending marks a transaction committed locally but awaiting remote recovery.

Functions

func BackupWithAdapter added in v0.16.0

func BackupWithAdapter[T any](
	ctx context.Context,
	db *sql.DB,
	w io.Writer,
	serialize func(rawConn T) ([]byte, error),
	backupToFile func(ctx context.Context, rawConn T, destName string) error,
) error

func BackupWithAdapterCopy added in v0.18.2

func BackupWithAdapterCopy[T any](
	ctx context.Context,
	db *sql.DB,
	w io.Writer,
	serialize func(rawConn T) ([]byte, error),
	backupToFile func(ctx context.Context, rawConn T, destName string) error,
	copyOut func(dst io.Writer, src io.Reader) (int64, error),
) (retErr error)

func ClearTableSchemaCache added in v0.16.0

func ClearTableSchemaCache(replicationID string)

func ConnectHandler added in v0.8.0

func ConnectHandler(interceptors ...connect.ServerInterceptor) (path string, handler http.Handler)

func ContextLocalDB added in v0.11.4

func ContextLocalDB(ctx context.Context, useLocalDB bool) context.Context

func CrossShardQuery added in v0.5.8

func CrossShardQuery(ctx context.Context, stmt *Statement, args []driver.NamedValue, queryRouter *regexp.Regexp, driverConn driverConnFunc) (driver.Rows, error)

func DefaultLWWTieBreaker added in v0.17.0

func DefaultLWWTieBreaker(incomingNode, localNode string) bool

DefaultLWWTieBreaker deterministically breaks timestamp ties by comparing node names lexicographically. For identical node names (e.g. idempotent replay or consecutive writes in the same nanosecond), incoming wins.

func ExtractRawConn added in v0.16.0

func ExtractRawConn[T any](conn *sql.Conn) (T, error)

func HistoryTableDeclaration added in v0.16.0

func HistoryTableDeclaration(tableName string) string

func LatestSnapshot added in v0.0.4

func LatestSnapshot(ctx context.Context, dsn string, options ...Option) (sequence uint64, reader io.ReadCloser, err error)

func ListDSN added in v0.1.3

func ListDSN() []string

func ListReplicationIDs added in v0.4.5

func ListReplicationIDs() []string

func LocalDB added in v0.11.4

func LocalDB(ctx context.Context) bool

func MountConnect added in v0.18.0

func MountConnect(mux connecthttp.ServeMux, interceptors []connect.ServerInterceptor, opts ...connecthttp.Option)

func NewConnectServer added in v0.18.0

func NewConnectServer(interceptors ...connect.ServerInterceptor) *connect.Server

func Shutdown added in v0.0.16

func Shutdown()

func UndoFunc added in v0.16.0

func UndoFunc(connector *Connector, filter haconnect.UndoFilter) func(int64) string

Types

type BackupFn added in v0.0.10

type BackupFn func(context.Context, *sql.DB, io.Writer) error

type CDCPublisher

type CDCPublisher interface {
	Publish(data []DebeziumData) error
}

type Change

type Change struct {
	Database  string   `json:"database,omitempty"`
	Table     string   `json:"table,omitempty"`
	Columns   []string `json:"columns,omitempty"`
	PKColumns []string `json:"pk_columns,omitempty"`
	Operation string   `json:"operation"` // "INSERT", "UPDATE", "DELETE", "SQL", "CUSTOM"
	OldRowID  int64    `json:"old_rowid,omitempty"`
	NewRowID  int64    `json:"new_rowid,omitempty"`
	OldValues []any    `json:"old_values,omitempty"`
	NewValues []any    `json:"new_values,omitempty"`
	Command   string   `json:"command,omitempty"`
	Args      []any    `json:"args,omitempty"`
	TsNs      int64    `json:"ts_ns,omitempty"`
}

func (Change) PKColumnsNames added in v0.2.0

func (c Change) PKColumnsNames() []string

func (Change) PKNewValues added in v0.2.1

func (c Change) PKNewValues() []any

func (Change) PKOldValues added in v0.2.0

func (c Change) PKOldValues() []any

func (Change) Reverse added in v0.10.0

func (c Change) Reverse() Change

type ChangeFilterFunc added in v0.17.0

type ChangeFilterFunc func(cs *ChangeSet, change Change) bool

ChangeFilterFunc decides whether an individual Change within a ChangeSet should be applied.

type ChangeSet

type ChangeSet struct {
	Node          string            `json:"node"`
	ProcessID     int64             `json:"process_id"`
	Filename      string            `json:"filename"`
	Changes       []Change          `json:"changes"`
	TraceContext  map[string]string `json:"trace_context,omitempty"`
	Timestamp     int64             `json:"timestamp_ns"`
	TransactionID string            `json:"transaction_id,omitempty"`
	Subject       string            `json:"-"`
	StreamSeq     uint64            `json:"-"`
	// contains filtered or unexported fields
}

func NewChangeSet

func NewChangeSet(node string, replicationID string) *ChangeSet

func (*ChangeSet) AddChange

func (cs *ChangeSet) AddChange(change Change)

func (*ChangeSet) AfterCommit added in v0.12.2

func (cs *ChangeSet) AfterCommit(conn *sql.Conn, err error) error

func (*ChangeSet) Apply

func (cs *ChangeSet) Apply(ctx context.Context, db *sql.DB) (err error)

func (*ChangeSet) Clear

func (cs *ChangeSet) Clear()

func (*ChangeSet) DebeziumData added in v0.3.0

func (cs *ChangeSet) DebeziumData() []DebeziumData

func (*ChangeSet) Prepare added in v0.12.1

func (cs *ChangeSet) Prepare(ctx context.Context, db *sql.DB) (conn *haconnect.ConnHooksEnabler, tx *sql.Tx, err error)

func (*ChangeSet) Send

func (cs *ChangeSet) Send(ctx context.Context, pub Publisher) error

func (*ChangeSet) SetConnProvider added in v0.0.10

func (cs *ChangeSet) SetConnProvider(connProvider ConnHooksProvider)

func (*ChangeSet) SetInterceptor added in v0.0.6

func (cs *ChangeSet) SetInterceptor(interceptor ChangeSetInterceptor)

func (*ChangeSet) SetStrategy added in v0.10.5

func (cs *ChangeSet) SetStrategy(t sqlStrategy)

func (*ChangeSet) UndoLocal added in v0.13.3

func (cs *ChangeSet) UndoLocal(db *sql.DB) error

type ChangeSetInterceptor added in v0.0.6

type ChangeSetInterceptor interface {
	BeforeApply(*ChangeSet, *sql.Conn) (skip bool, err error)
	AfterApply(*ChangeSet, *sql.Conn, error) error
}

type ChangeSetInterceptorFuncs added in v0.17.0

type ChangeSetInterceptorFuncs struct {
	BeforeApplyFn func(cs *ChangeSet, conn *sql.Conn) (skip bool, err error)
	AfterApplyFn  func(cs *ChangeSet, conn *sql.Conn, applyErr error) error
}

ChangeSetInterceptorFuncs adapts plain functions to the ChangeSetInterceptor interface.

func (ChangeSetInterceptorFuncs) AfterApply added in v0.17.0

func (f ChangeSetInterceptorFuncs) AfterApply(cs *ChangeSet, conn *sql.Conn, applyErr error) error

func (ChangeSetInterceptorFuncs) BeforeApply added in v0.17.0

func (f ChangeSetInterceptorFuncs) BeforeApply(cs *ChangeSet, conn *sql.Conn) (bool, error)

type ChangeSetSerializer added in v0.0.6

type ChangeSetSerializer func(*ChangeSet) ([]byte, error)

type ColumnLWWConflictHandler added in v0.17.0

type ColumnLWWConflictHandler func(cs *ChangeSet, change Change, localValue, incomingValue any)

ColumnLWWConflictHandler is invoked whenever an incoming Change loses column-based LWW resolution.

type ColumnLWWInterceptor added in v0.17.0

type ColumnLWWInterceptor struct {
	NoopInterceptor
	// contains filtered or unexported fields
}

ColumnLWWInterceptor implements Last-Writer-Wins / monotonic-version conflict resolution by comparing a column on the target table itself (such as "updated_at", "version", or an HLC string) against the current row stored in the local database.

Supported column types include integers, floats, time.Time, RFC3339 / SQLite datetime strings, and lexicographically ordered strings (such as ISO-8601 UTC or HLCs). For DELETE changes, the delete applies only if the local row version has not advanced past the version observed in Change.OldValues, preventing concurrent updates from being lost while maintaining convergence across nodes.

func NewColumnLWWInterceptor added in v0.17.0

func NewColumnLWWInterceptor(column string, opts ...ColumnLWWOption) *ColumnLWWInterceptor

NewColumnLWWInterceptor creates a ColumnLWWInterceptor using column as the default version/timestamp column name (defaults to "updated_at" if empty).

func (*ColumnLWWInterceptor) BeforeApply added in v0.17.0

func (i *ColumnLWWInterceptor) BeforeApply(cs *ChangeSet, conn *sql.Conn) (bool, error)

type ColumnLWWOption added in v0.17.0

type ColumnLWWOption func(*ColumnLWWInterceptor)

ColumnLWWOption configures a ColumnLWWInterceptor.

func WithColumnLWWAtomicTransaction added in v0.17.0

func WithColumnLWWAtomicTransaction(atomic bool) ColumnLWWOption

WithColumnLWWAtomicTransaction controls whether a conflict on any single row skips the entire ChangeSet transaction (true) or only drops the stale row Changes (false, default).

func WithColumnLWWIgnoreTables added in v0.17.0

func WithColumnLWWIgnoreTables(tables ...string) ColumnLWWOption

WithColumnLWWIgnoreTables excludes the given tables from column-based LWW conflict resolution.

func WithColumnLWWOnConflict added in v0.17.0

func WithColumnLWWOnConflict(fn ColumnLWWConflictHandler) ColumnLWWOption

WithColumnLWWOnConflict registers a callback invoked whenever an incoming Change loses resolution.

func WithColumnLWWStrictMissingColumn added in v0.17.0

func WithColumnLWWStrictMissingColumn(strict bool) ColumnLWWOption

WithColumnLWWStrictMissingColumn returns an error in BeforeApply if a managed table does not contain the configured version column (default false: changes pass through).

func WithColumnLWWTables added in v0.17.0

func WithColumnLWWTables(tables ...string) ColumnLWWOption

WithColumnLWWTables restricts column-based LWW conflict resolution to the given tables.

func WithColumnLWWTieBreaker added in v0.17.0

func WithColumnLWWTieBreaker(fn LWWTieBreaker) ColumnLWWOption

WithColumnLWWTieBreaker sets the node tie-breaker used together with WithNodeTieBreakerColumn.

func WithNodeTieBreakerColumn added in v0.17.0

func WithNodeTieBreakerColumn(column string) ColumnLWWOption

WithNodeTieBreakerColumn specifies an optional column storing the writer's node identifier to break ties when two concurrent writes carry the exact same version/timestamp value. When unset, ties are broken deterministically by comparing row column values.

func WithTableVersionColumn added in v0.17.0

func WithTableVersionColumn(table, column string) ColumnLWWOption

WithTableVersionColumn overrides the version/timestamp column name for a specific table.

type CompositeInterceptor added in v0.17.0

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

CompositeInterceptor chains multiple ChangeSetInterceptors together. BeforeApply executes interceptors in order and stops early if any interceptor returns skip=true or a non-nil error. AfterApply executes in reverse order for all interceptors whose BeforeApply ran.

func NewCompositeInterceptor added in v0.17.0

func NewCompositeInterceptor(interceptors ...ChangeSetInterceptor) *CompositeInterceptor

NewCompositeInterceptor creates a CompositeInterceptor from the given interceptors. Nil entries are ignored.

func (*CompositeInterceptor) AfterApply added in v0.17.0

func (c *CompositeInterceptor) AfterApply(cs *ChangeSet, conn *sql.Conn, applyErr error) error

func (*CompositeInterceptor) BeforeApply added in v0.17.0

func (c *CompositeInterceptor) BeforeApply(cs *ChangeSet, conn *sql.Conn) (bool, error)

func (*CompositeInterceptor) OnLocalChangeSet added in v0.17.0

func (c *CompositeInterceptor) OnLocalChangeSet(cs *ChangeSet)

type CompositePublisher added in v0.12.1

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

func NewCompositePublisher added in v0.12.1

func NewCompositePublisher(publishers ...Publisher) *CompositePublisher

func (*CompositePublisher) Close added in v0.18.0

func (p *CompositePublisher) Close() error

func (*CompositePublisher) Publish added in v0.12.1

func (p *CompositePublisher) Publish(ctx context.Context, cs *ChangeSet) error

func (*CompositePublisher) Sequence added in v0.12.1

func (p *CompositePublisher) Sequence() uint64

type Conn

type Conn struct {
	SQLiteConn
	// contains filtered or unexported fields
}

func HAConn added in v0.16.0

func HAConn(conn *sql.Conn) (*Conn, error)

func (*Conn) Begin added in v0.16.0

func (c *Conn) Begin() (driver.Tx, error)

func (*Conn) BeginTx added in v0.16.0

func (c *Conn) BeginTx(ctx context.Context, opts driver.TxOptions) (tx driver.Tx, retErr error)

func (*Conn) CheckNamedValue added in v0.16.0

func (c *Conn) CheckNamedValue(nv *driver.NamedValue) error

func (*Conn) Close added in v0.16.0

func (c *Conn) Close() error

func (*Conn) Context added in v0.16.0

func (c *Conn) Context() context.Context

func (*Conn) Exec

func (c *Conn) Exec(query string, args []driver.Value) (driver.Result, error)

func (*Conn) ExecContext

func (c *Conn) ExecContext(ctx context.Context, query string, args []driver.NamedValue) (result driver.Result, retErr error)

func (*Conn) IsValid added in v0.16.0

func (c *Conn) IsValid() bool

func (*Conn) Mutex added in v0.16.0

func (c *Conn) Mutex() *sync.Mutex

func (*Conn) Ping added in v0.16.0

func (c *Conn) Ping(ctx context.Context) error

func (*Conn) Query added in v0.16.0

func (c *Conn) Query(query string, args []driver.Value) (driver.Rows, error)

func (*Conn) QueryContext added in v0.16.0

func (c *Conn) QueryContext(ctx context.Context, query string, args []driver.NamedValue) (result driver.Rows, retErr error)

func (*Conn) ResetSession added in v0.16.0

func (c *Conn) ResetSession(ctx context.Context) error

type ConnHooksFactory added in v0.0.10

type ConnHooksFactory func() ConnHooksProvider

type ConnHooksProvider added in v0.0.10

type ConnHooksProvider interface {
	RegisterHooks(driver.Conn, *Connector) (driver.Conn, error)
	DisableHooks(*sql.Conn) error
	EnableHooks(*sql.Conn) error
}

func NewSQLiteHooksProvider added in v0.16.0

func NewSQLiteHooksProvider(adapter SQLiteHooksAdapter) ConnHooksProvider

type Connector

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

func LookupConnector added in v0.1.0

func LookupConnector(dsn string) (*Connector, bool)

func LookupConnectorByReplicationID added in v0.4.5

func LookupConnectorByReplicationID(id string) (*Connector, bool)

func NewConnector

func NewConnector(dsn string, drv driver.Driver, connHooksFactory ConnHooksFactory, backupFn BackupFn, options ...Option) (*Connector, error)

func (*Connector) Backup added in v0.8.0

func (c *Connector) Backup(ctx context.Context, writer io.Writer) error

func (*Connector) CDCPublisher added in v0.3.0

func (c *Connector) CDCPublisher() CDCPublisher

func (*Connector) Close

func (c *Connector) Close()

func (*Connector) Connect

func (c *Connector) Connect(ctx context.Context) (driver.Conn, error)

func (*Connector) ConsistentReader added in v0.1.0

func (c *Connector) ConsistentReader(timeout time.Duration, methods ...string) func(http.Handler) http.Handler

func (*Connector) ConsistentReaderFunc added in v0.1.0

func (c *Connector) ConsistentReaderFunc(h http.HandlerFunc, timeout time.Duration, methods ...string) http.HandlerFunc

func (*Connector) ContiguousSeq added in v0.16.2

func (c *Connector) ContiguousSeq() uint64

func (*Connector) DB added in v0.4.5

func (c *Connector) DB() *sql.DB

func (*Connector) DeliveredInfo

func (c *Connector) DeliveredInfo(ctx context.Context, name string) (any, error)

func (*Connector) DisableDDLSync added in v0.13.0

func (c *Connector) DisableDDLSync() bool

func (*Connector) DisableHooks added in v0.13.5

func (c *Connector) DisableHooks(conn *sql.Conn) error

func (*Connector) Driver

func (c *Connector) Driver() driver.Driver

func (*Connector) EnableHooks added in v0.13.5

func (c *Connector) EnableHooks(conn *sql.Conn) error

func (*Connector) ForwardToLeader added in v0.1.0

func (c *Connector) ForwardToLeader(timeout time.Duration, methods ...string) func(http.Handler) http.Handler

func (*Connector) ForwardToLeaderFunc added in v0.1.0

func (c *Connector) ForwardToLeaderFunc(h http.HandlerFunc, timeout time.Duration, methods ...string) http.HandlerFunc

func (*Connector) GrpcInsecure added in v0.13.0

func (c *Connector) GrpcInsecure() bool

func (*Connector) GrpcTimeout added in v0.13.0

func (c *Connector) GrpcTimeout() time.Duration

func (*Connector) GrpcToken added in v0.13.0

func (c *Connector) GrpcToken() string

func (*Connector) HealthHandler added in v0.15.0

func (c *Connector) HealthHandler() http.Handler

func (*Connector) HistoryBySeq added in v0.10.5

func (c *Connector) HistoryBySeq(ctx context.Context, startSeq uint64) ([]haconnect.HistoryItem, error)

func (*Connector) HistoryByTime added in v0.10.5

func (c *Connector) HistoryByTime(ctx context.Context, duration time.Duration) ([]haconnect.HistoryItem, error)

func (*Connector) LatestSeq

func (c *Connector) LatestSeq() uint64

func (*Connector) LatestSnapshot

func (c *Connector) LatestSnapshot(ctx context.Context) (uint64, io.ReadCloser, error)

func (*Connector) LeaderProvider added in v0.1.1

func (c *Connector) LeaderProvider() LeaderProvider

func (*Connector) Mutex added in v0.13.6

func (c *Connector) Mutex() *sync.Mutex

func (*Connector) NodeName added in v0.0.10

func (c *Connector) NodeName() string

func (*Connector) ObservabilityHandler added in v0.15.0

func (c *Connector) ObservabilityHandler() http.Handler

func (*Connector) ProxiedDB added in v0.11.4

func (c *Connector) ProxiedDB() *sql.DB

func (*Connector) ProxiedPositionProvider added in v0.11.8

func (c *Connector) ProxiedPositionProvider() ProxiedPositionProvider

func (*Connector) PruneMetadata added in v0.18.0

func (c *Connector) PruneMetadata(ctx context.Context, olderThan time.Duration) error

PruneMetadata compacts internal HA metadata tables (LWW version/tombstone records and COMMITTED two-phase commit transaction records) older than olderThan.

func (*Connector) PubSeq added in v0.4.5

func (c *Connector) PubSeq() uint64

func (*Connector) Publisher added in v0.0.10

func (c *Connector) Publisher() Publisher

func (*Connector) QueryRouter added in v0.13.0

func (c *Connector) QueryRouter() *regexp.Regexp

func (*Connector) ReadinessHandler added in v0.15.0

func (c *Connector) ReadinessHandler() http.Handler

func (*Connector) RemoveConsumer

func (c *Connector) RemoveConsumer(ctx context.Context, name string) error

func (*Connector) ReplicationID added in v0.13.0

func (c *Connector) ReplicationID() string

func (*Connector) ResponseWriter added in v0.1.3

func (c *Connector) ResponseWriter(w http.ResponseWriter) http.ResponseWriter

func (*Connector) SetProxiedDB added in v0.11.4

func (c *Connector) SetProxiedDB(db *sql.DB)

func (*Connector) SetProxiedPositionProvider added in v0.11.8

func (c *Connector) SetProxiedPositionProvider(provider ProxiedPositionProvider)

func (*Connector) Snapshotter added in v0.0.13

func (c *Connector) Snapshotter() DBSnapshotter

func (*Connector) Start added in v0.1.1

func (c *Connector) Start(db *sql.DB) error

func (*Connector) Subscriber added in v0.0.13

func (c *Connector) Subscriber() Subscriber

func (*Connector) TakeSnapshot

func (c *Connector) TakeSnapshot(ctx context.Context) (sequence uint64, err error)

func (*Connector) UndoBySeq added in v0.10.5

func (c *Connector) UndoBySeq(ctx context.Context, startSeq uint64, filterType haconnect.UndoFilter, filterEntities map[string][]int64) error

func (*Connector) UndoByTime added in v0.10.3

func (c *Connector) UndoByTime(ctx context.Context, duration time.Duration, filterType haconnect.UndoFilter, filterEntities map[string][]int64) error

type DBPublisher added in v0.10.7

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

func NewDBPublisher added in v0.10.7

func NewDBPublisher(db *sql.DB, maxAge time.Duration) (*DBPublisher, error)

func (*DBPublisher) Close added in v0.10.8

func (p *DBPublisher) Close() error

func (*DBPublisher) Publish added in v0.10.7

func (p *DBPublisher) Publish(ctx context.Context, cs *ChangeSet) error

func (*DBPublisher) SeqNotifyCh added in v0.18.0

func (p *DBPublisher) SeqNotifyCh() <-chan struct{}

func (*DBPublisher) Sequence added in v0.10.7

func (p *DBPublisher) Sequence() uint64

type DBSnapshotter added in v0.0.6

type DBSnapshotter interface {
	DB() *sql.DB
	SetDB(*sql.DB)
	Start()
	TakeSnapshot(ctx context.Context) (sequence uint64, err error)
	LatestSnapshot(ctx context.Context) (sequence uint64, reader io.ReadCloser, err error)
}

type DBSubscriber added in v0.10.7

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

func NewDBSubscriber added in v0.10.7

func NewDBSubscriber(cfg DBSubscriberConfig) (*DBSubscriber, error)

func (*DBSubscriber) DB added in v0.11.0

func (s *DBSubscriber) DB() *sql.DB

func (*DBSubscriber) DeliveredInfo added in v0.10.7

func (s *DBSubscriber) DeliveredInfo(ctx context.Context, name string) (any, error)

func (*DBSubscriber) HistoryBySeq added in v0.10.7

func (s *DBSubscriber) HistoryBySeq(ctx context.Context, startSeq uint64) ([]haconnect.HistoryItem, error)

func (*DBSubscriber) HistoryByTime added in v0.10.7

func (s *DBSubscriber) HistoryByTime(ctx context.Context, duration time.Duration) ([]haconnect.HistoryItem, error)

func (*DBSubscriber) LatestSeq added in v0.10.7

func (s *DBSubscriber) LatestSeq() uint64

func (*DBSubscriber) RemoveConsumer added in v0.10.7

func (s *DBSubscriber) RemoveConsumer(ctx context.Context, name string) error

func (*DBSubscriber) SeqNotifyCh added in v0.18.0

func (s *DBSubscriber) SeqNotifyCh() <-chan struct{}

func (*DBSubscriber) SetDB added in v0.10.7

func (s *DBSubscriber) SetDB(db *sql.DB)

func (*DBSubscriber) Start added in v0.10.7

func (s *DBSubscriber) Start() error

func (*DBSubscriber) UndoBySeq added in v0.10.7

func (s *DBSubscriber) UndoBySeq(ctx context.Context, startSeq uint64, filter haconnect.UndoFilter, filterEntities map[string][]int64) error

func (*DBSubscriber) UndoByTime added in v0.10.7

func (s *DBSubscriber) UndoByTime(ctx context.Context, duration time.Duration, filterType haconnect.UndoFilter, filterEntities map[string][]int64) error

type DBSubscriberConfig added in v0.10.7

type DBSubscriberConfig struct {
	HistoryDB    *sql.DB
	DB           *sql.DB
	ConnProvider ConnHooksProvider
	Interceptor  ChangeSetInterceptor
	RowIdentify  RowIdentify
}

type DebeziumData added in v0.3.0

type DebeziumData struct {
	Schema      any                 `json:"schema"`
	Payload     DebeziumPayload     `json:"payload"`
	Transaction DebeziumTransaction `json:"transaction"`
}

type DebeziumPayload added in v0.3.0

type DebeziumPayload struct {
	Before map[string]any `json:"before"`
	After  map[string]any `json:"after"`
	Source DebeziumSource `json:"source"`
	Op     string         `json:"op"`
	TsNs   int64          `json:"ts_ns"`
}

type DebeziumSource added in v0.3.0

type DebeziumSource struct {
	Version   string `json:"version"`
	Connector string `json:"connector"`
	Name      string `json:"name"`
	ServerID  int64  `json:"server_id"`
	TsNs      int64  `json:"ts_ns"`
	DB        string `json:"db"`
	Table     string `json:"table"`
}

type DebeziumTransaction added in v0.3.0

type DebeziumTransaction struct {
	ID string `json:"id"`
}

type DynamicLeader added in v0.1.1

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

func StartLeaderElection added in v0.15.0

func StartLeaderElection(ctx context.Context, redirectTarget string, nc *nats.Conn, subject string, clusterSize int, replicas int, logFile string) (*DynamicLeader, error)

func (*DynamicLeader) IsLeader added in v0.1.1

func (d *DynamicLeader) IsLeader() bool

func (*DynamicLeader) IsReady added in v0.15.0

func (d *DynamicLeader) IsReady() bool

func (*DynamicLeader) Ready added in v0.1.1

func (d *DynamicLeader) Ready() chan struct{}

func (*DynamicLeader) RedirectTarget added in v0.1.1

func (d *DynamicLeader) RedirectTarget() string

type EmbeddedNatsConfig

type EmbeddedNatsConfig struct {
	Name           string
	Port           int
	StoreDir       string
	User           string
	Pass           string
	File           string
	MaxPayload     int32
	WebSocketPort  int
	WebSocketNoTLS bool
	EnableLogs     bool
}

type FilterInterceptor added in v0.17.0

type FilterInterceptor struct {
	NoopInterceptor
	// contains filtered or unexported fields
}

FilterInterceptor filters Changes in a ChangeSet using a predicate function. If all changes in a non-empty ChangeSet are filtered out, BeforeApply returns skip=true.

func NewAllowOperationsInterceptor added in v0.17.0

func NewAllowOperationsInterceptor(operations ...string) *FilterInterceptor

NewAllowOperationsInterceptor returns an interceptor that only applies changes whose Operation matches one of the specified operations (e.g. "INSERT", "UPDATE", "DELETE", "SQL").

func NewAllowTablesInterceptor added in v0.17.0

func NewAllowTablesInterceptor(tables ...string) *FilterInterceptor

NewAllowTablesInterceptor returns an interceptor that only applies changes targeting the specified tables.

func NewFilterInterceptor added in v0.17.0

func NewFilterInterceptor(keep ChangeFilterFunc) *FilterInterceptor

NewFilterInterceptor creates a FilterInterceptor that retains only changes where keep returns true.

func NewIgnoreOperationsInterceptor added in v0.17.0

func NewIgnoreOperationsInterceptor(operations ...string) *FilterInterceptor

NewIgnoreOperationsInterceptor returns an interceptor that drops changes whose Operation matches any of the specified operations (e.g. "DELETE", "SQL").

func NewIgnoreTablesInterceptor added in v0.17.0

func NewIgnoreTablesInterceptor(tables ...string) *FilterInterceptor

NewIgnoreTablesInterceptor returns an interceptor that drops changes targeting the specified tables.

func (*FilterInterceptor) BeforeApply added in v0.17.0

func (f *FilterInterceptor) BeforeApply(cs *ChangeSet, _ *sql.Conn) (bool, error)

type HistoryCursor added in v0.16.0

type HistoryCursor struct {
	Connector *Connector
	Pos       int
	Rows      []haconnect.HistoryItem
}

func (*HistoryCursor) Close added in v0.16.0

func (vc *HistoryCursor) Close() error

func (*HistoryCursor) ColumnValue added in v0.16.0

func (vc *HistoryCursor) ColumnValue(col int) any

func (*HistoryCursor) EOF added in v0.16.0

func (vc *HistoryCursor) EOF() bool

func (*HistoryCursor) FilterValue added in v0.16.0

func (vc *HistoryCursor) FilterValue(hasVal bool, firstVal any) error

func (*HistoryCursor) Next added in v0.16.0

func (vc *HistoryCursor) Next() error

func (*HistoryCursor) Rowid added in v0.16.0

func (vc *HistoryCursor) Rowid() (int64, error)

type HookCallbacks added in v0.16.0

type HookCallbacks struct {
	OnPreUpdate func(Change)
	OnCommit    func() error
	OnRollback  func()
}

type JSONPublisher added in v0.0.6

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

func NewJSONPublisher added in v0.0.6

func NewJSONPublisher(w io.Writer) *JSONPublisher

func (*JSONPublisher) Publish added in v0.0.6

func (p *JSONPublisher) Publish(ctx context.Context, cs *ChangeSet) error

func (*JSONPublisher) Sequence added in v0.0.20

func (p *JSONPublisher) Sequence() uint64

type LWWConflictHandler added in v0.17.0

type LWWConflictHandler func(cs *ChangeSet, change Change, localTsNs int64, localNode string)

LWWConflictHandler is called whenever an incoming Change is skipped due to a newer local version.

type LWWOption added in v0.17.0

type LWWOption func(*LastWriterWinsInterceptor)

LWWOption configures a LastWriterWinsInterceptor.

func WithLWWAtomicTransaction added in v0.17.0

func WithLWWAtomicTransaction(atomic bool) LWWOption

WithLWWAtomicTransaction controls whether a conflict on any single row skips the entire ChangeSet transaction (true) or only drops the stale row Changes (false, default).

func WithLWWIgnoreTables added in v0.17.0

func WithLWWIgnoreTables(tables ...string) LWWOption

WithLWWIgnoreTables excludes the given tables from LWW conflict resolution.

func WithLWWOnConflict added in v0.17.0

func WithLWWOnConflict(fn LWWConflictHandler) LWWOption

WithLWWOnConflict registers a callback invoked whenever an incoming Change loses LWW resolution.

func WithLWWRetentionTTL added in v0.18.0

func WithLWWRetentionTTL(ttl time.Duration) LWWOption

WithLWWRetentionTTL configures automatic pruning of LWW version/tombstone entries older than ttl.

func WithLWWTableName added in v0.17.0

func WithLWWTableName(name string) LWWOption

WithLWWTableName sets the local SQLite table name used to store per-row LWW metadata.

func WithLWWTables added in v0.17.0

func WithLWWTables(tables ...string) LWWOption

WithLWWTables restricts LWW conflict resolution to the given tables. Changes to other tables pass through unmodified.

func WithLWWTieBreaker added in v0.17.0

func WithLWWTieBreaker(fn LWWTieBreaker) LWWOption

WithLWWTieBreaker sets a custom tie-breaker function for equal timestamps.

type LWWTieBreaker added in v0.17.0

type LWWTieBreaker func(incomingNode, localNode string) bool

LWWTieBreaker breaks ties when an incoming change and the local state have the exact same timestamp/version. Returning true means the incoming change wins; returning false keeps the local state.

type LastWriterWinsInterceptor added in v0.17.0

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

LastWriterWinsInterceptor implements schema-less Last-Writer-Wins (LWW) conflict resolution using Change.TsNs (falling back to ChangeSet.Timestamp) and a deterministic node-name tie-breaker.

Per-row timestamps and delete tombstones are persisted in a local control table (DefaultLWWTableName by default) and local commits on the origin node are tracked automatically via LocalChangeSetObserver so multi-master clusters converge cleanly without requiring timestamp columns on application tables.

func NewLastWriterWinsInterceptor added in v0.17.0

func NewLastWriterWinsInterceptor(opts ...LWWOption) *LastWriterWinsInterceptor

NewLastWriterWinsInterceptor creates a new LastWriterWinsInterceptor with the given options.

func (*LastWriterWinsInterceptor) AfterApply added in v0.17.0

func (i *LastWriterWinsInterceptor) AfterApply(cs *ChangeSet, conn *sql.Conn, applyErr error) error

func (*LastWriterWinsInterceptor) BeforeApply added in v0.17.0

func (i *LastWriterWinsInterceptor) BeforeApply(cs *ChangeSet, conn *sql.Conn) (bool, error)

func (*LastWriterWinsInterceptor) OnLocalChangeSet added in v0.17.0

func (i *LastWriterWinsInterceptor) OnLocalChangeSet(cs *ChangeSet)

OnLocalChangeSet records locally committed row versions so concurrent remote changesets with older timestamps cannot overwrite newer local writes.

func (*LastWriterWinsInterceptor) PruneBefore added in v0.18.0

func (i *LastWriterWinsInterceptor) PruneBefore(ctx context.Context, db *sql.DB, cutoff time.Time) (int64, error)

PruneBefore deletes LWW version/tombstone records strictly older than cutoff.

type LeaderProvider added in v0.1.0

type LeaderProvider interface {
	IsLeader() bool
	Ready() chan struct{}
	RedirectTarget() string
}

type LocalChangeSetObserver added in v0.17.0

type LocalChangeSetObserver interface {
	OnLocalChangeSet(cs *ChangeSet)
}

LocalChangeSetObserver is an optional interface that ChangeSetInterceptor implementations may implement to observe locally committed ChangeSets on the originating node (for example, to record local row timestamps for multi-master conflict resolution before remote changesets arrive).

type NATSPublisher added in v0.0.6

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

func NewNATSPublisher added in v0.0.6

func NewNATSPublisher(nc *nats.Conn, subject string, timeout time.Duration, streamConfig *jetstream.StreamConfig) (*NATSPublisher, error)

func (*NATSPublisher) Publish added in v0.0.6

func (p *NATSPublisher) Publish(ctx context.Context, cs *ChangeSet) error

func (*NATSPublisher) SeqNotifyCh added in v0.18.0

func (p *NATSPublisher) SeqNotifyCh() <-chan struct{}

func (*NATSPublisher) Sequence added in v0.0.20

func (p *NATSPublisher) Sequence() uint64

func (*NATSPublisher) SequenceRange added in v0.16.2

func (p *NATSPublisher) SequenceRange() (uint64, uint64)

type NATSSnapshotter added in v0.0.6

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

func NewNATSSnapshotter added in v0.0.6

func NewNATSSnapshotter(ctx context.Context, nc *nats.Conn, replicas int, stream string, db *sql.DB, backupFn BackupFn, interval time.Duration, sequenceProvider SequenceProvider, objectName string) (*NATSSnapshotter, error)

func (*NATSSnapshotter) Close added in v0.18.0

func (s *NATSSnapshotter) Close() error

func (*NATSSnapshotter) DB added in v0.11.0

func (s *NATSSnapshotter) DB() *sql.DB

func (*NATSSnapshotter) LatestSnapshot added in v0.0.6

func (s *NATSSnapshotter) LatestSnapshot(ctx context.Context) (uint64, io.ReadCloser, error)

func (*NATSSnapshotter) LatestSnapshotSequence added in v0.0.6

func (s *NATSSnapshotter) LatestSnapshotSequence(ctx context.Context) (uint64, error)

func (*NATSSnapshotter) LatestSnapshotTime added in v0.15.0

func (s *NATSSnapshotter) LatestSnapshotTime() time.Time

func (*NATSSnapshotter) SetDB added in v0.0.13

func (s *NATSSnapshotter) SetDB(db *sql.DB)

func (*NATSSnapshotter) Start added in v0.0.13

func (s *NATSSnapshotter) Start()

func (*NATSSnapshotter) TakeSnapshot added in v0.0.6

func (s *NATSSnapshotter) TakeSnapshot(ctx context.Context) (sequence uint64, err error)

type NATSSubscriber added in v0.0.6

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

func NewNATSSubscriber added in v0.0.6

func NewNATSSubscriber(cfg NATSSubscriberConfig) (*NATSSubscriber, error)

func (*NATSSubscriber) Close added in v0.18.0

func (s *NATSSubscriber) Close() error

func (*NATSSubscriber) DB added in v0.11.0

func (s *NATSSubscriber) DB() *sql.DB

func (*NATSSubscriber) DeliveredInfo added in v0.0.6

func (s *NATSSubscriber) DeliveredInfo(ctx context.Context, name string) (any, error)

func (*NATSSubscriber) HistoryBySeq added in v0.10.5

func (s *NATSSubscriber) HistoryBySeq(ctx context.Context, startSeq uint64) ([]haconnect.HistoryItem, error)

func (*NATSSubscriber) HistoryByTime added in v0.10.5

func (s *NATSSubscriber) HistoryByTime(ctx context.Context, duration time.Duration) ([]haconnect.HistoryItem, error)

func (*NATSSubscriber) LatestSeq added in v0.0.6

func (s *NATSSubscriber) LatestSeq() uint64

func (*NATSSubscriber) RemoveConsumer added in v0.0.6

func (s *NATSSubscriber) RemoveConsumer(ctx context.Context, name string) error

func (*NATSSubscriber) SeqNotifyCh added in v0.18.0

func (s *NATSSubscriber) SeqNotifyCh() <-chan struct{}

func (*NATSSubscriber) SetDB added in v0.0.13

func (s *NATSSubscriber) SetDB(db *sql.DB)

func (*NATSSubscriber) Start added in v0.0.6

func (s *NATSSubscriber) Start() error

func (*NATSSubscriber) UndoBySeq added in v0.10.5

func (s *NATSSubscriber) UndoBySeq(ctx context.Context, startSeq uint64, filterType haconnect.UndoFilter, filterEntities map[string][]int64) error

func (*NATSSubscriber) UndoByTime added in v0.10.3

func (s *NATSSubscriber) UndoByTime(ctx context.Context, duration time.Duration, filterType haconnect.UndoFilter, filterEntities map[string][]int64) error

type NATSSubscriberConfig added in v0.0.21

type NATSSubscriberConfig struct {
	Node         string
	Durable      string
	NatsConn     *nats.Conn
	Stream       string
	Subject      string
	Policy       string
	DB           *sql.DB
	ConnProvider ConnHooksProvider
	Interceptor  ChangeSetInterceptor
	RowIdentify  RowIdentify
}

type NoopInterceptor added in v0.17.0

type NoopInterceptor struct{}

NoopInterceptor is a no-op ChangeSetInterceptor that allows all changesets. It can be used directly or embedded in custom interceptors that only need to override BeforeApply or AfterApply.

func NewNoopInterceptor added in v0.17.0

func NewNoopInterceptor() *NoopInterceptor

NewNoopInterceptor returns a new NoopInterceptor.

func (*NoopInterceptor) AfterApply added in v0.17.0

func (*NoopInterceptor) AfterApply(*ChangeSet, *sql.Conn, error) error

func (*NoopInterceptor) BeforeApply added in v0.17.0

func (*NoopInterceptor) BeforeApply(*ChangeSet, *sql.Conn) (bool, error)

type NoopPublisher added in v0.0.6

type NoopPublisher struct{}

func NewNoopPublisher added in v0.0.6

func NewNoopPublisher() *NoopPublisher

func (*NoopPublisher) Publish added in v0.0.6

func (p *NoopPublisher) Publish(ctx context.Context, cs *ChangeSet) error

func (*NoopPublisher) Sequence added in v0.0.20

func (p *NoopPublisher) Sequence() uint64

type NoopSnapshotter added in v0.0.6

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

func NewNoopSnapshotter added in v0.0.6

func NewNoopSnapshotter() *NoopSnapshotter

func (*NoopSnapshotter) DB added in v0.11.0

func (s *NoopSnapshotter) DB() *sql.DB

func (*NoopSnapshotter) LatestSnapshot added in v0.0.6

func (s *NoopSnapshotter) LatestSnapshot(ctx context.Context) (uint64, io.ReadCloser, error)

func (*NoopSnapshotter) LatestSnapshotTime added in v0.15.0

func (s *NoopSnapshotter) LatestSnapshotTime() time.Time

func (*NoopSnapshotter) SetDB added in v0.0.13

func (s *NoopSnapshotter) SetDB(_ *sql.DB)

func (*NoopSnapshotter) Start added in v0.0.13

func (s *NoopSnapshotter) Start()

func (*NoopSnapshotter) TakeSnapshot added in v0.0.6

func (s *NoopSnapshotter) TakeSnapshot(ctx context.Context) (sequence uint64, err error)

type NoopSubscriber added in v0.0.6

type NoopSubscriber struct{}

func NewNoopSubscriber added in v0.0.6

func NewNoopSubscriber() *NoopSubscriber

func (*NoopSubscriber) DB added in v0.11.0

func (s *NoopSubscriber) DB() *sql.DB

func (*NoopSubscriber) DeliveredInfo added in v0.0.6

func (*NoopSubscriber) DeliveredInfo(ctx context.Context, name string) (any, error)

func (*NoopSubscriber) HistoryBySeq added in v0.10.5

func (*NoopSubscriber) HistoryBySeq(ctx context.Context, startSeq uint64) ([]haconnect.HistoryItem, error)

func (*NoopSubscriber) HistoryByTime added in v0.10.5

func (*NoopSubscriber) HistoryByTime(ctx context.Context, duration time.Duration) ([]haconnect.HistoryItem, error)

func (*NoopSubscriber) LatestSeq added in v0.0.6

func (s *NoopSubscriber) LatestSeq() uint64

func (*NoopSubscriber) RemoveConsumer added in v0.0.6

func (*NoopSubscriber) RemoveConsumer(ctx context.Context, name string) error

func (*NoopSubscriber) SetDB added in v0.0.13

func (s *NoopSubscriber) SetDB(db *sql.DB)

func (*NoopSubscriber) Start added in v0.0.6

func (s *NoopSubscriber) Start() error

func (*NoopSubscriber) UndoBySeq added in v0.10.5

func (*NoopSubscriber) UndoBySeq(ctx context.Context, startSeq uint64, filter haconnect.UndoFilter, filterEntities map[string][]int64) error

func (*NoopSubscriber) UndoByTime added in v0.10.3

func (*NoopSubscriber) UndoByTime(ctx context.Context, duration time.Duration, filter haconnect.UndoFilter, filterEntities map[string][]int64) error

type ObservabilityStatus added in v0.15.0

type ObservabilityStatus struct {
	Status               string            `json:"status"`
	Ready                bool              `json:"ready"`
	NodeName             string            `json:"node_name"`
	ReplicationID        string            `json:"replication_id"`
	Leader               bool              `json:"leader"`
	LeaderTarget         string            `json:"leader_target,omitempty"`
	NATSConfigured       bool              `json:"nats_configured"`
	NATSConnected        bool              `json:"nats_connected"`
	NATSStatus           string            `json:"nats_status"`
	PublishedSequence    uint64            `json:"published_sequence"`
	AppliedSequence      uint64            `json:"applied_sequence"`
	ReplicationLag       uint64            `json:"replication_lag_messages"`
	ReplicationLagByNode map[string]uint64 `json:"replication_lag_by_node"`
	LastSnapshotTime     *time.Time        `json:"last_snapshot_time,omitempty"`
	ObservabilityErrors  []string          `json:"observability_errors,omitempty"`
}

type Option

type Option func(*Connector)

func NameToOptions added in v0.0.10

func NameToOptions(name string, baseDriver string) (string, []Option, error)

func WithAsyncPublisher added in v0.0.15

func WithAsyncPublisher() Option

func WithAutoStart added in v0.1.0

func WithAutoStart(enabled bool) Option

func WithBackupFn added in v0.18.3

func WithBackupFn(fn BackupFn) Option

func WithCDCPublisher

func WithCDCPublisher(p CDCPublisher) Option

func WithChangeSetInterceptor added in v0.0.6

func WithChangeSetInterceptor(interceptor ChangeSetInterceptor) Option

func WithClusterSize added in v0.1.1

func WithClusterSize(size int) Option

func WithDBSnapshotter added in v0.0.6

func WithDBSnapshotter(snap DBSnapshotter) Option

func WithDeliverPolicy

func WithDeliverPolicy(deliverPolicy string) Option

func WithDisableDDLSync added in v0.0.4

func WithDisableDDLSync() Option

func WithEmbeddedNatsConfig

func WithEmbeddedNatsConfig(cfg *EmbeddedNatsConfig) Option

func WithExtensions

func WithExtensions(extensions ...string) Option

func WithForcePublishBeforeStart added in v0.13.1

func WithForcePublishBeforeStart(enabled bool) Option

func WithGrpcInsecure added in v0.9.2

func WithGrpcInsecure(insecure bool) Option

func WithGrpcPort added in v0.4.5

func WithGrpcPort(port int) Option

func WithGrpcTimeout added in v0.4.7

func WithGrpcTimeout(timeout time.Duration) Option

func WithGrpcToken added in v0.7.0

func WithGrpcToken(token string) Option

func WithLeaderElectionLocalTarget added in v0.1.1

func WithLeaderElectionLocalTarget(localEndpoint string) Option

func WithLeaderProvider added in v0.1.1

func WithLeaderProvider(p LeaderProvider) Option

func WithMetadataRetention added in v0.18.0

func WithMetadataRetention(ttl time.Duration) Option

WithMetadataRetention configures automatic retention and background compaction for internal HA metadata tables (such as ha_lww_versions tombstones and COMMITTED rows in ha_2pc_transactions).

func WithName

func WithName(name string) Option

func WithNatsOptions

func WithNatsOptions(options ...nats.Option) Option

func WithOpenTelemetry added in v0.15.0

func WithOpenTelemetry(meterProvider metric.MeterProvider, tracerProvider trace.TracerProvider) Option

WithOpenTelemetry enables instrumentation using the supplied providers. A nil provider uses the corresponding global OpenTelemetry provider.

func WithProxiedDB added in v0.11.4

func WithProxiedDB(db *sql.DB) Option

func WithProxiedPositionProvider added in v0.11.8

func WithProxiedPositionProvider(provider ProxiedPositionProvider) Option

func WithPublisherTimeout

func WithPublisherTimeout(timeout time.Duration) Option

func WithQueryRouter added in v0.5.5

func WithQueryRouter(re *regexp.Regexp) Option

func WithReplicas

func WithReplicas(replicas int) Option

func WithReplicationID added in v0.3.0

func WithReplicationID(id string) Option

func WithReplicationPublisher added in v0.3.0

func WithReplicationPublisher(pub Publisher) Option

func WithReplicationStream added in v0.0.9

func WithReplicationStream(stream string) Option

func WithReplicationSubscriber added in v0.3.0

func WithReplicationSubscriber(sub Subscriber) Option

func WithReplicationURL

func WithReplicationURL(url string) Option

func WithRowIdentify added in v0.0.21

func WithRowIdentify(i RowIdentify) Option

func WithSnapshotInterval

func WithSnapshotInterval(interval time.Duration) Option

func WithStreamMaxAge

func WithStreamMaxAge(maxAge time.Duration) Option

func WithWaitFor added in v0.0.4

func WithWaitFor(ch chan struct{}) Option

type OutboxPublisher added in v0.14.0

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

func NewAsyncNATSPublisher added in v0.0.15

func NewAsyncNATSPublisher(nc *nats.Conn, subject string, timeout time.Duration, streamConfig *jetstream.StreamConfig) (*OutboxPublisher, error)

func NewOutboxPublisher added in v0.14.0

func NewOutboxPublisher(publisher Publisher, subject string) *OutboxPublisher

func (*OutboxPublisher) BindLocalDB added in v0.14.0

func (p *OutboxPublisher) BindLocalDB(db *sql.DB) error

BindLocalDB configures the origin database used to persist outbox records.

func (*OutboxPublisher) Close added in v0.14.0

func (p *OutboxPublisher) Close() error

func (*OutboxPublisher) PrepareTwoPhaseCommit added in v0.14.0

func (p *OutboxPublisher) PrepareTwoPhaseCommit(_ context.Context, cs *ChangeSet) (PreparedTwoPhaseCommit, error)

func (*OutboxPublisher) Publish added in v0.14.0

func (p *OutboxPublisher) Publish(ctx context.Context, cs *ChangeSet) error

func (*OutboxPublisher) SeqNotifyCh added in v0.18.0

func (p *OutboxPublisher) SeqNotifyCh() <-chan struct{}

func (*OutboxPublisher) Sequence added in v0.14.0

func (p *OutboxPublisher) Sequence() uint64

func (*OutboxPublisher) SequenceRange added in v0.16.2

func (p *OutboxPublisher) SequenceRange() (uint64, uint64)

type PreparedTwoPhaseCommit added in v0.13.17

type PreparedTwoPhaseCommit interface {
	RecordCommitDecision(context.Context, TwoPhaseCommitDecisionWriter) error
	Commit(context.Context) error
	Abort() error
	ResolveCommit(context.Context) (bool, error)
	Close()
}

PreparedTwoPhaseCommit finalizes or aborts a transaction after remote preparation.

type ProxiedPositionProvider added in v0.11.8

type ProxiedPositionProvider interface {
	SourcePosition(context.Context) (uint64, error)
	ReplicaPosition(context.Context) (uint64, error)
}

type ProxiedQuerierExecer added in v0.16.0

type ProxiedQuerierExecer interface {
	ExecContext(ctx context.Context, query string, args ...any) (sql.Result, error)
	QueryContext(ctx context.Context, query string, args ...any) (*sql.Rows, error)
}

type Publisher added in v0.3.0

type Publisher interface {
	Publish(ctx context.Context, cs *ChangeSet) error
	Sequence() uint64
}

type RowIdentify added in v0.0.21

type RowIdentify string
const (
	PK    RowIdentify = "pk"
	Rowid RowIdentify = "rowid"
	Full  RowIdentify = "full"
)

type SQLiteConn added in v0.16.0

type SQLiteConn interface {
	driver.Conn
	driver.ConnBeginTx
	driver.ConnPrepareContext
	Deserialize(b []byte, schema string) error
}

func RawSQLiteConn added in v0.16.0

func RawSQLiteConn(conn *sql.Conn) (SQLiteConn, error)

type SQLiteHooksAdapter added in v0.16.0

type SQLiteHooksAdapter interface {
	WrapConn(c driver.Conn, connector *Connector) (SQLiteConn, error)
	EnableHooks(conn SQLiteConn, cb HookCallbacks)
	DisableHooks(conn SQLiteConn)
}

type SequenceNotifier added in v0.18.0

type SequenceNotifier interface {
	SeqNotifyCh() <-chan struct{}
}

SequenceNotifier is an optional interface implemented by Publishers and Subscribers that broadcast a channel close whenever their sequence advances, avoiding busy polling.

type SequenceProvider

type SequenceProvider interface {
	LatestSeq() uint64
}

type Statement

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

func Parse

func Parse(ctx context.Context, sql string) ([]*Statement, error)

func ParseStatement added in v0.0.4

func ParseStatement(ctx context.Context, source string) (*Statement, error)

func UnverifiedStatement added in v0.0.12

func UnverifiedStatement(source string, hasDistinct bool,
	hasReturning bool, typ string, parameters []string, columns []string,
	ddl bool, hasIfExists bool, hasModifier bool,
	modifiesDatabase bool, aggregateFunctions map[int]*sql.Call) *Statement

func (*Statement) AggregateFunctions added in v0.6.5

func (s *Statement) AggregateFunctions() map[int]*sql.Call

func (*Statement) Begin

func (s *Statement) Begin() bool

func (*Statement) Columns

func (s *Statement) Columns() []string

func (*Statement) Commit

func (s *Statement) Commit() bool

func (*Statement) DDL

func (s *Statement) DDL() bool

func (*Statement) HasDistinct

func (s *Statement) HasDistinct() bool

func (*Statement) HasReturning

func (s *Statement) HasReturning() bool

func (*Statement) IsCreateTable

func (s *Statement) IsCreateTable() bool

func (*Statement) IsDelete

func (s *Statement) IsDelete() bool

func (*Statement) IsExplain

func (s *Statement) IsExplain() bool

func (*Statement) IsInsert

func (s *Statement) IsInsert() bool

func (*Statement) IsSelect

func (s *Statement) IsSelect() bool

func (*Statement) IsUpdate

func (s *Statement) IsUpdate() bool

func (*Statement) Limit added in v0.5.9

func (s *Statement) Limit() int

func (*Statement) ModifiesDatabase added in v0.0.12

func (s *Statement) ModifiesDatabase() bool

func (*Statement) OrderBy added in v0.5.6

func (s *Statement) OrderBy() []string

func (*Statement) Parameters

func (s *Statement) Parameters() []string

func (*Statement) RewriteQueryToAggregate added in v0.6.5

func (s *Statement) RewriteQueryToAggregate() (query string, aggregateFunctions map[int]*sql.Call, newColumns map[int]int, err error)

func (*Statement) Rollback

func (s *Statement) Rollback() bool

func (*Statement) Source

func (s *Statement) Source() string

func (*Statement) SourceWithIfExists added in v0.0.10

func (s *Statement) SourceWithIfExists() string

func (*Statement) Type

func (s *Statement) Type() string

func (*Statement) Visit added in v0.6.0

func (s *Statement) Visit(n sql.Node) (w sql.Visitor, node sql.Node, err error)

func (*Statement) VisitEnd added in v0.6.0

func (s *Statement) VisitEnd(n sql.Node) (sql.Node, error)

type StaticLeader added in v0.1.0

type StaticLeader struct {
	Target string
}

func (*StaticLeader) IsLeader added in v0.1.0

func (s *StaticLeader) IsLeader() bool

func (*StaticLeader) IsReady added in v0.15.0

func (s *StaticLeader) IsReady() bool

func (*StaticLeader) Ready added in v0.1.1

func (s *StaticLeader) Ready() chan struct{}

func (*StaticLeader) RedirectTarget added in v0.1.0

func (s *StaticLeader) RedirectTarget() string

type Subscriber added in v0.3.0

type Subscriber interface {
	TxSeqTracker
	DB() *sql.DB
	SetDB(*sql.DB)
	Start() error
	RemoveConsumer(ctx context.Context, name string) error
	DeliveredInfo(ctx context.Context, name string) (any, error)
	HistoryBySeq(ctx context.Context, startSeq uint64) ([]haconnect.HistoryItem, error)
	HistoryByTime(ctx context.Context, duration time.Duration) ([]haconnect.HistoryItem, error)
	UndoBySeq(ctx context.Context, startSeq uint64, filterType haconnect.UndoFilter, filterEntities map[string][]int64) error
	UndoByTime(ctx context.Context, duration time.Duration, filterType haconnect.UndoFilter, filterEntities map[string][]int64) error
}

type TwoPhaseCommitDecisionWriter added in v0.13.17

type TwoPhaseCommitDecisionWriter func(context.Context, string, ...any) error

TwoPhaseCommitDecisionWriter records the commit decision in the origin transaction.

type TwoPhaseCommitPreparer added in v0.13.17

type TwoPhaseCommitPreparer interface {
	PrepareTwoPhaseCommit(context.Context, *ChangeSet) (PreparedTwoPhaseCommit, error)
}

TwoPhaseCommitPreparer starts the remote prepare phase for an origin transaction.

type TwoPhaseCommitPublisher added in v0.12.1

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

func NewTwoPhaseCommitPublisher added in v0.12.1

func NewTwoPhaseCommitPublisher(workersKeys map[string]string, timeout time.Duration) (*TwoPhaseCommitPublisher, error)

func (*TwoPhaseCommitPublisher) BindLocalDB added in v0.13.17

func (p *TwoPhaseCommitPublisher) BindLocalDB(db *sql.DB) error

BindLocalDB configures the origin database used to persist and recover decisions.

func (*TwoPhaseCommitPublisher) Close added in v0.18.0

func (p *TwoPhaseCommitPublisher) Close() error

func (*TwoPhaseCommitPublisher) PrepareTwoPhaseCommit added in v0.13.17

func (p *TwoPhaseCommitPublisher) PrepareTwoPhaseCommit(ctx context.Context, cs *ChangeSet) (PreparedTwoPhaseCommit, error)

PrepareTwoPhaseCommit prepares each configured remote participant concurrently.

func (*TwoPhaseCommitPublisher) Publish added in v0.12.1

func (p *TwoPhaseCommitPublisher) Publish(ctx context.Context, cs *ChangeSet) (err error)

func (*TwoPhaseCommitPublisher) RecoverTwoPhaseCommits added in v0.13.17

func (p *TwoPhaseCommitPublisher) RecoverTwoPhaseCommits(ctx context.Context) error

RecoverTwoPhaseCommits replays durable local decisions before new transactions begin.

func (*TwoPhaseCommitPublisher) Sequence added in v0.12.1

func (p *TwoPhaseCommitPublisher) Sequence() uint64

type TxSeqTracker added in v0.4.8

type TxSeqTracker interface {
	LatestSeq() uint64
}

type TxSeqTrackerProvider added in v0.4.8

type TxSeqTrackerProvider func() TxSeqTracker

type WriterPublisher added in v0.0.6

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

func NewWriterPublisher added in v0.0.6

func NewWriterPublisher(w io.Writer, serializer ChangeSetSerializer) *WriterPublisher

func (*WriterPublisher) Publish added in v0.0.6

func (p *WriterPublisher) Publish(ctx context.Context, cs *ChangeSet) error

func (*WriterPublisher) Sequence added in v0.0.20

func (p *WriterPublisher) Sequence() uint64

Directories

Path Synopsis
api

Jump to

Keyboard shortcuts

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