Skip to content

Commit 006dc4a

Browse files
author
Hein
committed
Using scan model method for better relation handling. e.g bun When querying has-many or many-to-many relationships, you should use Model instead of the dest parameter in Scan
1 parent ecd7b31 commit 006dc4a

File tree

5 files changed

+15
-2
lines changed

5 files changed

+15
-2
lines changed

.gitignore

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,4 +23,5 @@ go.work.sum
2323

2424
# env file
2525
.env
26-
bin/
26+
bin/
27+
test.db

pkg/common/adapters/database/bun.go

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -238,6 +238,10 @@ func (b *BunSelectQuery) Scan(ctx context.Context, dest interface{}) error {
238238
return b.query.Scan(ctx, dest)
239239
}
240240

241+
func (b *BunSelectQuery) ScanModel(ctx context.Context) error {
242+
return b.query.Scan(ctx)
243+
}
244+
241245
func (b *BunSelectQuery) Count(ctx context.Context) (int, error) {
242246
// If Model() was set, use bun's native Count() which works properly
243247
if b.hasModel {

pkg/common/adapters/database/gorm.go

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -221,6 +221,13 @@ func (g *GormSelectQuery) Scan(ctx context.Context, dest interface{}) error {
221221
return g.db.WithContext(ctx).Find(dest).Error
222222
}
223223

224+
func (g *GormSelectQuery) ScanModel(ctx context.Context) error {
225+
if g.db.Statement.Model == nil {
226+
return fmt.Errorf("ScanModel requires Model() to be set before scanning")
227+
}
228+
return g.db.WithContext(ctx).Find(g.db.Statement.Model).Error
229+
}
230+
224231
func (g *GormSelectQuery) Count(ctx context.Context) (int, error) {
225232
var count int64
226233
err := g.db.WithContext(ctx).Count(&count).Error

pkg/common/interfaces.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,7 @@ type SelectQuery interface {
3939

4040
// Execution methods
4141
Scan(ctx context.Context, dest interface{}) error
42+
ScanModel(ctx context.Context) error
4243
Count(ctx context.Context) (int, error)
4344
Exists(ctx context.Context) (bool, error)
4445
}

pkg/restheadspec/handler.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -398,7 +398,7 @@ func (h *Handler) handleRead(ctx context.Context, w common.ResponseWriter, id st
398398
}
399399

400400
// Execute query - modelPtr was already created earlier
401-
if err := query.Scan(ctx, modelPtr); err != nil {
401+
if err := query.ScanModel(ctx); err != nil {
402402
logger.Error("Error executing query: %v", err)
403403
h.sendError(w, http.StatusInternalServerError, "query_error", "Error executing query", err)
404404
return

0 commit comments

Comments
 (0)