From abee5c942fb9c1c2e8cc23447aa8a2941dcac14b Mon Sep 17 00:00:00 2001 From: Hein Date: Fri, 7 Nov 2025 13:54:24 +0200 Subject: [PATCH] Count Fixes --- pkg/common/adapters/database/bun.go | 5 ++++- pkg/resolvespec/handler.go | 8 ++++---- pkg/restheadspec/handler.go | 6 +++--- 3 files changed, 11 insertions(+), 8 deletions(-) diff --git a/pkg/common/adapters/database/bun.go b/pkg/common/adapters/database/bun.go index e0a6a93..8f13f2f 100644 --- a/pkg/common/adapters/database/bun.go +++ b/pkg/common/adapters/database/bun.go @@ -228,7 +228,10 @@ func (b *BunSelectQuery) Scan(ctx context.Context, dest interface{}) error { } func (b *BunSelectQuery) Count(ctx context.Context) (int, error) { - count, err := b.query.Count(ctx) + // Use ColumnExpr with Scan instead of Count() to avoid requiring a model + // This works with just Table() set and avoids "Model(nil)" error + var count int + err := b.query.ColumnExpr("count(*)").Scan(ctx, &count) return count, err } diff --git a/pkg/resolvespec/handler.go b/pkg/resolvespec/handler.go index c14ef6e..54d75ac 100644 --- a/pkg/resolvespec/handler.go +++ b/pkg/resolvespec/handler.go @@ -171,13 +171,13 @@ func (h *Handler) handleRead(ctx context.Context, w common.ResponseWriter, id st logger.Info("Reading records from %s.%s", schema, entity) - // Create the model pointer early for Bun compatibility - // Bun requires Model() to be set for Count() and Scan() operations + // Create the model pointer for Scan() operations + // We don't set it on the query to avoid table duplication in FROM clause sliceType := reflect.SliceOf(reflect.PointerTo(modelType)) modelPtr := reflect.New(sliceType).Interface() - // Use Model() and Table() - Bun needs both for proper operation - query := h.db.NewSelect().Model(modelPtr).Table(tableName) + // Use only Table() - model will be provided to Scan() directly + query := h.db.NewSelect().Table(tableName) // Apply column selection if len(options.Columns) > 0 { diff --git a/pkg/restheadspec/handler.go b/pkg/restheadspec/handler.go index c29815a..712af0e 100644 --- a/pkg/restheadspec/handler.go +++ b/pkg/restheadspec/handler.go @@ -201,9 +201,9 @@ func (h *Handler) handleRead(ctx context.Context, w common.ResponseWriter, id st logger.Info("Reading records from %s.%s", schema, entity) - // Use Table() with the resolved table name and Model() for Bun compatibility - // Bun requires Model() to be set for Count() and Scan() operations - query := h.db.NewSelect().Model(modelPtr).Table(tableName) + // Use Table() with the resolved table name + // Model will be provided to Scan() directly to avoid table duplication in FROM clause + query := h.db.NewSelect().Table(tableName) // Apply column selection if len(options.Columns) > 0 {