dalgo2clickhouse

package module
v0.0.0-...-8d7a746 Latest Latest
Warning

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

Go to latest
Published: Nov 30, 2026 License: Apache-2.0 Imports: 22 Imported by: 1 module, 2 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

DALgo ClickHouse adapter

A read-only Go adapter for ClickHouse exploration using the official clickhouse-go/v2 driver's database/sql interface and the framework-owned dal.NewDB wrapper.

Linux validation passed dependency resolution, formatting, vet and all nine race-tested unit tests. Real-server integration, publication, CLI integration and web integration remain separate gates; none is established by the unit results or the presence of this code.

Read contract

  • Structured queries read one configured database/table into a DALgo RecordsetReader. Explicit projections/aliases, scalar comparisons, AND/OR, IS NULL/IS NOT NULL, field ordering and positive bounded LIMIT/OFFSET are supported. Tables and columns come from the configuration allowlist; filter values use driver parameters and never enter the generated identifier text.
  • Caller-authored native SQL is an additional, explicitly enabled capability. It uses the ClickHouse credential's permissions, including any permitted functions, external sources and other databases. The structured table/column allowlist does not constrain native SQL. There is no pretend SQL sanitizer.
  • Both paths retain UInt64 integers, decimal.Decimal, DateTime64 timestamps, nullable pointers, arrays, maps and other supported driver scalar/container values without JSON or floating-point conversion. DbType retains the native column type. Unsupported native structs fail explicitly instead of coercing.
  • An operation has one deadline, one leased SQL connection and finite row/value budgets. It fully materializes the result, checks EOF and closes the SQL rows and lease before returning a reader. A stream error, row overflow, byte overflow, empty output column label or unsupported value returns no partial reader. The byte budget accounts for copied native values and container slots; it is not a measurement of wire bytes. Server-side profile limits bound server work and driver buffering separately.
  • MergeTree sorting/primary indexes do not imply unique records. Duplicate rows remain duplicate rows. Duplicate output labels and repeated projections retain their original column order and values. Read them by ordinal index; name-based lookup is ambiguous and a map would collapse columns. Identical structured projections may repeat a label; different expressions with the same output label are refused before I/O, matching ClickHouse alias semantics. Native SQL reaches the server unchanged and backend alias failures remain sealed. Structured projection, predicate and ordering fields are qualified against the actual source table, so a SELECT alias cannot change a source or policy filter. Point Get/Exists/GetMulti, durable record keys, RecordsReader, write sessions, callback transactions and cursors are unsupported. Structured joins, grouping, aggregate expressions, subqueries, membership/array filters, NULL comparisons and wildcard exclusions are refused. Native SQL can express analytics under its separate credential scope.

Credentials and server settings

Use a dedicated least-privilege ClickHouse user with SELECT only on admitted data and required catalog tables. Every operation checks the effective readonly=1 setting on the same leased connection before its statement. A writable account is refused, even for a SELECT. The adapter never implements a transaction by calling ClickHouse's transaction-shaped driver stubs.

The administrator must enforce immutable readonly=1 and throw-on-overflow settings, plus finite read/CPU/memory ceilings. Allow max_execution_time, max_result_rows and max_result_bytes to change in read-only mode only inside finite administrator-owned MIN/MAX constraints. Never make readonly changeable in read-only mode. testdata/init.sql shows the exact synthetic profile prepared for the integration fixture. Production grants and ceilings must be chosen for the application, independently of these synthetic fixtures.

The driver derives max_execution_time from the caller deadline with its own grace period. The adapter also sends result limits and result_overflow_mode throw; incompatible profiles fail closed. Native SQL can request settings within the server profile's bounds, so a profile constraint is essential to bound work even when caller-authored SQL specifies its own settings. Local row and copied-value budgets and caller cancellation remain additional limits.

Caller context values are not passed into private driver query options, so a context cannot smuggle authentication overrides, settings, external tables or logging callbacks. Returned errors omit SQL, credentials, response bodies, endpoint details and driver causes. Driver debug logging is not enabled.

TLS with certificate verification is the default. Unencrypted transport needs an explicit PlaintextLoopback option and a literal loopback address.

Example

This uses a synthetic explore.events table and the disposable fixture account:

db, err := dalgo2clickhouse.NewDB(ctx, dalgo2clickhouse.Config{
    Address: "127.0.0.1:9000", Database: "explore",
    Username: "fixture_reader", Password: "synthetic-reader",
    PlaintextLoopback: true,
    Tables: map[string][]string{"events": {"id", "amount"}},
    MaxRows: 100, MaxBytes: 1 << 20, Timeout: 5 * time.Second,
})
if err != nil { return err }
defer db.(*dalgo2clickhouse.Database).Close()
query := dal.From(dal.NewRootCollectionRef("events", "")).NewQuery().
    Limit(10).OrderBy(dal.AscendingField("id")).SelectIntoRecordset()
reader, err := db.ExecuteQueryToRecordsetReader(ctx, query)
if err != nil { return err }
defer reader.Close()

For native SQL, enable Config.NativeSQL deliberately and obtain dal.As[dalgo2clickhouse.NativeQuerier](db). QueryNative(ctx, sql, args...) accepts SQL and scalar parameters under the server credential. Its result must fit the configured limits; SELECT ... LIMIT n is useful, but unbounded SQL is also subject to server and materialization limits and is never silently cut off.

Pass named parameters as sql.Named("id", value) and use the driver's typed server placeholders such as {id:UInt64} or {amount:Decimal(38,9)}. Names remain names, SQL is passed unchanged to the pinned driver, and positional and named styles cannot be mixed. Duplicate, malformed or nested names are refused before I/O. Exact integer json.Number tokens and *big.Int values fit the ClickHouse Int256/UInt256 range; fractional/exponent JSON numbers and decimal.Decimal values fit at most 76 decimal digits and scale 76. Exact values are copied without passing through floats. Non-finite floats, unsafe integer-valued floats, nested values and custom Valuers/Stringers are refused. An explicit nil native parameter binds SQL NULL; a structured null comparison still requires an IS NULL condition.

dal.As[dalgo2clickhouse.StructuredQueryValidator](db) exposes the pure ValidateStructuredQuery preflight, backed by the execution compiler. Policy preparers must guard both the original AST and the effective AST. A valid dal.Param is accepted only in a supported comparison's scalar value position for this preflight; it must be substituted before execution, which rejects unresolved parameters before acquiring a connection. Preflight neither performs I/O nor authorizes the read, native SQL, or a policy bypass.

dal.As[dbschema.SchemaReader](db) exposes permitted tables, ordered columns, native type/default metadata and real non-unique data-skipping index names. ListDatabases reports only the configured database. Constraint/referrer introspection is explicitly unsupported. No primary-key uniqueness is invented.

Prepared validation

Dependency pins are real versions: DALgo v0.96.1, the official Go driver v2.49.0, and the ClickHouse-published image clickhouse/clickhouse-server:26.10.3.7. The fixture pins its published multi-platform index digest sha256:739e099abd1157390960a59e4532d21781d8fde57e6e4151cb920ea02c30b1ce. This is a verified Docker Hub image tag; no matching GitHub stable-release tag is claimed. The Go module checksum file was generated by normal Go tooling in the capped Linux worker. To reproduce its checks there:

GOMAXPROCS=2 GOTOOLCHAIN=local go mod tidy
gofmt -w .
go vet ./...
go test -race -count=1 -coverprofile=coverage.out ./...

With Docker available in the separately admitted integration environment:

bash testdata/integration.sh

That Linux-only script owns one disposable container limited to 2 GiB memory, zero swap, two CPUs and 128 PIDs, with random loopback ports. Its documented global/background worker settings are reduced for this small fixture, including two merge/mutation workers, one streaming-scheduler worker, a concurrency ratio of two and three positive free-entry thresholds of one. The related MergeTree thresholds must fit the executor's four-task capacity. This tuning is a candidate to test, not confirmation that the observed initialization stall is pool starvation. The internal global thread-pool ceiling is now 96 instead of 64 for a causal comparison; the external 128-PID, 2 GiB, zero-swap and two-CPU limits are unchanged. After the real Go tests pass, a bounded read of the owned container's cgroup counters must show zero PID-limit events, OOM events and OOM kills; otherwise the integration check fails despite passing tests. Failure diagnostics include thread-name/wait-channel counts and selected process and cgroup counters without depending on SQL. Metadata-file presence reports database/table metadata persistence without claiming DDL or row insertion completed. A metrics-only listener on port 9363 stays inside the owned container, with no Docker port publication. On failure, a private HTTP capture uses the same 2 MiB/five-second limits and prints only the three validated global-thread counters when available; missing or malformed counters are a diagnostic failure, not occupancy evidence. The existing teardown removes this listener with its container. Actual startup under those limits remains a mandatory CI check. It initializes synthetic data and a read-only profile, runs the real driver tests and removes only its own container. Missing server configuration fails the integration tests. The required real-clickhouse CI job tests native write/settings refusals, data grants, UInt64/Decimal/DateTime64/array/map/null fidelity, duplicate rows, schema scope, injection, limits and cancellation. Unit tests exercise SQL planning, native copying and controlled stream/error lifetimes; they do not claim server behavior. Do not land while real-server CI is red or has not run.

Consumer integration is still required

DataTug CLI's accesspolicies.Run and pkg/secureread currently consume RecordsReader. This adapter intentionally returns anonymous recordsets, so it is not an automatic drop-in for those paths. A separate policy-aware anonymous recordset/native-SQL execution path must be integrated under the existing policy/server read refusal rules. Do not fabricate stable keys or bypass accesspolicies to connect it. CLI and web wiring are not implemented here.

Upstream references: Go client, HTTP interface, settings constraints.

Documentation

Overview

Package dalgo2clickhouse provides bounded, read-only ClickHouse exploration.

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrConfig           = errors.New("clickhouse: invalid configuration")
	ErrClosed           = errors.New("clickhouse: database closed")
	ErrBackend          = errors.New("clickhouse: read failed")
	ErrLimit            = errors.New("clickhouse: operation budget exceeded")
	ErrReadOnlyRequired = errors.New("clickhouse: server account must enforce readonly=1")
	ErrUnsupportedValue = errors.New("clickhouse: unsupported native value")
)

Functions

func NewDB

func NewDB(ctx context.Context, cfg Config) (dal.DB, error)

NewDB validates configuration without network I/O. Every operation subsequently verifies readonly=1 on its own leased connection before sending its statement.

Types

type Config

type Config struct {
	Address   string
	Database  string
	Username  string
	Password  string
	Tables    map[string][]string
	NativeSQL bool
	HTTP      bool
	// PlaintextLoopback permits unencrypted transport only to a literal loopback IP.
	PlaintextLoopback bool
	Timeout           time.Duration
	MaxRows           int
	MaxBytes          int64
}

Config contains no DSN, SQL settings, debug callbacks or arbitrary transports. Tables is the structured-query/catalog allowlist in Database; each value is an allowed column list (empty means all columns visible to the credential). NativeSQL is a separate, credential-scoped permission and is disabled by default.

func (Config) GoString

func (c Config) GoString() string

func (Config) String

func (Config) String() string

type Database

type Database struct {
	dal.DB
	// contains filtered or unexported fields
}

Database embeds the framework-owned sealed DB. Close owns its private pool; callers never lend a pool whose transaction/write capabilities could leak.

func (*Database) Close

func (d *Database) Close() error

func (*Database) DescribeCollection

func (d *Database) DescribeCollection(ctx context.Context, ref *dal.CollectionRef) (*dbschema.CollectionDef, error)

func (*Database) ListCollections

func (d *Database) ListCollections(ctx context.Context, parent *record.Key) ([]dal.CollectionRef, error)

func (*Database) ListConstraints

func (d *Database) ListConstraints(ctx context.Context, ref *dal.CollectionRef) ([]dbschema.ConstraintDef, error)

func (*Database) ListDatabases

func (d *Database) ListDatabases(ctx context.Context) ([]string, error)

ListDatabases reports only the configured database, and only if the server returns it. It does not enumerate databases outside the structured scope.

func (*Database) ListIndexes

func (d *Database) ListIndexes(ctx context.Context, ref *dal.CollectionRef) ([]dbschema.IndexDef, error)

ListIndexes reports real data-skipping index names as non-unique. Its native expressions are not guessed into portable field lists.

func (*Database) ListReferrers

func (d *Database) ListReferrers(ctx context.Context, ref *dal.CollectionRef) ([]dbschema.Referrer, error)

func (*Database) QueryNative

func (d *Database) QueryNative(ctx context.Context, statement string, args ...any) (dal.RecordsetReader, error)

func (*Database) ValidateStructuredQuery

func (d *Database) ValidateStructuredQuery(query dal.Query) error

ValidateStructuredQuery runs the execution compiler against this database's immutable relation/column scope and bounds. A valid dal.Param may occur only in a supported comparison's scalar value position, so policy preparers can guard the original AST before substitution as well as the effective AST. Execution still refuses unresolved parameters before I/O. This method acquires no connection, changes no query, and neither authorizes nor executes a policy.

type NativeQuerier

type NativeQuerier interface {
	QueryNative(context.Context, string, ...any) (dal.RecordsetReader, error)
}

NativeQuerier is deliberately separate from structured table/column allowlists. SQL is authored by the caller, not sanitized by this adapter. The configured server credential/profile is its authority boundary, including table functions.

type StructuredQueryValidator

type StructuredQueryValidator interface {
	ValidateStructuredQuery(dal.Query) error
}

StructuredQueryValidator is an optional, pure preflight capability. A policy preparer must validate both the original AST and the effective AST with the same method before executing either. It does not authorize native SQL.

Jump to

Keyboard shortcuts

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