89 online 3 members  + Join RP Base  +
FreeScript

QueryBuilder

by fantasticbin  ·  version 2026.11.04  ·  updated 2 days ago

No reviews yet

Downloads
0
Reviews
0
Size
256 KB
Code check
Clean
Licence
MIT
Released
Nov 2026

Simplifies list querying in Go

QueryBuilder
English | 中文

QueryBuilder
A Go library for building type-safe list queries across multiple data sources. Leverages Go 1.26 self-referential generic constraints to provide dedicated query builders for GORM-Compatible DB (GORM, e.g. MySQL/PostgreSQL/SQLite/SQL Server), MongoDB, and ElasticSearch — with zero type assertions, flexible middleware, and a unified query interface.

Features
  • Multi-DataSource Builders: Dedicated GormBuilder, MongoBuilder, and ElasticSearchBuilder with strongly-typed SetFilter / SetSort methods.
  • Aggregate Query Builders: The agg package provides dedicated builders for grouped statistics on GORM, MongoDB, and ElasticSearch, including Count, CountDistinct, Sum, SumDistinct, Avg, Min, Max, conditional metrics, HAVING filters, result ordering, typed result decoding, Explain, and aggregate middleware in middleware.
  • Self-Referential Generics: Uses Go 1.26 self-referential generic constraints for type-safe fluent chaining.
  • Zero Type Assertions: All filter/sort operations are fully typed — no any casts at runtime.
  • Scope Helpers: Built-in SetScope + NewGormScope / NewMongoScope / NewElasticSearchScope — set filter/sort in one line under List mode, no manual middleware or type assertions needed.
  • **Unified Querier Interface**: A common interface for pagination, middleware, and query execution across all data sources.
  • Middleware Pipeline: Insert custom logic (timing, logging, caching, etc.) into the query pipeline.
  • Built-in Cache Middleware: Out-of-the-box CacheMiddleware with a pluggable CacheProvider interface — bring your own cache backend (Redis, in-memory, etc.).
  • Field Selection: Use SetFields to select only specific fields, reducing bandwidth and memory usage across all data sources.
  • Query Hooks: BeforeQueryHook and AfterQueryHook for lightweight pre/post query logic (context injection, logging, metrics, etc.).
  • Query Meta: Middleware can access QueryMeta directly via builder.GetQueryMeta() — data source type, pagination/cursor info, and query start time are available without context injection.
  • Dry Run / Explain: Each builder provides an Explain method to preview the generated query (SQL, MongoDB filter, ES DSL) without executing it.
  • Cursor Pagination: Built-in cursor-based pagination with QueryCursor, returning Go 1.23+ iter.Seq2 iterators for memory-efficient streaming over large datasets. Supports Gorm (row value expressions), MongoDB ($gt compound conditions), and ElasticSearch (search_after API). Also provides QueryPage for single-batch cursor pagination, returning a structured core.CursorPageResult (items + has_more + next_cursor) — ideal for App "load more" or API-driven pagination. Supports the search_after + Point-in-Time (PIT) approach for full data iteration in ElasticSearch cursor scenarios, ensuring index snapshot consistency during iteration and avoiding unstable sorting caused by refresh operations. It can be automatically enabled via SetNeedPagination(false), with the keep-alive duration configurable through SetPitKeepAlive(...).
  • Clone for Concurrent Forking: Each builder provides a Clone() method to create an independent copy of the current query configuration — enabling safe concurrent forked queries without shared state.
  • Pagination Control: Toggle pagination on/off — useful for data export scenarios.
  • Bounded Total Count: Cap expensive total-count queries with WithTotalLimit / SetTotalLimit while keeping exact counting as the default.
  • Options Pattern: Flexible query configuration via functional options.
  • Easy to Test: Built-in MockQuerier for convenient unit testing.

Installation
go get github.com/fantasticbin/QueryBuilder/v2

Requires Go 1.26+ (for self-referential generic constraints).

Architecture
┌──────────────────────────────────────────────────────────┐
│                       Querier[R]                         │  ← Unified interface
│  Use / SetStart / SetLimit / SetNeedTotal /              │
│  SetNeedPagination / SetFields / SetBeforeQueryHook /    │
│  SetAfterQueryHook / SetCursorField / QueryList /        │
│  QueryCursor / QueryPage                                 │
└──────────┬──────────────┬──────────────┬─────────────────┘
           │              │              │
    ┌──────▼──┐     ┌─────▼────┐ ┌───────▼─────────┐
    │  Gorm   │     │  Mongo   │ │  ElasticSearch  │   ← Dedicated builders
    │ Builder │     │ Builder  │ │     Builder     │
    └──────┬──┘     └─────┬────┘ └───────┬─────────┘
           │              │              │
    ┌──────▼──────────────▼──────────────▼──────────────────┐
    │                   builder[B, R]                       │   ← Shared base (generics)
    │  data / start / limit / fields / hooks / middlewares  │
    └───────────────────────────────────────────────────────┘

Each dedicated builder embeds the private builder base via Go 1.26 self-referential generics, inheriting common pagination, field selection, hooks, and middleware logic while exposing its own strongly-typed SetFilter / SetSort and Explain.

Quick Start1. Direct Builder Usage (Recommended)
Use a dedicated builder directly for full type safety:

```go
package main

import (
"context"
"gorm.io/gorm"
builder "github.com/fantasticbin/QueryBuilder/v2"
)

func main() {
ctx := context.Background()
db := &gorm.DB{} // your GORM instance

// Create a GORM builder (defaults: limit=10, paginated, needTotal=true)
b := builder.NewGormBuilderUser))

// Set strongly-typed filter & sort (GormScope = func(*gorm.DB) *gorm.DB)
b.SetFilter(func(db *gorm.DB) *gorm.DB {
ret

…