forked from go/pgm
perf enhancement
This commit is contained in:
50
README.md
50
README.md
@@ -172,6 +172,56 @@ func main() {
|
||||
}
|
||||
```
|
||||
|
||||
## Important: Query Builder Lifecycle
|
||||
|
||||
⚠️ **Query builders are single-use and should not be reused:**
|
||||
|
||||
```go
|
||||
// ❌ WRONG - Don't reuse query builders
|
||||
baseQuery := users.User.Select(users.ID, users.Email)
|
||||
baseQuery.Where(users.ID.Eq(1)).First(ctx, &id1, &email1)
|
||||
baseQuery.Where(users.Status.Eq(2)).First(ctx, &id2, &email2)
|
||||
// Second query has BOTH WHERE clauses - incorrect behavior!
|
||||
|
||||
// ✅ CORRECT - Create new query each time
|
||||
users.User.Select(users.ID, users.Email).Where(users.ID.Eq(1)).First(ctx, &id1, &email1)
|
||||
users.User.Select(users.ID, users.Email).Where(users.Status.Eq(2)).First(ctx, &id2, &email2)
|
||||
```
|
||||
|
||||
**Why?** Query builders are mutable and accumulate state. Each method call modifies the builder, so reusing the same builder causes conditions to stack up.
|
||||
|
||||
### Thread Safety
|
||||
|
||||
⚠️ **Query builders are NOT thread-safe** and must not be shared across goroutines:
|
||||
|
||||
```go
|
||||
// ✅ CORRECT - Each goroutine creates its own query
|
||||
for i := 0; i < 10; i++ {
|
||||
go func(id int) {
|
||||
var email string
|
||||
err := users.User.Select(users.Email).
|
||||
Where(users.ID.Eq(id)).
|
||||
First(ctx, &email)
|
||||
// Process result...
|
||||
}(i)
|
||||
}
|
||||
|
||||
// ❌ WRONG - Sharing query builder across goroutines
|
||||
baseQuery := users.User.Select(users.Email)
|
||||
for i := 0; i < 10; i++ {
|
||||
go func(id int) {
|
||||
var email string
|
||||
baseQuery.Where(users.ID.Eq(id)).First(ctx, &email)
|
||||
// RACE CONDITION! Multiple goroutines modifying shared state
|
||||
}(i)
|
||||
}
|
||||
```
|
||||
|
||||
**Thread-Safe Components:**
|
||||
- ✅ Connection Pool - Safe for concurrent use
|
||||
- ✅ Table objects - Safe to share
|
||||
- ❌ Query builders - Create new instance per goroutine
|
||||
|
||||
## Usage Examples
|
||||
|
||||
### SELECT Queries
|
||||
|
||||
Reference in New Issue
Block a user