Files
go/struct_map.go
zeekay 22b3f5ce2b hanzo-ds/go: branded datastore client, rebased on clickhouse-go v2.44.0
Feature-complete v2.44.0 (lib/churl, lib/col, BFloat16, QBit, scanTypeDuration,
Options.Logger *slog.Logger) — fixes the [email protected].0 downgrade RED caught.
Package datastore, module github.com/hanzo-ds/go, depends only on hanzo-ds/native.
Wire strings preserved VERBATIM (X-ClickHouse-* headers, sql.Register("clickhouse"),
clickhouse:// DSN, ClientName="clickhouse-go") — consistent with native.
2026-07-10 13:11:20 -07:00

95 lines
1.8 KiB
Go

package datastore
import (
"fmt"
"reflect"
"sync"
)
type structMap struct {
cache sync.Map
}
func (m *structMap) Map(op string, columns []string, s any, ptr bool) ([]any, error) {
v := reflect.ValueOf(s)
if v.Kind() != reflect.Ptr {
return nil, &OpError{
Op: op,
Err: fmt.Errorf("must pass a pointer, not a value, to %s destination", op),
}
}
if v.IsNil() {
return nil, &OpError{
Op: op,
Err: fmt.Errorf("nil pointer passed to %s destination", op),
}
}
t := reflect.TypeOf(s)
if v = reflect.Indirect(v); t.Kind() == reflect.Ptr {
t = t.Elem()
}
if v.Kind() != reflect.Struct {
return nil, &OpError{
Op: op,
Err: fmt.Errorf("%s expects a struct dest", op),
}
}
var (
index map[string][]int
values = make([]any, 0, len(columns))
)
switch idx, found := m.cache.Load(t); {
case found:
index = idx.(map[string][]int)
default:
index = structIdx(t)
m.cache.Store(t, index)
}
for _, name := range columns {
idx, found := index[name]
if !found {
return nil, &OpError{
Op: op,
Err: fmt.Errorf("missing destination name %q in %T", name, s),
}
}
switch field := v.FieldByIndex(idx); {
case ptr:
values = append(values, field.Addr().Interface())
default:
values = append(values, field.Interface())
}
}
return values, nil
}
func structIdx(t reflect.Type) map[string][]int {
fields := make(map[string][]int)
for i := 0; i < t.NumField(); i++ {
var (
f = t.Field(i)
name = f.Name
)
if tn := f.Tag.Get("ch"); len(tn) != 0 {
name = tn
}
switch {
case name == "-", len(f.PkgPath) != 0 && !f.Anonymous:
continue
}
switch {
case f.Anonymous:
if f.Type.Kind() != reflect.Ptr {
for k, idx := range structIdx(f.Type) {
fields[k] = append(f.Index, idx...)
}
}
default:
fields[name] = f.Index
}
}
return fields
}