Skip to content

Commit 040d27b

Browse files
committed
fix(libsql): Chunk based on maxPlaceholders instead of rows
1 parent 84ffff2 commit 040d27b

File tree

2 files changed

+42
-6
lines changed

2 files changed

+42
-6
lines changed

example/example.go

+15
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ package main
33
import (
44
"context"
55
"database/sql"
6+
"fmt"
67
"log"
78
"os"
89
"path/filepath"
@@ -317,4 +318,18 @@ func main() {
317318
log.Printf("getPost has value: %+v", getPost)
318319
log.Printf("getPost has found: %+v", found)
319320
log.Printf("getPost has error: %+v", err)
321+
322+
twentyThousand := make([]cache.SetMany[*string], 0)
323+
for i := range 20_000 {
324+
str := fmt.Sprintf("%d", i)
325+
twentyThousand = append(twentyThousand, cache.SetMany[*string]{
326+
Value: &str,
327+
Key: str,
328+
Opts: nil,
329+
})
330+
}
331+
332+
if err := service.cache.String.SetMany(ctx, twentyThousand, nil); err != nil {
333+
log.Fatal(err)
334+
}
320335
}

store/libsql/libsql.go

+27-6
Original file line numberDiff line numberDiff line change
@@ -171,15 +171,36 @@ func (l *LibsqlStore) Set(ns types.TNamespace, key string, value types.TValue) e
171171
return err
172172
}
173173

174+
const maxPlaceholders = 32_766
175+
const placeHoldersPerRow = 4
176+
174177
func (l *LibsqlStore) SetMany(ns types.TNamespace, values []types.TValue, opts *types.SetOptions) error {
175-
// IMPORTANT: This is not a transaction and will be a max of 2000 rows at a time
178+
// IMPORTANT: This is not a transaction and will be a max of maxPlaceholders placeholders at a time
179+
// cache table has 4 columns so we need to multiply by placeHoldersPerRow
180+
totalPlaceholders := placeHoldersPerRow * len(values)
181+
176182
chunks := make([][]types.TValue, 0)
177-
chunkSize := 2000
178-
for i, v := range values {
179-
if i%chunkSize == 0 {
180-
chunks = append(chunks, make([]types.TValue, 0))
183+
if totalPlaceholders <= maxPlaceholders {
184+
// If we’re below the limit, no need to split into chunks
185+
chunks = append(chunks, values)
186+
} else {
187+
currentChunk := make([]types.TValue, 0)
188+
currentPlaceholders := 0
189+
190+
for _, v := range values {
191+
if currentPlaceholders+placeHoldersPerRow > maxPlaceholders {
192+
chunks = append(chunks, currentChunk)
193+
currentChunk = make([]types.TValue, 0)
194+
currentPlaceholders = 0
195+
}
196+
197+
currentChunk = append(currentChunk, v)
198+
currentPlaceholders += placeHoldersPerRow
199+
}
200+
201+
if len(currentChunk) > 0 {
202+
chunks = append(chunks, currentChunk)
181203
}
182-
chunks[len(chunks)-1] = append(chunks[len(chunks)-1], v)
183204
}
184205

185206
for _, chunk := range chunks {

0 commit comments

Comments
 (0)