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
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
Each dedicated builder embeds the private
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
…
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, andElasticSearchBuilderwith strongly-typedSetFilter/SetSortmethods. - Aggregate Query Builders: The
aggpackage provides dedicated builders for grouped statistics on GORM, MongoDB, and ElasticSearch, includingCount,CountDistinct,Sum,SumDistinct,Avg,Min,Max, conditional metrics, HAVING filters, result ordering, typed result decoding,Explain, and aggregate middleware inmiddleware. - 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
anycasts at runtime. - Scope Helpers: Built-in
SetScope+NewGormScope/NewMongoScope/NewElasticSearchScope— set filter/sort in one line underListmode, no manual middleware or type assertions needed. - **Unified
QuerierInterface**: 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
CacheMiddlewarewith a pluggableCacheProviderinterface — bring your own cache backend (Redis, in-memory, etc.). - Field Selection: Use
SetFieldsto select only specific fields, reducing bandwidth and memory usage across all data sources. - Query Hooks:
BeforeQueryHookandAfterQueryHookfor lightweight pre/post query logic (context injection, logging, metrics, etc.). - Query Meta: Middleware can access
QueryMetadirectly viabuilder.GetQueryMeta()— data source type, pagination/cursor info, and query start time are available without context injection. - Dry Run / Explain: Each builder provides an
Explainmethod 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.Seq2iterators for memory-efficient streaming over large datasets. Supports Gorm (row value expressions), MongoDB ($gtcompound conditions), and ElasticSearch (search_afterAPI). Also providesQueryPagefor single-batch cursor pagination, returning a structuredcore.CursorPageResult(items + has_more + next_cursor) — ideal for App "load more" or API-driven pagination. Supports thesearch_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 viaSetNeedPagination(false), with the keep-alive duration configurable throughSetPitKeepAlive(...). - 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/SetTotalLimitwhile keeping exact counting as the default. - Options Pattern: Flexible query configuration via functional options.
- Easy to Test: Built-in
MockQuerierfor convenient unit testing.
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
…