sql

package
v1.0.1 Latest Latest
Warning

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

Go to latest
Published: May 25, 2026 License: AGPL-3.0 Imports: 29 Imported by: 0

Documentation

Overview

Package sql exposes a SQLite-dialect SQL surface over the PostgreSQL wire protocol. It is the scaffolding for a swytch-backed SQL layer; in this phase, SQLite runs in :memory: per connection with no swytch storage wired in.

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrNoSuchTable is returned from vtab / schema read paths when a
	// table name is not registered in the replicated table list.
	ErrNoSuchTable = errors.New("sql: no such table")

	// ErrTableExists is returned from DDL when CREATE TABLE targets a
	// name already in the registry.
	ErrTableExists = errors.New("sql: table already exists")

	// ErrNoSuchIndex is returned from index load/drop paths when the
	// index name is not registered.
	ErrNoSuchIndex = errors.New("sql: no such index")

	// ErrNoSuchView is returned from view load/drop paths when the
	// view name is not registered in the replicated view list.
	ErrNoSuchView = errors.New("sql: no such view")

	// ErrViewExists is returned from CREATE VIEW when the name is
	// already taken by another view. Table/view name collisions
	// surface as "sql: table already exists" via the parent pathway.
	ErrViewExists = errors.New("sql: view already exists")
)
View Source
var ErrUniqueViolation = errors.New("sql: unique constraint violation")

ErrUniqueViolation is returned from write paths when an INSERT or UPDATE would put two rows under the same value of a UNIQUE index.

View Source
var Version = "dev"

Functions

func Evaluate

func Evaluate(p *Predicate, row *RowWrite) bool

Evaluate reports whether the given row satisfies the predicate under SELECT-filter semantics: TRUE rows would have been observed by the query, so a concurrent write producing such a row constitutes a conflict. UNKNOWN (NULL in comparisons) reduces to "not observed" → no conflict.

func Run

func Run(args []string) error

Run parses CLI arguments and runs the SQL server until terminated by SIGINT/SIGTERM. When a cluster passphrase is supplied the server joins the cluster via beacon.Runtime; otherwise it runs standalone against a single-node effects engine.

Types

type CmpOp

type CmpOp uint8

CmpOp is the comparison operator for Cmp / ColCmp terms.

BETWEEN is deliberately not represented here — the planner decomposes `col BETWEEN x AND y` into `And(Cmp(col ≥ x), Cmp(col ≤ y))`.

const (
	OpEq CmpOp = iota
	OpLt
	OpLe
	OpGt
	OpGe
)

type PredKind

type PredKind uint8

PredKind discriminates the Predicate struct's contents.

const (
	// PredBool is the TRUE/FALSE leaf. Unsupported predicate
	// fragments conservatively expand to Bool(TRUE) so the
	// observation widens rather than missing conflicts.
	PredBool PredKind = iota

	// PredAnd / PredOr are boolean connectives. Short-circuit
	// evaluation with three-valued logic propagates NULL/unknown
	// correctly.
	PredAnd
	PredOr

	// PredNot inverts its child; three-valued with UNKNOWN passing
	// through.
	PredNot

	// PredCmp is `col <op> literal`.
	PredCmp

	// PredColCmp is `col <op> col` — both operands come from the
	// write's tuple.
	PredColCmp

	// PredIsNull is `col IS NULL`. `col IS NOT NULL` is expressed
	// as Not(IsNull(col)).
	PredIsNull
)

type Predicate

type Predicate struct {
	Kind     PredKind
	BoolVal  bool
	Children []Predicate
	Child    *Predicate
	Col      int
	Col2     int
	Op       CmpOp
	Literal  TypedValue
}

Predicate is a node in a boolean expression tree. Exactly one field-group is meaningful, discriminated by Kind:

Bool                       -> BoolVal
And / Or                   -> Children
Not                        -> Child
Cmp                        -> Col, Op, Literal
ColCmp                     -> Col, Op, Col2
IsNull                     -> Col

The struct is intentionally a tagged sum rather than an interface so it round-trips through protobuf without wrapper types and is cheap to evaluate (no type assertions on the hot path).

func PAnd

func PAnd(children ...Predicate) Predicate

func PCmp

func PCmp(col int, op CmpOp, lit TypedValue) Predicate

func PColCmp

func PColCmp(left int, op CmpOp, right int) Predicate

func PFalse

func PFalse() Predicate

func PIsNull

func PIsNull(col int) Predicate

func PNot

func PNot(child Predicate) Predicate

func POr

func POr(children ...Predicate) Predicate

func PTrue

func PTrue() Predicate

type RowWrite

type RowWrite struct {
	Table string
	PK    []byte
	Kind  WriteKind
	Cols  []TypedValue
}

RowWrite is the structured row payload carried by every INSERT/UPDATE/DELETE, consumed by the predicate evaluator at fork-choice time. The Cols slice is ordinal-aligned with the table's column list at the schema tip the observation saw.

For INSERTs, Cols is the new row's state. For UPDATEs, it's the effective post-commit state (carry-forward already applied). For DELETEs, it's the pre-deletion state so an observation like `role = 'admin'` can be evaluated against the row that was there.

type Server

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

Server is a PostgreSQL-wire-compatible SQL server that executes SQLite dialect SQL. Each client connection is assigned its own SQLite connection opened in ":memory:" mode; swytch is the authoritative storage for all tables created through this server.

func NewServer

func NewServer(cfg ServerConfig) (*Server, error)

NewServer builds a Server with the given configuration. It does not begin listening — call Start or StartAsync.

func (*Server) Addr

func (s *Server) Addr() net.Addr

Addr returns the network address the server is listening on, or nil if it has not started yet.

func (*Server) Done

func (s *Server) Done() <-chan error

Done returns a channel that receives the error (if any) from the serve loop when StartAsync was used. Nil when Start was used.

func (*Server) Engine

func (s *Server) Engine() *effects.Engine

Engine returns the underlying effects engine.

func (*Server) Start

func (s *Server) Start() error

Start listens on the configured address and serves until the listener is closed. It blocks.

func (*Server) StartAsync

func (s *Server) StartAsync() error

StartAsync listens on the configured address and serves in a background goroutine. The bound address is available via Addr once this method returns.

func (*Server) Stop

func (s *Server) Stop(ctx context.Context) error

Stop shuts the server down, waiting for in-flight queries to complete or the context to expire. Errors from each step are collected via errors.Join so one failing close doesn't hide others.

type ServerConfig

type ServerConfig struct {
	// Address is the TCP address to listen on (e.g. ":5433").
	Address string

	// AdvertisedVersion is the string sent as server_version during the
	// pg wire startup handshake. Defaults to "17.0 (Swytch)".
	AdvertisedVersion string

	// Logger is an optional *slog.Logger. When nil, slog.Default() is used.
	Logger *slog.Logger

	// Engine is the swytch effects engine used as the storage layer.
	// When nil, NewServer constructs a standalone single-node engine.
	// Shared with other swytch subsystems (cluster, beacon) when
	// provided externally.
	Engine *effects.Engine
	// contains filtered or unexported fields
}

ServerConfig holds configuration for the SQL server.

func DefaultServerConfig

func DefaultServerConfig() ServerConfig

DefaultServerConfig returns a default server configuration.

type TypedValue

type TypedValue struct {
	Kind  sqlite.ColumnType
	Int   int64
	Float float64
	Text  string
	Blob  []byte
}

TypedValue is a tagged literal value. The Kind tag identifies which of the payload fields is meaningful; the evaluator uses it to pick a typed comparison path and to detect type mismatches that should evaluate to UNKNOWN.

func BlobVal

func BlobVal(v []byte) TypedValue

func FloatVal

func FloatVal(v float64) TypedValue

func IntVal

func IntVal(v int64) TypedValue

func NullVal

func NullVal() TypedValue

func TextVal

func TextVal(v string) TypedValue

type WriteKind

type WriteKind uint8

WriteKind identifies which write-path produced a RowWrite.

const (
	WriteInsert WriteKind = iota
	WriteUpdate
	WriteDelete
)

Jump to

Keyboard shortcuts

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