database-helpers-go

Complex queries, one operator at a time.

database-helpers-go turns a relational or Elasticsearch query into a pipeline of small operators. Filtering, search, ordering and pagination are read from the request, checked against the fields you allow, and applied in order.

go get github.com/pixie-sh/database-helpers-go

Go 1.25+, built on GORM. MIT licensed. The full reference is in the README.

The problem

Every list endpoint grows the same pile of ifs.

A tenant filter, then free-text search, then sorting, then pagination. Each one wraps the query builder in conditions, and each endpoint writes them again, slightly differently.

By hand

q := db.Model(&User{}).Where("tenant_id = ?", tenantID)

if s := params.Get("q"); s != "" {
    q = q.Where("name LIKE ?", "%"+s+"%")
}

switch params.Get("sort_by") {
case "created_at":
    q = q.Order("created_at ASC")
case "-created_at", "":
    q = q.Order("created_at DESC")
default:
    return nil, errBadSort
}

page, perPage := parsePaging(params) // and its limits
var total int64
q.Count(&total)
q.Limit(perPage).Offset((page - 1) * perPage).Find(&users)

Written again for orders, invoices and every other list.

As a pipeline

pipeline.NewPipeline(log).
    AddOperator(
        operators.NewHardWhereOperator("tenant_id = ?", tenantID),
        operators.NewGlobalSearchOperator(params, "q",
            models.SearchableProperty{Field: "name", Type: "text",
                Comparison: "LIKE", LikeBefore: true, LikeAfter: true},
        ),
        operators.NewOrderByOperator(params, true, []string{"-created_at"},
            models.SearchableProperty{Field: "created_at", Type: "date"},
        ),
        operators.NewPaginateOperator(params, &users, 10, 25, 50),
    ).
    ExecWithPassable(ctx, operators.NewResult(db.Model(&User{})))

Four operators, in the order they apply. The next endpoint reuses them.

One operator, one concern

Operators are small, ordered and testable on their own.

Driven by the request

Search, order and pagination read the query string and accept only the fields you list.

Two back ends, one shape

The same pipeline builds a GORM query or an Elasticsearch _search body.

Elasticsearch

Search bodies without hand-written JSON.

Elasticsearch operators add clauses to a builder: filters, nested bool queries, geo distance, scoring scripts and pagination. The result is a plain request you can send with the bundled repository or any client.

result, err := pipeline.NewPipeline(log).
    AddOperator(
        elastic.NewSourceOperator("id", "title", "status"),
        elastic.NewFilterOperator(elastic.Term("status", "live")),
        // online deals, or physical deals within 250 km
        elastic.NewFilterOperator(elastic.BoolShould(1,
            elastic.Term("deal_type", "online"),
            elastic.BoolFilter(
                elastic.Term("deal_type", "physical"),
                elastic.GeoDistance("locations.coords", "250km", 52.3676, 4.9041),
            ),
        )),
        elastic.NewMustNotOperator(elastic.IDs("hidden_deal_id")),
        elastic.NewShouldOperator(elastic.MultiMatch("eco laundry", "title^3", "description")),
        elastic.NewMinimumShouldMatchOperator(1),
        elastic.NewFromSizePaginationOperator(0, 30),
    ).
    ExecWithPassable(ctx, operators.NewResult(elastic.NewBuilder("deals")))

request := result.GetPassable().(*elastic.Builder).SearchRequest()

repo := database.NewElasticRepository(database.ElasticConfiguration{
    BaseURL: "https://search.internal:9200",
    Index:   "deals",
})
response, err := repo.Search(ctx, request)
POST /deals/_search
{
  "_source": ["id", "title", "status"],
  "from": 0,
  "size": 30,
  "query": {
    "bool": {
      "filter": [
        { "term": { "status": "live" } },
        { "bool": { "minimum_should_match": 1, "should": [
          { "term": { "deal_type": "online" } },
          { "bool": { "filter": [
            { "term": { "deal_type": "physical" } },
            { "geo_distance": { "distance": "250km",
                "locations.coords": { "lat": 52.3676, "lon": 4.9041 } } }
          ] } }
        ] } }
      ],
      "must_not": [ { "ids": { "values": ["hidden_deal_id"] } } ],
      "should": [ { "multi_match": { "fields": ["title^3", "description"], "query": "eco laundry" } } ],
      "minimum_should_match": 1
    }
  }
}
// A large Painless script, composed from fragments.
elastic.NewScriptHelperOperator(`
double getVal(String field) {
  if (doc.containsKey(field) && !doc[field].empty) {
    return doc[field].value;
  }
  return 0.0;
}
`, nil),
elastic.NewScriptScoringOperator(`
if (params.w_freshness != 0 && doc.containsKey('created_at') && !doc['created_at'].empty) {
  long ageMillis = params.now - doc['created_at'].value.toInstant().toEpochMilli();
  double ageDays = ageMillis / 86400000.0;
  score += Math.max(0, 1.0 - (ageDays / params.freshness_window_days)) * params.w_freshness;
}
`, map[string]interface{}{
    "now":                   nowMillis,
    "w_freshness":           25.0,
    "freshness_window_days": 14,
}),
elastic.NewScriptScoreOperator(nil),

// Params merge into one script.params object.
// A duplicate key is an error, so weights cannot collide by accident.
// offset style, from ?page= and ?per_page=
elastic.NewOffsetPaginationOperator(queryParams, 30, 100)

// search_after for feeds and deep pages; ask for size+1 to know if there is more
elastic.NewSearchAfterPaginationOperator(
    31,
    []elastic.Query{
        elastic.SortField("_score", "desc"),
        elastic.SortField("id.keyword", "asc"),
    },
    lastScore,
    lastID,
)

// point in time
elastic.NewPointInTimeOperator(pitID, "1m")
// Put it near the end of the pipeline to log the request being built.
elastic.NewDebugOperator(
    log,
    elastic.DebugMaxBodyBytes(20_000),
    elastic.DebugRedactParams("seen_ids"),
)

// POST /deals/_search
// {
//   "size": 30,
//   "query": {}
// }
Included

Operators that ship with the library.

Write your own for business rules, such as a freshness score, and reuse them across endpoints.

FamilyOperators
SQL (GORM)NewHardWhereOperator, NewWhereIdsInOperator, NewWhereUUIDsInOperator, NewWherePropertiesInOperator, NewSearchInPropertiesOperator, NewGlobalSearchOperator, NewOrderByOperator, NewPaginateOperator, NewOffsetPaginateOperator, NewListOperator
ElasticsearchNewSourceOperator, NewFilterOperator, NewShouldOperator, NewMustNotOperator, NewMinimumShouldMatchOperator, script helper, scoring and score operators, from/size, offset, search_after and point-in-time pagination, NewDebugOperator
Query helpersTerm, Terms, IDs, MultiMatch, GeoDistance, BoolFilter, BoolMust, BoolMustNot, BoolShould, MatchAll, SortField
Around the pipeline

Connections, repositories and migrations.

Connections

NewGormDb opens PostgreSQL or MySQL from a small configuration struct.

Repositories

Repository[T] adds transactions and WithTx to your repository without hiding GORM.

Migrations

NewMigrator runs ordered migrations.

Elasticsearch repository

ElasticRepository covers search, index creation, bulk indexing and cursor helpers.

type UserRepository struct {
    database.Repository[UserRepository]
}

func NewUserRepository(db *database.DB) UserRepository {
    return UserRepository{database.NewRepository(db, NewUserRepository)}
}

func (r UserRepository) Rename(id uint64, name string) error {
    return r.Transaction(func(tx *database.DB) error {
        return tx.Model(&User{}).Where("id = ?", id).Update("name", name).Error
    })
}
Open source at Pixie

One of a set that works together.

These libraries run in our own services every day. Use one, or all of them.