xb

package module
v1.4.2 Latest Latest
Warning

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

Go to latest
Published: Dec 21, 2025 License: Apache-2.0 Imports: 9 Imported by: 0

README

xb (eXtensible Builder)

OSCS Status workflow build GitHub tag Go Report Card

Languages: English | 中文

xb is an AI-first SQL/JSON builder for relational + vector databases. One fluent API builds:

  • SQL for database/sql, sqlx, gorm, any raw driver
  • JSON for Qdrant (Recommend / Discover / Scroll) and other vector stores
  • Hybrid pipelines that mix SQL tables with vector similarity

Everything flows through Custom() + Build() so the surface stays tiny even as capabilities grow.

Notes

  • Persistence structs mirror the database schema, so numeric primary keys can stay as plain values.
  • Request/filter DTOs should declare non-primary numeric and boolean fields as pointers to distinguish “unset” from “0/false” and to leverage autobypass logic.
  • Need to bypass optimizations? Use X("...") to inject raw SQL (the clause will never be auto-skipped), and pick explicit JOIN helpers (e.g., JOIN(NON_JOIN) or custom builders) when you want to keep every JOIN even if it looks redundant. For BuilderX, call WithoutOptimization() to disable the JOIN/CTE optimizer entirely.
  • For non-functional control flow inside fluent chains, use Any(func(*BuilderX)) to run loops or helper functions without breaking chaining, and Bool(func() bool, func(*CondBuilder)) to conditionally add blocks while reusing the auto-filtered DSL.

Highlights

  • Unified vector entryJsonOfSelect() now covers all Qdrant search/recommend/discover/scroll flows. Legacy ToQdrant*JSON() methods were retired.
  • Composable SQLWith/WithRecursive and UNION(kind, fn) let you express ClickHouse-style analytics directly in Go.
  • Smart condition DSL — auto-filter nil/zero, guard rails via InRequired, raw expressions via X(), reusable subqueries via CondBuilderX.Sub(), and inline conditional blocks.
  • Adaptive JOIN plannerFromX + JOIN(kind) skip meaningless joins automatically (e.g., empty ON blocks), keeping SQL lean.
  • Observability-firstMeta(func) plus interceptors carry TraceID/UserID across builder stages.
  • AI-assisted maintenance — code, tests, docs co-authored by AI and reviewed by humans every release.

Quickstart

Build SQL
package main

import "github.com/fndome/xb"

type Cat struct {
    ID    uint64   `db:"id"`
    Name  string   `db:"name"`
    Age   *uint    `db:"age"`
    Price *float64 `db:"price"`
}

func main() {
    built := xb.Of(&Cat{}).
        Eq("status", 1).
        Gte("age", 3).
        Build()

    sql, args, _ := built.SqlOfSelect()
    // SELECT * FROM t_cat WHERE status = ? AND age >= ?
    _ = sql
    _ = args
}
queryVector := xb.Vector{0.1, 0.2, 0.3}

json, err := xb.Of(&CodeVector{}).
    Custom(
        xb.NewQdrantBuilder().
            Recommend(func(rb *xb.RecommendBuilder) {
                rb.Positive(123, 456).Negative(789).Limit(20)
            }).
            Build(),
    ).
    Eq("language", "golang").
    VectorSearch("embedding", queryVector, 10).
    Build().
    JsonOfSelect()

if err != nil {
    panic(err)
}
// POST json to /collections/{name}/points/recommend

Advanced Capabilities

CTE + UNION pipelines
report := xb.Of("recent_orders").
    With("recent_orders", func(sb *xb.BuilderX) {
        sb.From("orders o").
            Select("o.id", "o.user_id").
            Gt("o.created_at", since30Days)
    }).
    WithRecursive("team_hierarchy", func(sb *xb.BuilderX) {
        sb.From("users u").
            Select("u.id", "u.manager_id").
            Eq("u.active", true)
    }).
    UNION(xb.ALL, func(sb *xb.BuilderX) {
        sb.From("archived_orders ao").
            Select("ao.id", "ao.user_id")
    }).
    Meta(func(meta *interceptor.Metadata) {
        meta.TraceID = traceID
        meta.Set("source", "dashboard")
    }).
    Build()

sql, args, _ := report.SqlOfSelect()
JOIN builder with subqueries
builder := xb.X().
    Select("p.id", "p.weight").
    FromX(func(fb *xb.FromBuilder) {
        fb.Sub(func(sb *xb.BuilderX) {
            sb.Select("id", "type").
                From("t_pet").
                Gt("id", 10000)
        }).As("p").
            JOIN(xb.INNER).Of("t_dog").As("d").On("d.pet_id = p.id").
            JOIN(xb.LEFT).Of("t_cat").As("c").On("c.pet_id = p.id").
            Cond(func(on *xb.ON) {
					on.Gt("p.weight", 10)
				})
    }).
    Ne("p.type", "PIG")

sql, args, _ := builder.Build().SqlOfSelect()
Qdrant Recommend / Discover / Scroll
  • Configure via NewQdrantBuilder().Recommend(...).Build() / Discover(...) / ScrollID(...).
  • JsonOfSelect() inspects builder state and emits the correct JSON schema.
  • Compatible with diversity helpers (WithHashDiversity, WithMinDistance) and standard filters.
Interceptors & Metadata
  • Register global BeforeBuild / AfterBuild hooks (see xb/interceptor).
  • Meta(func) injects metadata before hooks run — perfect for tracing, tenancy, or experiments.
Dialect & Custom
  • Dialects (dialect.go) let you swap quoting rules, placeholder styles, and vendor-specific predicates without rewriting builders — see doc/en/DIALECT_CUSTOM_DESIGN.md / doc/cn/DIALECT_CUSTOM_DESIGN.md.
  • Custom() is the escape hatch for vector DBs and bespoke backends: plug in Custom implementations, emit JSON via JsonOfSelect(), or mix SQL + vector calls in one fluent chain. Deep dives live in doc/en/CUSTOM_VECTOR_DB_GUIDE.md / doc/cn/CUSTOM_VECTOR_DB_GUIDE.md.
  • Need Oracle/Milvus/other dialects? Implement a tiny interface Custom, register it once, and the fluent chains instantly start outputting those drivers’ SQL/JSON schemas without forking the builder core.

Documentation

Topic English Chinese
Overview & Index doc/en/README.md doc/cn/README.md
Quickstart doc/en/QUICKSTART.md doc/cn/QUICKSTART.md
Qdrant Guide doc/en/QDRANT_GUIDE.md doc/cn/QDRANT_GUIDE.md
Vector Guide doc/en/VECTOR_GUIDE.md doc/cn/VECTOR_GUIDE.md
Custom Interface doc/en/CUSTOM_INTERFACE.md doc/cn/CUSTOM_INTERFACE.md
Auto-filter (nil/0 skip) doc/en/ALL_FILTERING_MECHANISMS.md doc/cn/FILTERING.md
Join optimization doc/en/CUSTOM_JOINS_GUIDE.md (coming soon)
AI Application Starter doc/en/AI_APPLICATION.md doc/cn/AI_APPLICATION.md

We are migrating docs into doc/en/ + doc/cn/. Legacy files remain under doc/ until the move completes.


Contributing

We welcome issues, discussions, PRs!

Before opening a PR:

  1. Run go test ./...
  2. Update docs/tests related to your change
  3. Describe behavior changes clearly in the PR template

License

Apache License 2.0 — see LICENSE.

Documentation

Overview

Copyright 2025 me.fndo.xb

Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Index

Constants

View Source
const (
	XX       = ""
	AGG      = ""
	SUB      = "SUB"
	AND      = "AND"
	OR       = "OR"
	AND_SUB  = AND
	OR_SUB   = OR
	EQ       = "="
	NE       = "<>"
	GT       = ">"
	LT       = "<"
	GTE      = ">="
	LTE      = "<="
	LIKE     = "LIKE"
	NOT_LIKE = "NOT LIKE"
	IN       = "IN"
	NIN      = "NOT IN"
	IS_NULL  = "IS NULL"
	NON_NULL = "IS NOT NULL"
)
View Source
const (
	VECTOR_SEARCH          = "VECTOR_SEARCH"
	VECTOR_DISTANCE_FILTER = "VECTOR_DISTANCE_FILTER"
)

Vector operators (v0.8.0 added)

View Source
const (
	QDRANT_HNSW_EF         = "QDRANT_HNSW_EF"
	QDRANT_EXACT           = "QDRANT_EXACT"
	QDRANT_SCORE_THRESHOLD = "QDRANT_SCORE_THRESHOLD"
	QDRANT_WITH_VECTOR     = "QDRANT_WITH_VECTOR"
	QDRANT_RECOMMEND       = "QDRANT_RECOMMEND"    // Recommend API (v0.10.0)
	QDRANT_SCROLL          = "QDRANT_SCROLL"       // Scroll API (v0.10.0)
	QDRANT_BATCH_SEARCH    = "QDRANT_BATCH_SEARCH" // Batch Search (v0.10.1)
	QDRANT_DISCOVER        = "QDRANT_DISCOVER"     // Discover API (v0.10.1)
	QDRANT_XX              = "QDRANT_XX"           // User-defined Qdrant-specific parameters
)

Qdrant-specific operators (v0.9.1 added)

Variables

This section is empty.

Functions

func ALL added in v1.2.3

func ALL() string

ALL returns UNION ALL operator

func ASC

func ASC() string

func ASOF

func ASOF() string

func ApplyCommonVectorParams added in v1.1.0

func ApplyCommonVectorParams(bbs []Bb, req VectorDBRequest)

ApplyCommonVectorParams apply all vector database common parameters This function can be reused by all databases (Qdrant, Milvus, Weaviate, etc.)

Parameters:

  • bbs: xb's condition array
  • req: any request object that implements the VectorDBRequest interface

Example:

// Qdrant uses
ApplyCommonVectorParams(built.Conds, qdrantReq)

// Milvus uses
ApplyCommonVectorParams(built.Conds, milvusReq)

func Bool

func Bool(b bool) *bool

func Byte

func Byte(b byte) *byte

func CROSS

func CROSS() string

func DESC

func DESC() string

func DISTINCT added in v1.2.3

func DISTINCT() string

func Eq

func Eq() string

func ExtractCustomParams added in v1.1.0

func ExtractCustomParams(bbs []Bb, customOp string) map[string]interface{}

ExtractCustomParams extract user-defined parameters (common version) Can be reused by all databases (Qdrant, Milvus, Weaviate, etc.)

Parameters:

  • bbs: xb's condition array
  • customOp: custom operator (QDRANT_XX, MILVUS_XX, WEAVIATE_XX, etc.)

Return:

  • map[string]interface{}: extracted user-defined parameters

Example:

// Qdrant uses
customParams := ExtractCustomParams(bbs, QDRANT_XX)

// Milvus uses
customParams := ExtractCustomParams(bbs, MILVUS_XX)

func FULL_OUTER

func FULL_OUTER() string

func Float32

func Float32(f float32) *float32

func Float64

func Float64(f float64) *float64

func GLOBAL

func GLOBAL() string

func Gt

func Gt() string

func Gte

func Gte() string

func INNER

func INNER() string

func Int

func Int(v int) *int

func Int16

func Int16(v int16) *int16

func Int32

func Int32(v int32) *int32

func Int64

func Int64(v int64) *int64

func Int8

func Int8(v int8) *int8

func IsNull

func IsNull() string

func LEFT

func LEFT() string

func Like

func Like() string

func LikeLeft

func LikeLeft() string

func Lt

func Lt() string

func Lte

func Lte() string

func N2s

func N2s(p interface{}) string

func NON_JOIN

func NON_JOIN() string

func Ne

func Ne() string

func NilOrNumber

func NilOrNumber(p interface{}) (bool, interface{})

func NonNull

func NonNull() string

func NotLike

func NotLike() string

func Np2s

func Np2s(p interface{}) (string, bool)

func QdrantDistanceMetric

func QdrantDistanceMetric(metric VectorDistance) string

QdrantDistanceMetric converts distance metric

func RIGHT() string

func Uint

func Uint(v uint) *uint

func Uint64

func Uint64(v uint64) *uint64

Types

type Bb

type Bb struct {
	Op    string
	Key   string
	Value interface{}
	Subs  []Bb
}

type BoolFunc

type BoolFunc func() bool

type BuilderX

type BuilderX struct {
	CondBuilderX
	// contains filtered or unexported fields
}

ToId build sql, like: SELECT DISTINCT f.id FROM foo f INNER_JOIN JOIN (SELECT foo_id FROM bar) b ON b.foo_id = f.id Sql for MySQL, Clickhouse....

@author Sim

func Of

func Of(tableNameOrPo interface{}) *BuilderX

func X

func X() *BuilderX

func (*BuilderX) Agg

func (x *BuilderX) Agg(fn string, vs ...interface{}) *BuilderX

func (*BuilderX) And

func (x *BuilderX) And(f func(cb *CondBuilder)) *BuilderX

func (*BuilderX) Any

func (x *BuilderX) Any(f func(x *BuilderX)) *BuilderX

func (*BuilderX) As

func (x *BuilderX) As(alia string) *BuilderX

func (*BuilderX) Bool

func (x *BuilderX) Bool(preCond BoolFunc, then func(cb *CondBuilder)) *BuilderX

func (*BuilderX) Build

func (x *BuilderX) Build() *Built

func (*BuilderX) Custom added in v1.1.0

func (x *BuilderX) Custom(custom Custom) *BuilderX

Custom sets database-specific configuration

Parameters:

  • custom: Database-specific config (QdrantCustom/MilvusCustom/WeaviateCustom, etc.)

Returns:

  • *BuilderX: Chainable

Example:

// Using QdrantBuilder (recommended)
built := xb.Of(&CodeVector{}).
    Custom(
        xb.NewQdrantBuilder().
            HnswEf(512).
            ScoreThreshold(0.8).
            Build()
    ).
    Insert(...).
    Build()

json, _ := built.JsonOfInsert()  // ⭐ Automatically uses Qdrant

// Direct Custom usage (example: future implementation using Builder pattern)
// built := xb.Of(&User{}).
//     Custom(xb.NewMilvusBuilder().Build()).
//     Insert(...).
//     Build()
//
// json, _ := built.JsonOfInsert()  // ⭐ Automatically uses Milvus

func (*BuilderX) Eq

func (x *BuilderX) Eq(k string, v interface{}) *BuilderX

func (*BuilderX) From

func (x *BuilderX) From(orFromSql string) *BuilderX

func (*BuilderX) FromX

func (x *BuilderX) FromX(f func(fb *FromBuilder)) *BuilderX

func (*BuilderX) GroupBy

func (x *BuilderX) GroupBy(groupBy string) *BuilderX

func (*BuilderX) Gt

func (x *BuilderX) Gt(k string, v interface{}) *BuilderX

func (*BuilderX) Gte

func (x *BuilderX) Gte(k string, v interface{}) *BuilderX

func (*BuilderX) Having

func (x *BuilderX) Having(f func(cb *CondBuilderX)) *BuilderX

func (*BuilderX) In

func (x *BuilderX) In(k string, vs ...interface{}) *BuilderX

func (*BuilderX) InRequired added in v1.2.2

func (x *BuilderX) InRequired(k string, vs ...interface{}) *BuilderX

InRequired required IN condition (panics on empty values) See CondBuilder.InRequired() documentation for details

func (*BuilderX) Insert

func (x *BuilderX) Insert(f func(b *InsertBuilder)) *BuilderX

func (*BuilderX) IsNull

func (x *BuilderX) IsNull(key string) *BuilderX

func (*BuilderX) Last

func (x *BuilderX) Last(last string) *BuilderX

func (*BuilderX) Like

func (x *BuilderX) Like(k string, v string) *BuilderX

func (*BuilderX) LikeLeft

func (x *BuilderX) LikeLeft(k string, v string) *BuilderX

func (*BuilderX) Limit

func (x *BuilderX) Limit(limit int) *BuilderX

Limit sets the number of records to return (for simple queries, not pagination) Supports PostgreSQL and MySQL

func (*BuilderX) Lt

func (x *BuilderX) Lt(k string, v interface{}) *BuilderX

func (*BuilderX) Lte

func (x *BuilderX) Lte(k string, v interface{}) *BuilderX

func (*BuilderX) Meta

func (x *BuilderX) Meta(fn func(meta *interceptor.Metadata)) *BuilderX

Meta configures metadata (chainable) Mainly used to pass through TraceID, TenantID and other context information

func (*BuilderX) Ne

func (x *BuilderX) Ne(k string, v interface{}) *BuilderX

func (*BuilderX) Nin

func (x *BuilderX) Nin(k string, vs ...interface{}) *BuilderX

func (*BuilderX) NonNull

func (x *BuilderX) NonNull(key string) *BuilderX

func (*BuilderX) NotLike

func (x *BuilderX) NotLike(k string, v string) *BuilderX

func (*BuilderX) OR

func (x *BuilderX) OR() *BuilderX

func (*BuilderX) Offset

func (x *BuilderX) Offset(offset int) *BuilderX

Offset sets the number of records to skip (usually used with Limit) Supports PostgreSQL and MySQL

func (*BuilderX) Or

func (x *BuilderX) Or(f func(cb *CondBuilder)) *BuilderX

func (*BuilderX) Paged

func (x *BuilderX) Paged(f func(pb *PageBuilder)) *BuilderX

func (*BuilderX) Select

func (x *BuilderX) Select(resultKeys ...string) *BuilderX

func (*BuilderX) Sort

func (x *BuilderX) Sort(orderBy string, direction Direction) *BuilderX

func (*BuilderX) Sub

func (x *BuilderX) Sub(s string, f func(sb *BuilderX)) *BuilderX

func (*BuilderX) UNION added in v1.2.3

func (x *BuilderX) UNION(kind UNION, fn func(sb *BuilderX)) *BuilderX

UNION combines queries

func (*BuilderX) Update

func (x *BuilderX) Update(f func(ub *UpdateBuilder)) *BuilderX

func (*BuilderX) VectorDistance

func (x *BuilderX) VectorDistance(metric VectorDistance) *BuilderX

VectorDistance sets vector distance metric (BuilderX extension)

Example:

builder.VectorSearch("embedding", vec, 10).
    VectorDistance(xb.L2Distance)

func (*BuilderX) VectorDistanceFilter

func (x *BuilderX) VectorDistanceFilter(
	field string,
	queryVector Vector,
	op string,
	threshold float32,
) *BuilderX

VectorDistanceFilter vector distance filtering (BuilderX extension)

Example:

builder.VectorDistanceFilter("embedding", queryVector, "<", 0.3)

func (*BuilderX) VectorSearch

func (x *BuilderX) VectorSearch(field string, queryVector Vector, topK int) *BuilderX

VectorSearch vector similarity search (BuilderX extension) Same functionality as CondBuilder.VectorSearch(), but returns *BuilderX for chaining

Example:

xb.Of(&CodeVector{}).
    Eq("language", "golang").
    VectorSearch("embedding", queryVector, 10).
    Build().
    SqlOfVectorSearch()

func (*BuilderX) With added in v1.2.3

func (x *BuilderX) With(name string, fn func(sb *BuilderX)) *BuilderX

With defines a common table expression (CTE)

func (*BuilderX) WithDiversity

func (x *BuilderX) WithDiversity(strategy DiversityStrategy, params ...interface{}) *BuilderX

WithDiversity sets diversity parameters (BuilderX extension) ⭐ Core: if database doesn't support, will be automatically ignored

Example:

xb.Of(&CodeVector{}).
    VectorSearch("embedding", vec, 20).
    WithDiversity(xb.DiversityByHash, "semantic_hash").
    Build()

func (*BuilderX) WithHashDiversity

func (x *BuilderX) WithHashDiversity(hashField string) *BuilderX

WithHashDiversity sets hash deduplication (BuilderX extension)

Example:

xb.Of(&CodeVector{}).
    VectorSearch("embedding", vec, 20).
    WithHashDiversity("semantic_hash").
    Build()

func (*BuilderX) WithMMR

func (x *BuilderX) WithMMR(lambda float32) *BuilderX

WithMMR sets MMR algorithm (BuilderX extension)

Example:

xb.Of(&CodeVector{}).
    VectorSearch("embedding", vec, 20).
    WithMMR(0.5).
    Build()

func (*BuilderX) WithMinDistance

func (x *BuilderX) WithMinDistance(minDistance float32) *BuilderX

WithMinDistance sets minimum distance diversity (BuilderX extension)

Example:

xb.Of(&CodeVector{}).
    VectorSearch("embedding", vec, 20).
    WithMinDistance(0.3).
    Build()

func (*BuilderX) WithRecursive added in v1.2.3

func (x *BuilderX) WithRecursive(name string, fn func(sb *BuilderX)) *BuilderX

WithRecursive defines a recursive common table expression (CTE)

func (*BuilderX) WithoutOptimization

func (x *BuilderX) WithoutOptimization() *BuilderX

func (*BuilderX) X

func (x *BuilderX) X(k string, vs ...interface{}) *BuilderX

type Built

type Built struct {
	Delete     bool
	Inserts    *[]Bb
	Updates    *[]Bb
	ResultKeys []string
	Conds      []Bb
	Sorts      []Sort
	Havings    []Bb
	GroupBys   []string
	Aggs       []Bb
	Last       string
	OrFromSql  string
	Fxs        []*FromX
	Svs        []interface{}

	PageCondition *PageCondition

	// ⭐ Database-specific configuration (Dialect + Custom)
	// If nil, defaults to SQL dialect
	Custom      Custom
	LimitValue  int                   // ⭐ LIMIT value (v0.10.1)
	OffsetValue int                   // ⭐ OFFSET value (v0.10.1)
	Meta        *interceptor.Metadata // ⭐ Metadata (v0.9.2)
	Alia        string
	Withs       []WithClause
	Unions      []UnionClause
}

func (*Built) JsonOfDelete added in v1.1.0

func (built *Built) JsonOfDelete() (string, error)

JsonOfDelete generates delete JSON (vector databases) ⭐ Used for delete operations in vector databases like Qdrant/Milvus

func (*Built) JsonOfInsert added in v1.1.0

func (built *Built) JsonOfInsert() (string, error)

JsonOfInsert generates insert JSON (vector databases) ⭐ Used for insert operations in vector databases like Qdrant/Milvus

func (*Built) JsonOfSelect added in v1.1.0

func (built *Built) JsonOfSelect() (string, error)

JsonOfSelect generates query JSON (unified interface) ⭐ Automatically selects database dialect based on Built.Custom (Qdrant/Milvus/Weaviate, etc.)

Returns:

  • JSON string
  • error

Example:

// Qdrant
built := xb.Of("code_vectors").
    Custom(xb.NewQdrantBuilder().Build()).
    VectorSearch(...).
    Build()

json, _ := built.JsonOfSelect()  // ⭐ Automatically uses Qdrant

// Milvus (example: future implementation using Builder pattern)
// built := xb.Of("users").
//     Custom(xb.NewMilvusBuilder().Build()).
//     VectorSearch(...).
//     Build()
//
// json, _ := built.JsonOfSelect()  // ⭐ Automatically uses Milvus

func (*Built) JsonOfUpdate added in v1.1.0

func (built *Built) JsonOfUpdate() (string, error)

JsonOfUpdate generates update JSON (vector databases) ⭐ Used for update operations in vector databases like Qdrant/Milvus

func (*Built) SqlCount added in v1.1.0

func (built *Built) SqlCount() string

SqlCount generates COUNT SQL (for pagination)

Notes:

  • Used to generate COUNT(*) SQL, usually used with SqlData for pagination
  • Custom implementations can call this method to generate count SQL

Returns:

  • string: COUNT SQL

Example:

countSQL := built.SqlCount()
// SELECT COUNT(*) FROM users WHERE age > ?

func (*Built) SqlData added in v1.1.0

func (built *Built) SqlData(vs *[]interface{}, km map[string]string) (string, map[string]string)

SqlData generates data query SQL (SELECT or UPDATE)

Notes:

  • Generates complete SELECT or UPDATE SQL (does not include pagination COUNT SQL)
  • Custom implementations can call this method to generate base SQL

Parameters:

  • vs: parameter list (pointer)
  • km: metadata map

Returns:

  • string: SQL statement
  • map[string]string: metadata

Example:

vs := []interface{}{}
km := make(map[string]string)
sql, meta := built.SqlData(&vs, km)
// SELECT * FROM users WHERE age > ?

func (*Built) SqlInsert added in v1.1.0

func (built *Built) SqlInsert(vs *[]interface{}) string

SqlInsert generates INSERT SQL

Notes:

  • Generates standard INSERT SQL statement
  • Custom implementations can call this method to generate base INSERT SQL

Parameters:

  • vs: parameter list (pointer)

Returns:

  • string: INSERT SQL

Example:

vs := []interface{}{}
sql := built.SqlInsert(&vs)
// INSERT INTO users (name, age) VALUES (?, ?)

func (*Built) SqlOfCond

func (built *Built) SqlOfCond() (string, string, []interface{})

func (*Built) SqlOfDelete

func (built *Built) SqlOfDelete() (string, []interface{})

func (*Built) SqlOfInsert

func (built *Built) SqlOfInsert() (string, []interface{})

func (*Built) SqlOfInsertIgnore added in v1.2.0

func (built *Built) SqlOfInsertIgnore() (string, []interface{})

SqlOfInsertIgnore generates MySQL INSERT IGNORE SQL

Notes:

  • No need to set Custom, call directly
  • Ignores duplicate key errors, doesn't throw exceptions

Returns:

  • string: SQL statement
  • []interface{}: parameter list

Example:

built := xb.Of(user).Insert(func(ib *InsertBuilder) {
    ib.Set("id", 1).Set("name", "John Doe")
}).Build()

sql, args := built.SqlOfInsertIgnore()
// INSERT IGNORE INTO users (id, name) VALUES (?, ?)

func (*Built) SqlOfPage

func (built *Built) SqlOfPage() (string, string, []interface{}, map[string]string)

func (*Built) SqlOfSelect

func (built *Built) SqlOfSelect() (string, []interface{}, map[string]string)

func (*Built) SqlOfUpdate

func (built *Built) SqlOfUpdate() (string, []interface{})

func (*Built) SqlOfUpsert added in v1.2.0

func (built *Built) SqlOfUpsert() (string, []interface{})

SqlOfUpsert generates MySQL UPSERT SQL (INSERT ... ON DUPLICATE KEY UPDATE)

Notes:

  • No need to set Custom, call directly
  • Automatically generates ON DUPLICATE KEY UPDATE clause

Returns:

  • string: SQL statement
  • []interface{}: parameter list

Example:

built := xb.Of(user).Insert(func(ib *InsertBuilder) {
    ib.Set("id", 1).Set("name", "John Doe").Set("age", 18)
}).Build()

sql, args := built.SqlOfUpsert()
// INSERT INTO users (id, name, age) VALUES (?, ?, ?)
// ON DUPLICATE KEY UPDATE name = VALUES(name), age = VALUES(age)

func (*Built) SqlOfVectorSearch

func (built *Built) SqlOfVectorSearch() (string, []interface{})

SqlOfVectorSearch generates vector search SQL Returns: sql, args

Example output:

SELECT *, embedding <-> ? AS distance
FROM code_vectors
WHERE language = ?
ORDER BY distance
LIMIT 10

func (*Built) ToQdrantRequest

func (built *Built) ToQdrantRequest() (*QdrantSearchRequest, error)

ToQdrantRequest builds Qdrant request object ⭐ Public method: for testing and advanced usage

type CondBuilder

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

func (*CondBuilder) And

func (cb *CondBuilder) And(f func(cb *CondBuilder)) *CondBuilder

func (*CondBuilder) Bool

func (cb *CondBuilder) Bool(preCond BoolFunc, f func(cb *CondBuilder)) *CondBuilder

func (*CondBuilder) Eq

func (cb *CondBuilder) Eq(k string, v interface{}) *CondBuilder

func (*CondBuilder) Gt

func (cb *CondBuilder) Gt(k string, v interface{}) *CondBuilder

func (*CondBuilder) Gte

func (cb *CondBuilder) Gte(k string, v interface{}) *CondBuilder

func (*CondBuilder) In

func (cb *CondBuilder) In(k string, vs ...interface{}) *CondBuilder

func (*CondBuilder) InRequired added in v1.2.2

func (cb *CondBuilder) InRequired(k string, vs ...interface{}) *CondBuilder

InRequired required IN condition (panics on empty values) Used for scenarios where filter conditions must be provided to prevent accidentally querying all data

Panic scenarios:

  • Empty slice: InRequired("id") or InRequired("id", []int{}...)
  • nil value: InRequired("id", nil)
  • Zero value: InRequired("id", 0)

Example:

// ✅ Normal usage
ids := []int{1, 2, 3}
xb.Of(&User{}).InRequired("id", toInterfaces(ids)...).Build()

// ❌ Panic: empty slice
ids := []int{}
xb.Of(&User{}).InRequired("id", toInterfaces(ids)...).Build()
// panic: InRequired("id") received empty values, this would match all records

func (*CondBuilder) IsNull

func (cb *CondBuilder) IsNull(key string) *CondBuilder

func (*CondBuilder) Like

func (cb *CondBuilder) Like(k string, v string) *CondBuilder

Like sql: LIKE %value%, Like() default has double %

func (*CondBuilder) LikeLeft

func (cb *CondBuilder) LikeLeft(k string, v string) *CondBuilder

LikeLeft sql: LIKE value%, Like() default has double %, then LikeLeft() remove left %

func (*CondBuilder) Lt

func (cb *CondBuilder) Lt(k string, v interface{}) *CondBuilder

func (*CondBuilder) Lte

func (cb *CondBuilder) Lte(k string, v interface{}) *CondBuilder

func (*CondBuilder) Ne

func (cb *CondBuilder) Ne(k string, v interface{}) *CondBuilder

func (*CondBuilder) Nin

func (cb *CondBuilder) Nin(k string, vs ...interface{}) *CondBuilder

func (*CondBuilder) NonNull

func (cb *CondBuilder) NonNull(key string) *CondBuilder

func (*CondBuilder) NotLike

func (cb *CondBuilder) NotLike(k string, v string) *CondBuilder

func (*CondBuilder) OR

func (cb *CondBuilder) OR() *CondBuilder

func (*CondBuilder) Or

func (cb *CondBuilder) Or(f func(cb *CondBuilder)) *CondBuilder

func (*CondBuilder) VectorDistance

func (cb *CondBuilder) VectorDistance(metric VectorDistance) *CondBuilder

VectorDistance sets vector distance metric Must be called after VectorSearch()

Example:

builder.VectorSearch("embedding", vec, 10).VectorDistance(xb.L2Distance)

func (*CondBuilder) VectorDistanceFilter

func (cb *CondBuilder) VectorDistanceFilter(
	field string,
	queryVector Vector,
	op string,
	threshold float32,
) *CondBuilder

VectorDistanceFilter vector distance filtering Used for: WHERE distance < threshold

Example:

builder.VectorDistanceFilter("embedding", queryVector, "<", 0.3)

Generates SQL:

WHERE (embedding <-> $1) < 0.3

func (*CondBuilder) VectorSearch

func (cb *CondBuilder) VectorSearch(field string, queryVector Vector, topK int) *CondBuilder

VectorSearch vector similarity search field: vector field name queryVector: query vector topK: returns Top-K most similar results

Example:

builder.VectorSearch("embedding", queryVector, 10)

Generates SQL:

ORDER BY embedding <-> $1 LIMIT 10

func (*CondBuilder) WithDiversity

func (cb *CondBuilder) WithDiversity(strategy DiversityStrategy, params ...interface{}) *CondBuilder

WithDiversity chain sets diversity parameters ⭐ Core: if database doesn't support, will be automatically ignored

Example:

builder.VectorSearch("embedding", vec, 20).
    WithDiversity(xb.DiversityByHash, "semantic_hash")

func (*CondBuilder) WithHashDiversity

func (cb *CondBuilder) WithHashDiversity(hashField string) *CondBuilder

WithHashDiversity convenience method: sets hash deduplication

Example:

builder.VectorSearch("embedding", vec, 20).
    WithHashDiversity("semantic_hash")

func (*CondBuilder) WithMMR

func (cb *CondBuilder) WithMMR(lambda float32) *CondBuilder

WithMMR convenience method: sets MMR algorithm

Example:

builder.VectorSearch("embedding", vec, 20).
    WithMMR(0.5)  // lambda = 0.5, balances relevance and diversity

func (*CondBuilder) WithMinDistance

func (cb *CondBuilder) WithMinDistance(minDistance float32) *CondBuilder

WithMinDistance convenience method: sets minimum distance diversity

Example:

builder.VectorSearch("embedding", vec, 20).
    WithMinDistance(0.3)

func (*CondBuilder) X

func (cb *CondBuilder) X(k string, vs ...interface{}) *CondBuilder

X custom SQL fragment (universal supplement)

Used for special scenarios: query zero values, false, or complex SQL expressions

Two usage patterns:

  1. No parameters (recommended): write SQL fragment directly .X("age = 0") .X("is_active = false") .X("YEAR(created_at) = 2024")

  2. With parameters: use placeholders (still filters zero values) .X("name = ?", name) // name="" will be filtered .X("age > ?", age) // age=0 will be filtered ⚠️

⚠️ Important: If you want to query zero values or false, use the no-parameter approach!

Example:

// ✅ Query age = 0
xb.Of("users").X("age = 0").Build()

// ✅ Query is_active = false
xb.Of("users").X("is_active = false").Build()

// ✅ Complex expression
xb.Of("orders").X("total_amt > discount_amt").Build()

// ❌ Wrong: age=0 will be filtered
xb.Of("users").X("age = ?", 0).Build()

// ✅ Correct: write SQL directly
xb.Of("users").X("age = 0").Build()

⚠️ For subqueries, use Sub() method (safer and more flexible):

// ❌ Not recommended: handwritten subquery
.X("user_id IN (SELECT id FROM vip_users)")

// ✅ Recommended: use Sub()
.Sub("user_id IN ?", func(sb *BuilderX) {
    sb.Of(&VipUser{}).Select("id")
})

type CondBuilderX

type CondBuilderX struct {
	CondBuilder
}

func (*CondBuilderX) Sub

func (x *CondBuilderX) Sub(s string, f func(sb *BuilderX)) *CondBuilderX

Sub subquery (type-safe subquery construction)

Used to build nested queries using xb's fluent API instead of handwritten SQL

Parameters:

  • s: SQL template, use ? as subquery placeholder
  • f: subquery construction function

Example:

// ✅ IN subquery
xb.Of("orders").
    Sub("user_id IN ?", func(sb *BuilderX) {
        sb.Of(&VipUser{}).Select("id")
    }).
    Build()
// Generates: SELECT * FROM orders WHERE user_id IN (SELECT id FROM vip_users)

// ✅ EXISTS subquery
xb.Of(&User{}).
    Sub("EXISTS ?", func(sb *BuilderX) {
        sb.Of(&Order{}).
           Select("1").
           X("orders.user_id = users.id")
    }).
    Build()
// Generates: SELECT * FROM users WHERE EXISTS (SELECT 1 FROM orders WHERE orders.user_id = users.id)

// ✅ Complex subquery
xb.Of(&Product{}).
    Sub("price > ?", func(sb *BuilderX) {
        sb.Of(&Product{}).
           Select("AVG(price)").
           Eq("category", "electronics")
    }).
    Build()
// Generates: SELECT * FROM products WHERE price > (SELECT AVG(price) FROM products WHERE category = ?)

Advantages:

  • Type-safe: uses xb API instead of string concatenation
  • High readability: clear nested structure
  • Maintainable: subqueries can also use Eq/In/X and other methods

type Custom added in v1.1.0

type Custom interface {
	// Generate generates query (unified interface)
	// Parameters:
	//   - built: Built object (contains all query conditions)
	// Returns:
	//   - interface{}: string (JSON) or *SQLResult (SQL + Args)
	//   - error
	//
	// Notes:
	//   - Vector databases: returns string (JSON)
	//   - SQL databases: returns *SQLResult (SQL + Args)
	//   - Callers use JsonOfSelect() or SqlOfSelect() for automatic type conversion
	Generate(built *Built) (interface{}, error)
}

Custom database-specific configuration interface Each database implements its own Custom, achieving different behaviors through interface polymorphism

Design principles (v1.1.0):

  • ✅ Unified return type: Generate() returns interface{}
  • ✅ Type flexibility: can be string (JSON) or *SQLResult (SQL)
  • ✅ Zero performance overhead: SQL doesn't need to be wrapped in JSON
  • ✅ Minimal interface: one method handles all databases

Return value types:

  • string: Vector database JSON (Qdrant/Milvus/Weaviate)
  • *SQLResult: SQL database result (PostgreSQL/Oracle/MySQL)

Implementation examples:

// Qdrant (returns JSON string)
type QdrantCustom struct {
    DefaultHnswEf int
}

func (c *QdrantCustom) Generate(built *Built) (interface{}, error) {
    json, err := built.toQdrantJSON()
    return json, err  // ← returns string
}

// Oracle (returns SQLResult)
type OracleCustom struct {
    UseRowNum bool
}

func (c *OracleCustom) Generate(built *Built) (interface{}, error) {
    sql, args, _ := built.toOracleSQL()
    return &SQLResult{SQL: sql, Args: args}, nil  // ← returns *SQLResult
}

Usage examples:

// Qdrant
built := xb.Of("code_vectors").
    Custom(xb.NewQdrantBuilder().Build()).
    Build()

json, _ := built.JsonOfSelect()  // ← automatic type conversion

// Oracle (example: future implementation using Builder pattern)
// built := xb.Of("users").
//     Custom(xb.NewOracleBuilder().Build()).
//     Build()
//
// sql, args, _ := built.SqlOfSelect()  // ← automatic type conversion

type Direction

type Direction func() string

type DiscoverBuilder

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

DiscoverBuilder Discover API builder

func (*DiscoverBuilder) Context

func (db *DiscoverBuilder) Context(ids ...int64) *DiscoverBuilder

Context sets context IDs

func (*DiscoverBuilder) Limit

func (db *DiscoverBuilder) Limit(limit int) *DiscoverBuilder

Limit sets the number of results to return

type DiversityParams

type DiversityParams struct {
	// Enabled whether diversity is enabled
	Enabled bool

	// Strategy diversity strategy
	Strategy DiversityStrategy

	// HashField semantic hash field name (for DiversityByHash)
	// Example: "semantic_hash", "content_hash"
	HashField string

	// MinDistance minimum distance between results (for DiversityByDistance)
	// Example: 0.3 means distance between results is at least 0.3
	MinDistance float32

	// Lambda MMR balance parameter (for DiversityByMMR)
	// Range: 0-1
	// 0 = complete diversity
	// 1 = complete relevance
	// 0.5 = balanced (recommended)
	Lambda float32

	// OverFetchFactor over-fetch factor
	// First fetch TopK * OverFetchFactor results, then apply diversity filtering
	// Default: 5 (fetch 5x results then filter)
	OverFetchFactor int
}

DiversityParams diversity query parameters

type DiversityStrategy

type DiversityStrategy string

DiversityStrategy diversity strategy

const (
	// DiversityByHash deduplication based on semantic hash
	DiversityByHash DiversityStrategy = "hash"

	// DiversityByDistance deduplication based on vector distance
	DiversityByDistance DiversityStrategy = "distance"

	// DiversityByMMR uses MMR (Maximal Marginal Relevance) algorithm
	DiversityByMMR DiversityStrategy = "mmr"
)

type FromBuilder

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

func (*FromBuilder) As

func (fb *FromBuilder) As(alia string) *FromBuilder

func (*FromBuilder) Cond

func (fb *FromBuilder) Cond(on func(on *ON)) *FromBuilder

func (*FromBuilder) JOIN

func (fb *FromBuilder) JOIN(join JOIN) *FromBuilder

func (*FromBuilder) Of

func (fb *FromBuilder) Of(tableName string) *FromBuilder

func (*FromBuilder) On

func (fb *FromBuilder) On(onStr string) *FromBuilder

func (*FromBuilder) Sub

func (fb *FromBuilder) Sub(sub func(sb *BuilderX)) *FromBuilder

func (*FromBuilder) Using

func (fb *FromBuilder) Using(key string) *FromBuilder

type FromX

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

type InsertBuilder

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

func (*InsertBuilder) Set

func (b *InsertBuilder) Set(k string, v interface{}) *InsertBuilder

type JOIN

type JOIN func() string

*

  • Config your own JOIN string as string func

type Join

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

type LongId

type LongId interface {
	GetId() uint64
}

type MySQLBuilder added in v1.2.1

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

MySQLBuilder MySQL configuration builder Uses Builder pattern to construct MySQLCustom configuration

func NewMySQLBuilder added in v1.2.1

func NewMySQLBuilder() *MySQLBuilder

NewMySQLBuilder creates a MySQL configuration builder

Example:

xb.Of(...).Custom(
    xb.NewMySQLBuilder().
        UseUpsert(true).
        UseIgnore(false).
        Build(),
).Build()

func (*MySQLBuilder) Build added in v1.2.1

func (mb *MySQLBuilder) Build() *MySQLCustom

Build constructs and returns MySQLCustom configuration

func (*MySQLBuilder) Placeholder added in v1.2.1

func (mb *MySQLBuilder) Placeholder(placeholder string) *MySQLBuilder

Placeholder sets the placeholder

func (*MySQLBuilder) UseIgnore added in v1.2.1

func (mb *MySQLBuilder) UseIgnore(use bool) *MySQLBuilder

UseIgnore sets whether to use INSERT IGNORE

func (*MySQLBuilder) UseUpsert added in v1.2.1

func (mb *MySQLBuilder) UseUpsert(use bool) *MySQLBuilder

UseUpsert sets whether to use ON DUPLICATE KEY UPDATE

type MySQLCustom added in v1.1.0

type MySQLCustom struct {
	// UseUpsert uses ON DUPLICATE KEY UPDATE (MySQL-specific)
	UseUpsert bool

	// UseIgnore uses INSERT IGNORE (ignores duplicate key errors)
	UseIgnore bool

	// Placeholder placeholder (default "?", compatible with MySQL/PostgreSQL/SQLite)
	Placeholder string
}

MySQLCustom MySQL database-specific configuration

Notes:

  • xb defaults to MySQL-compatible SQL syntax (? placeholder, LIMIT/OFFSET)
  • PostgreSQL/SQLite drivers automatically convert placeholders (? → $1, $2)
  • Most scenarios don't need Custom, use default implementation directly

Use cases:

  • MySQL special syntax (ON DUPLICATE KEY UPDATE, INSERT IGNORE)
  • Performance optimization (STRAIGHT_JOIN, FORCE INDEX)
  • Extended functionality (user-defined)

Example:

// Default configuration (using singleton)
built := xb.Of("users").Custom(xb.DefaultMySQLCustom()).Build()

// Custom configuration (using Builder)
custom := xb.NewMySQLBuilder().UseUpsert(true).Build()
built := xb.Of("users").Custom(custom).Build()

func DefaultMySQLCustom added in v1.1.0

func DefaultMySQLCustom() *MySQLCustom

DefaultMySQLCustom gets default MySQL Custom (singleton)

Notes:

  • Returns global singleton to avoid repeated creation
  • xb defaults to MySQL-compatible SQL syntax, most scenarios don't need to set Custom
  • Only use when MySQL special syntax (UPSERT, INSERT IGNORE) is needed

Returns:

  • *MySQLCustom

Example:

// ⭐ Default scenario (recommended, most concise)
built := xb.Of("users").Eq("id", 1).Build()
sql, args, _ := built.SqlOfSelect()
// SELECT * FROM users WHERE id = ?

// ⭐ When UPSERT is needed
built := xb.Of("users").
    Custom(xb.NewMySQLBuilder().UseUpsert(true).Build()).
    Insert(func(ib *xb.InsertBuilder) {
        ib.Set("name", "John Doe").Set("age", 18)
    }).
    Build()
sql, args := built.SqlOfInsert()
// INSERT INTO users (name, age) VALUES (?, ?)
// ON DUPLICATE KEY UPDATE name = VALUES(name), age = VALUES(age)

func (*MySQLCustom) Generate added in v1.1.0

func (c *MySQLCustom) Generate(built *Built) (interface{}, error)

Generate implements Custom interface

Notes:

  • Most scenarios use default SQL generation logic
  • Special scenarios (UPSERT, IGNORE) use MySQL-specific syntax

Parameters:

  • built: Built object

Returns:

  • interface{}: *SQLResult
  • error: error information

type ON

type ON struct {
	CondBuilder
	// contains filtered or unexported fields
}

type Op

type Op func() string

type PageBuilder

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

func (*PageBuilder) IgnoreTotalRows

func (pb *PageBuilder) IgnoreTotalRows() *PageBuilder

func (*PageBuilder) Last

func (pb *PageBuilder) Last(last uint64) *PageBuilder

Last if ASC: orderBy > last else DESC: orderBy < last LIMIT rows

func (*PageBuilder) Page

func (pb *PageBuilder) Page(page uint) *PageBuilder

func (*PageBuilder) Rows

func (pb *PageBuilder) Rows(rows uint) *PageBuilder

func (*PageBuilder) SetTotalRowsIgnored

func (pb *PageBuilder) SetTotalRowsIgnored(ignored bool) *PageBuilder

type PageCondition

type PageCondition struct {
	Page               uint
	Rows               uint
	Last               uint64
	IsTotalRowsIgnored bool
}

type Po

type Po interface {
	TableName() string
}

type QdrantBuilder added in v1.2.1

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

QdrantBuilder Qdrant configuration builder Uses Builder pattern to construct QdrantCustom configuration

func NewQdrantBuilder added in v1.2.1

func NewQdrantBuilder() *QdrantBuilder

NewQdrantBuilder creates a Qdrant configuration builder

Example:

// Basic configuration
xb.Of(...).Custom(
    xb.NewQdrantBuilder().
        HnswEf(512).
        ScoreThreshold(0.8).
        Build(),
).Build()

// Advanced API
xb.Of(...).Custom(
    xb.NewQdrantBuilder().
        HnswEf(512).
        Recommend(func(rb *xb.RecommendBuilder) {
            rb.Positive(123, 456).Limit(20)
        }).
        Build(),
).Build()

// Mixed configuration
xb.Of(...).Custom(
    xb.NewQdrantBuilder().
        HnswEf(512).
        ScoreThreshold(0.8).
        Recommend(func(rb *xb.RecommendBuilder) {
            rb.Positive(123, 456).Limit(20)
        }).
        Build(),
).Build()

func (*QdrantBuilder) Build added in v1.2.1

func (qb *QdrantBuilder) Build() *QdrantCustom

Build constructs and returns QdrantCustom configuration

func (*QdrantBuilder) Discover added in v1.4.1

func (qb *QdrantBuilder) Discover(fn func(db *DiscoverBuilder)) *QdrantBuilder

Discover enables Qdrant Discover API

Example:

xb.NewQdrantBuilder().
    HnswEf(512).
    Discover(func(db *xb.DiscoverBuilder) {
        db.Context(101, 102, 103).Limit(20)
    }).
    Build()

func (*QdrantBuilder) HnswEf added in v1.2.1

func (qb *QdrantBuilder) HnswEf(ef int) *QdrantBuilder

HnswEf sets the ef parameter for HNSW algorithm Larger ef means higher query precision but slower speed Recommended value: 64-256

func (*QdrantBuilder) Recommend added in v1.4.1

func (qb *QdrantBuilder) Recommend(fn func(rb *RecommendBuilder)) *QdrantBuilder

Recommend enables Qdrant Recommend API

Example:

xb.NewQdrantBuilder().
    HnswEf(512).
    Recommend(func(rb *xb.RecommendBuilder) {
        rb.Positive(123, 456).Negative(789).Limit(20)
    }).
    Build()

func (*QdrantBuilder) ScoreThreshold added in v1.2.1

func (qb *QdrantBuilder) ScoreThreshold(threshold float32) *QdrantBuilder

ScoreThreshold sets the minimum similarity threshold Only returns results with similarity >= threshold

func (*QdrantBuilder) ScrollID added in v1.4.1

func (qb *QdrantBuilder) ScrollID(scrollID string) *QdrantBuilder

ScrollID enables Qdrant Scroll API

Example:

xb.NewQdrantBuilder().
    HnswEf(512).
    ScrollID("scroll-abc123").
    Build()

func (*QdrantBuilder) WithVector added in v1.2.1

func (qb *QdrantBuilder) WithVector(withVector bool) *QdrantBuilder

WithVector sets whether to return vector data true: return vectors (uses bandwidth) false: don't return vectors (saves bandwidth)

type QdrantCondition

type QdrantCondition struct {
	Key   string                `json:"key,omitempty"`
	Match *QdrantMatchCondition `json:"match,omitempty"`
	Range *QdrantRangeCondition `json:"range,omitempty"`
}

QdrantCondition Qdrant condition

type QdrantCustom added in v1.1.0

type QdrantCustom struct {
	// Default parameters (used if user doesn't explicitly specify)
	DefaultHnswEf         int     // Default HNSW EF parameter
	DefaultScoreThreshold float32 // Default similarity threshold
	DefaultWithVector     bool    // Default whether to return vectors
	// contains filtered or unexported fields
}

QdrantCustom Qdrant-specific configuration implementation

Implements Custom interface, provides Qdrant default configuration and preset modes

func (*QdrantCustom) Generate added in v1.1.0

func (c *QdrantCustom) Generate(built *Built) (interface{}, error)

Generate implements Custom interface ⭐ Returns different JSON based on operation type

type QdrantDiscoverRequest

type QdrantDiscoverRequest struct {
	Context        []int64             `json:"context"` // Context sample ID list
	Limit          int                 `json:"limit"`
	Filter         *QdrantFilter       `json:"filter,omitempty"`
	WithPayload    interface{}         `json:"with_payload,omitempty"` // true, false, or []string
	WithVector     bool                `json:"with_vector,omitempty"`
	ScoreThreshold *float32            `json:"score_threshold,omitempty"`
	Offset         int                 `json:"offset,omitempty"`
	Params         *QdrantSearchParams `json:"params,omitempty"`
}

QdrantDiscoverRequest Qdrant Discover request structure (v0.10.0) Documentation: https://qdrant.tech/documentation/concepts/explore/#discovery-api

func (*QdrantDiscoverRequest) GetFilter added in v1.1.0

func (r *QdrantDiscoverRequest) GetFilter() interface{}

func (*QdrantDiscoverRequest) GetParams added in v1.1.0

func (r *QdrantDiscoverRequest) GetParams() **QdrantSearchParams

Implements QdrantRequest interface (specific)

func (*QdrantDiscoverRequest) GetQdrantFilter added in v1.1.0

func (r *QdrantDiscoverRequest) GetQdrantFilter() **QdrantFilter

func (*QdrantDiscoverRequest) GetScoreThreshold added in v1.1.0

func (r *QdrantDiscoverRequest) GetScoreThreshold() **float32

Implements VectorDBRequest interface (common)

func (*QdrantDiscoverRequest) GetWithVector added in v1.1.0

func (r *QdrantDiscoverRequest) GetWithVector() *bool

type QdrantFilter

type QdrantFilter struct {
	Must    []QdrantCondition `json:"must,omitempty"`
	Should  []QdrantCondition `json:"should,omitempty"`
	MustNot []QdrantCondition `json:"must_not,omitempty"`
}

QdrantFilter Qdrant filter

type QdrantMatchCondition

type QdrantMatchCondition struct {
	Value interface{}   `json:"value,omitempty"`
	Any   []interface{} `json:"any,omitempty"`
}

QdrantMatchCondition Qdrant exact match condition

type QdrantPoint added in v1.1.0

type QdrantPoint struct {
	ID      interface{}            `json:"id"`
	Vector  interface{}            `json:"vector"`
	Payload map[string]interface{} `json:"payload,omitempty"`
}

QdrantPoint Qdrant point structure

type QdrantRangeCondition

type QdrantRangeCondition struct {
	Gt  *float64 `json:"gt,omitempty"`
	Gte *float64 `json:"gte,omitempty"`
	Lt  *float64 `json:"lt,omitempty"`
	Lte *float64 `json:"lte,omitempty"`
}

QdrantRangeCondition Qdrant range condition

type QdrantRecommendRequest

type QdrantRecommendRequest struct {
	Positive       []int64             `json:"positive"`           // Positive sample ID list
	Negative       []int64             `json:"negative,omitempty"` // Negative sample ID list (optional)
	Limit          int                 `json:"limit"`
	Filter         *QdrantFilter       `json:"filter,omitempty"`
	WithPayload    interface{}         `json:"with_payload,omitempty"` // true, false, or []string
	WithVector     bool                `json:"with_vector,omitempty"`
	ScoreThreshold *float32            `json:"score_threshold,omitempty"`
	Offset         int                 `json:"offset,omitempty"`
	Params         *QdrantSearchParams `json:"params,omitempty"`
	Strategy       string              `json:"strategy,omitempty"` // "average_vector" or "best_score"
}

QdrantRecommendRequest Qdrant recommend request structure (v0.10.0) Documentation: https://qdrant.tech/documentation/concepts/explore/#recommendation-api

func (*QdrantRecommendRequest) GetFilter added in v1.1.0

func (r *QdrantRecommendRequest) GetFilter() interface{}

func (*QdrantRecommendRequest) GetParams added in v1.1.0

func (r *QdrantRecommendRequest) GetParams() **QdrantSearchParams

Implements QdrantRequest interface (specific)

func (*QdrantRecommendRequest) GetQdrantFilter added in v1.1.0

func (r *QdrantRecommendRequest) GetQdrantFilter() **QdrantFilter

func (*QdrantRecommendRequest) GetScoreThreshold added in v1.1.0

func (r *QdrantRecommendRequest) GetScoreThreshold() **float32

Implements VectorDBRequest interface (common)

func (*QdrantRecommendRequest) GetWithVector added in v1.1.0

func (r *QdrantRecommendRequest) GetWithVector() *bool

type QdrantRequest added in v1.1.0

type QdrantRequest interface {
	VectorDBRequest // ⭐ Extends common interface

	// GetParams gets Qdrant-specific search parameters (HNSW, Exact, etc.)
	GetParams() **QdrantSearchParams

	// GetQdrantFilter gets Qdrant-specific filter (type-safe)
	GetQdrantFilter() **QdrantFilter
}

QdrantRequest Qdrant-specific request interface Extends common interface with Qdrant-specific HNSW parameters

type QdrantScrollRequest

type QdrantScrollRequest struct {
	ScrollID    string        `json:"scroll_id,omitempty"`
	Limit       int           `json:"limit,omitempty"`
	Filter      *QdrantFilter `json:"filter,omitempty"`
	WithPayload interface{}   `json:"with_payload,omitempty"`
	WithVector  bool          `json:"with_vector,omitempty"`
}

QdrantScrollRequest Qdrant Scroll request structure (v0.10.0) Documentation: https://qdrant.tech/documentation/concepts/points/#scroll-points

func (*QdrantScrollRequest) GetFilter added in v1.1.0

func (r *QdrantScrollRequest) GetFilter() interface{}

func (*QdrantScrollRequest) GetParams added in v1.1.0

func (r *QdrantScrollRequest) GetParams() **QdrantSearchParams

Implements QdrantRequest interface (specific)

func (*QdrantScrollRequest) GetQdrantFilter added in v1.1.0

func (r *QdrantScrollRequest) GetQdrantFilter() **QdrantFilter

func (*QdrantScrollRequest) GetScoreThreshold added in v1.1.0

func (r *QdrantScrollRequest) GetScoreThreshold() **float32

Implements VectorDBRequest interface (common)

func (*QdrantScrollRequest) GetWithVector added in v1.1.0

func (r *QdrantScrollRequest) GetWithVector() *bool

type QdrantSearchParams

type QdrantSearchParams struct {
	HnswEf      int  `json:"hnsw_ef,omitempty"`
	Exact       bool `json:"exact,omitempty"`
	IndexedOnly bool `json:"indexed_only,omitempty"`
}

QdrantSearchParams Qdrant search parameters

type QdrantSearchRequest

type QdrantSearchRequest struct {
	Vector         []float32           `json:"vector"`
	Limit          int                 `json:"limit"`
	Filter         *QdrantFilter       `json:"filter,omitempty"`
	WithPayload    interface{}         `json:"with_payload,omitempty"` // true, false, or []string
	WithVector     bool                `json:"with_vector,omitempty"`
	ScoreThreshold *float32            `json:"score_threshold,omitempty"`
	Offset         int                 `json:"offset,omitempty"`
	Params         *QdrantSearchParams `json:"params,omitempty"`
}

QdrantSearchRequest Qdrant search request structure Documentation: https://qdrant.tech/documentation/concepts/search/

func (*QdrantSearchRequest) GetFilter added in v1.1.0

func (r *QdrantSearchRequest) GetFilter() interface{}

func (*QdrantSearchRequest) GetParams added in v1.1.0

func (r *QdrantSearchRequest) GetParams() **QdrantSearchParams

Implements QdrantRequest interface (specific)

func (*QdrantSearchRequest) GetQdrantFilter added in v1.1.0

func (r *QdrantSearchRequest) GetQdrantFilter() **QdrantFilter

func (*QdrantSearchRequest) GetScoreThreshold added in v1.1.0

func (r *QdrantSearchRequest) GetScoreThreshold() **float32

Implements VectorDBRequest interface (common)

func (*QdrantSearchRequest) GetWithVector added in v1.1.0

func (r *QdrantSearchRequest) GetWithVector() *bool

type RecommendBuilder

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

RecommendBuilder Recommend API builder

func (*RecommendBuilder) Limit

func (rb *RecommendBuilder) Limit(limit int) *RecommendBuilder

Limit sets the number of results to return

func (*RecommendBuilder) Negative

func (rb *RecommendBuilder) Negative(ids ...int64) *RecommendBuilder

Negative sets negative sample IDs

func (*RecommendBuilder) Positive

func (rb *RecommendBuilder) Positive(ids ...int64) *RecommendBuilder

Positive sets positive sample IDs

type SQLResult added in v1.1.0

type SQLResult struct {
	SQL      string            // Data SQL (with placeholders)
	CountSQL string            // Count SQL (optional, for pagination, required by Oracle/ClickHouse, etc.)
	Args     []interface{}     // Parameter values
	Meta     map[string]string // Metadata (optional)
}

SQLResult SQL query result (SQL + parameters) Used for SQL databases (PostgreSQL, MySQL, Oracle, etc.)

type Sort

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

type StringId

type StringId interface {
	GetId() string
}

type TotalRows

type TotalRows struct {
	Count int64 `db:"COUNT(*)"`
}

type UNION added in v1.2.3

type UNION func() string

UNION combination operator

type USING

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

type UnionClause added in v1.2.3

type UnionClause struct {
	Operator string
	SQL      string
	Args     []interface{}
}

UnionClause UNION definition

type UpdateBuilder

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

func (*UpdateBuilder) Any

func (ub *UpdateBuilder) Any(f func(*UpdateBuilder)) *UpdateBuilder

func (*UpdateBuilder) Bool

func (ub *UpdateBuilder) Bool(preCond BoolFunc, f func(cb *UpdateBuilder)) *UpdateBuilder

func (*UpdateBuilder) Set

func (ub *UpdateBuilder) Set(k string, v interface{}) *UpdateBuilder

func (*UpdateBuilder) X

func (ub *UpdateBuilder) X(s string, vs ...interface{}) *UpdateBuilder

type Vector

type Vector []float32

Vector vector type (compatible with PostgreSQL pgvector)

func (Vector) Dim

func (v Vector) Dim() int

Dim returns vector dimension

func (Vector) Distance

func (v Vector) Distance(other Vector, metric VectorDistance) float32

Distance calculates the distance between two vectors

func (Vector) Normalize

func (v Vector) Normalize() Vector

Normalize vector normalization (L2 norm)

func (*Vector) Scan

func (v *Vector) Scan(value interface{}) error

Scan implements sql.Scanner interface

func (Vector) Value

func (v Vector) Value() (driver.Value, error)

Value implements driver.Valuer interface

type VectorDBRequest added in v1.1.0

type VectorDBRequest interface {
	// GetScoreThreshold get similarity threshold
	// All vector databases support setting the minimum similarity threshold
	// Return value: **float32 supports nil value judgment and modification
	GetScoreThreshold() **float32

	// GetWithVector whether to return vector data
	// Control whether the query result contains the original vector (saving bandwidth)
	// Return value: *bool supports direct modification
	GetWithVector() *bool

	// GetFilter get filter
	// The filter structure is different for different databases:
	//  - Qdrant: *QdrantFilter
	//  - Milvus: *string (Expr)
	//  - Weaviate: *WeaviateFilter
	// Return value: interface{} allows any type, the caller needs to type assert
	GetFilter() interface{}
}

VectorDBRequest Vector database request common interface Suitable for all vector databases (Qdrant, Milvus, Weaviate, Pinecone, etc.)

Design principles:

  1. Only include common fields supported by all vector databases
  2. Each database inherits this interface and adds its own fields
  3. Use **Type mode to support nil initialization and modification

Example:

// Qdrant inherits common interface
type QdrantRequest interface {
    VectorDBRequest           // Inherits common interface
    GetParams() **QdrantSearchParams  // Own fields
}

// Milvus inherits common interface
type MilvusRequest interface {
    VectorDBRequest           // Inherits common interface
    GetSearchParams() **MilvusSearchParams  // Own fields
}

type VectorDistance

type VectorDistance string

VectorDistance vector distance metric type

const (
	// CosineDistance cosine distance (most commonly used)
	// PostgreSQL: <->
	CosineDistance VectorDistance = "<->"

	// L2Distance Euclidean distance (L2 norm)
	// PostgreSQL: <#>
	L2Distance VectorDistance = "<#>"

	// InnerProduct inner product distance (dot product)
	// PostgreSQL: <=>
	InnerProduct VectorDistance = "<=>"
)

type VectorDistanceFilterParams

type VectorDistanceFilterParams struct {
	QueryVector    Vector
	Operator       string // <, <=, >, >=, =
	Threshold      float32
	DistanceMetric VectorDistance
}

VectorDistanceFilterParams vector distance filter parameters

type VectorSearchParams

type VectorSearchParams struct {
	QueryVector    Vector
	TopK           int
	DistanceMetric VectorDistance
	Diversity      *DiversityParams // ⭐ Added: diversity parameters (optional)
}

VectorSearchParams vector search parameters

type WithClause added in v1.2.3

type WithClause struct {
	Name      string
	SQL       string
	Args      []interface{}
	Recursive bool
}

WithClause common table expression (CTE) definition

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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