From 0aaeff63a2c41e5f783c9de33dcf93ea53d3f085 Mon Sep 17 00:00:00 2001 From: Hein Date: Mon, 20 Apr 2026 17:15:33 +0200 Subject: [PATCH] fix(db): guard against non-existent relations in preload --- pkg/common/adapters/database/bun.go | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/pkg/common/adapters/database/bun.go b/pkg/common/adapters/database/bun.go index b74011a..9c3131c 100644 --- a/pkg/common/adapters/database/bun.go +++ b/pkg/common/adapters/database/bun.go @@ -597,6 +597,19 @@ func (b *BunSelectQuery) PreloadRelation(relation string, apply ...func(common.S if !b.skipAutoDetect { model := b.query.GetModel() if model != nil && model.Value() != nil { + // Guard against relations that don't exist on the model. Without this, + // bun panics inside Count/Scan with `model=X does not have relation="Y"`. + // Only validate the root segment so nested paths (e.g. "PRM.CHILD") still + // fall through to bun's native resolution. + rootRelation := relation + if idx := strings.Index(rootRelation, "."); idx >= 0 { + rootRelation = rootRelation[:idx] + } + if reflection.GetRelationType(model.Value(), rootRelation) == reflection.RelationUnknown { + logger.Warn("Skipping preload '%s': relation '%s' is not declared on model %T", relation, rootRelation, model.Value()) + return b + } + relType := reflection.GetRelationType(model.Value(), relation) // Log the detected relationship type