Skip to content

IsReadOnlyQuery() incorrectly returns false for COUNT/EXISTS queries #1271

@nb-park

Description

@nb-park

Encountered trying to prevent a write-then-read scenario.

Code Sample

// query hook, see next comment for test code
db.AddQueryHook(&RoutingHook{})

// works
selectQuery := db.NewSelect().Model(&User{})
fmt.Printf("SELECT: %v\n", bun.IsReadOnlyQuery(selectQuery))

// don't work
// These create internal wrapper types that fail the type assertion
countQuery := db.NewSelect().Model(&User{}).Count(ctx) 
// isReadOnly fails in query hook

existsQuery := db.NewSelect().Model(&User{}).Exists(ctx)
// isReadOnly fails in query hook

edited due to invalid code; see below for working (broken) example

Root Cause

The offending line performs a type check invalid for embedded structs:

sel, ok := query.(*SelectQuery)

Env

Bun version: v1.2.15
Go version: 1.24

Suggestion

Implement an interface to fix this. Starting with an issue because I'm not super familiar with the repo, concerned about side-effects and whether there are other similar patterns which might be broken.

Metadata

Metadata

Assignees

No one assigned

    Labels

    invalidThis doesn't seem right

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions