Last active
February 6, 2025 14:50
-
-
Save caioreix/6a89f65c76e055ac2ee4afdfeff68c5b to your computer and use it in GitHub Desktop.
Async Find With GORM
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func getAllAsync[CH any](db *gorm.DB, pageSize int, ch chan<- *CH, wg *sync.WaitGroup, conds ...any) { | |
wg.Add(1) | |
defer close(ch) | |
defer wg.Done() | |
currentPage := 0 | |
for { | |
rows := []*CH{} | |
_ = db. | |
Limit(pageSize). | |
Offset(currentPage*pageSize). | |
Find(&rows, conds...).Error | |
if len(rows) == 0 { | |
break | |
} | |
for _, row := range rows { | |
ch <- row | |
} | |
currentPage++ | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
func main() { | |
var ( | |
pageSize = 10 | |
wg = &sync.WaitGroup{} | |
rowChan = make(chan *map[string]any, pageSize) | |
) | |
go getAllAsync(db, pageSize, rowChan, wg) | |
wg.Add(1) | |
go func() { | |
defer wg.Done() | |
for row := range rowChan { | |
fmt.Println(row) | |
} | |
}() | |
wg.Wait() | |
fmt.Println("Done") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment