Built a linter to catch GORM's unsafe *gorm.DB reuse
#7680
mpyw
started this conversation in
Show and tell
Replies: 0 comments
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
Have you ever been bitten by GORM's reuse trap?
Hey GORM community! 👋
I think many of us have experienced this frustrating bug at least once - especially if you're maintaining codebases using GORM's Traditional API (and let's be honest, that's most of us! 😅):
The problem: GORM's Traditional API chain methods (
Where,Order, etc.) create shallow clones that share internal state. When the same mutable*gorm.DBbranches into multiple queries, they interfere with each other. This is documented in GORM's official guide on Method Chaining, but it's easy to miss in real-world code with complex control flows.Note about Generics API: GORM's Generics API (
gorm.G[T], available since v1.30.0) avoids this issue by design - it returns different types (Interface[T],ChainInterface[T]) instead of*gorm.DB. However, many production codebases still use (and will continue to maintain for years) the Traditional API. This linter is specifically for those real-world scenarios.Introducing gormreuse - A Static Analysis Linter
I've built a linter that detects these unsafe reuse patterns at compile time: github.com/mpyw/gormreuse
Key Features
*gorm.DBvalues through complex code paths (loops, conditionals, function calls, closures, defer/goroutines)*gorm.DB) - Generics API types are ignored//gormreuse:pure- Mark helpers that don't pollute DB arguments//gormreuse:immutable-return- Mark DB connection/transaction wrappers that return fresh instances//gormreuse:ignore- Suppress false positives when neededExample Detection
Handling Custom Helpers
The linter treats user-defined functions conservatively by default, but you can annotate them:
Installation
go install github.com/mpyw/gormreuse/cmd/gormreuse@latest go vet -vettool=$(which gormreuse) ./...Or integrate with golangci-lint (supports
--build-tags).I think this could be genuinely useful for teams working with GORM's Traditional API, especially in large codebases where these bugs can hide. The linter has been tested on complex scenarios including closures, deferred calls, and control flow.
Would love to hear your thoughts! Have you encountered this issue? Would a linter like this be helpful in your workflow? Any feedback or suggestions are welcome! 🙏
Repository: https://github.com/mpyw/gormreuse
P.S. This linter was developed with the help of Claude Code 🤖
Beta Was this translation helpful? Give feedback.
All reactions