Skip to content

chore: Add linting rule to help catch InTx misuse #1980

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Jun 2, 2022
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
update InTx ruleguard
  • Loading branch information
Emyrk committed Jun 2, 2022
commit c856e8d762205f29435408c998c447b59415ec8e
29 changes: 20 additions & 9 deletions scripts/rules.go
Original file line number Diff line number Diff line change
Expand Up @@ -73,34 +73,45 @@ func doNotCallTFailNowInsideGoroutine(m dsl.Matcher) {
// InTx checks to ensure the database used inside the transaction closure is the transaction
// database, and not the original database that creates the tx.
func InTx(m dsl.Matcher) {
m.Import("github.com/coder/coder/coderd/database")

// ':=' and '=' are 2 different matches :(
m.Match(`
$x.InTx(func($y database.Store) error {
$x.InTx(func($y) error {
$*_
$*_ = $x.$f($*_)
$*_
})
`).Where(m["x"].Text != m["y"].Text && m["x"].Type.Implements("database.Store")).
`, `
$x.InTx(func($y) error {
$*_
$*_ := $x.$f($*_)
$*_
})
`).Where(m["x"].Text != m["y"].Text).
At(m["f"]).
Report("Do not use the database directly within the InTx closure. Use '$y' instead of '$x'.")

// When using a tx closure, ensure that if you pass the db to another
// function inside the closure, it is the tx.
// This will miss more complex cases such as passing the db as apart
// of another struct.
//When using a tx closure, ensure that if you pass the db to another
//function inside the closure, it is the tx.
//This will miss more complex cases such as passing the db as apart
//of another struct.
m.Match(`
$x.InTx(func($y database.Store) error {
$*_
$*_ = $f($*_, $x, $*_)
$*_
})
`, `
$x.InTx(func($y database.Store) error {
$*_
$*_ := $f($*_, $x, $*_)
$*_
})
`, `
$x.InTx(func($y database.Store) error {
$*_
$f($*_, $x, $*_)
$*_
})
`).Where(m["x"].Text != m["y"].Text && m["x"].Type.Implements("database.Store")).
`).Where(m["x"].Text != m["y"].Text).
At(m["f"]).Report("Pass the tx database into the '$f' function inside the closure. Use '$y' over $x'")
}