Skip to content

Commit 06eb7e0

Browse files
authoredFeb 18, 2025··
Merge pull request #20 from initia-labs/fix/psql-limit
fix: batch insert db by max postgres limit
2 parents e7e9409 + c043aa5 commit 06eb7e0

File tree

1 file changed

+22
-4
lines changed

1 file changed

+22
-4
lines changed
 

‎informative-indexer/db/util.go

+22-4
Original file line numberDiff line numberDiff line change
@@ -3,13 +3,18 @@ package db
33
import (
44
"context"
55
"fmt"
6+
"math"
67
"reflect"
78
"strings"
89

910
"github.com/jackc/pgx/v5"
1011
"github.com/jackc/pgx/v5/pgconn"
1112
)
1213

14+
const (
15+
MaxPostgresParams = math.MaxUint16 // Max PostgreSQL limit
16+
)
17+
1318
func getColumns(t interface{}) []string {
1419
var fieldNames []string
1520
tType := reflect.TypeOf(t)
@@ -75,10 +80,23 @@ func BulkInsert(parentCtx context.Context, dbTx Queryable, tableName string, col
7580
return ErrorLengthMismatch
7681
}
7782

78-
query := fmt.Sprintf("INSERT INTO %s (%s) VALUES %s %s", tableName, strings.Join(columns, ", "), generatePlaceholders(values), extraArgs)
79-
_, err := ExecWithTimeout(parentCtx, dbTx, query, flattenValues(values)...)
80-
if err != nil {
81-
return err
83+
maxRowsPerBatch := MaxPostgresParams / len(columns)
84+
for start := 0; start < len(values); start += maxRowsPerBatch {
85+
end := start + maxRowsPerBatch
86+
if end > len(values) {
87+
end = len(values)
88+
}
89+
90+
batchValues := values[start:end]
91+
query := fmt.Sprintf(
92+
"INSERT INTO %s (%s) VALUES %s %s",
93+
tableName, strings.Join(columns, ", "), generatePlaceholders(batchValues), extraArgs,
94+
)
95+
96+
_, err := ExecWithTimeout(parentCtx, dbTx, query, flattenValues(batchValues)...)
97+
if err != nil {
98+
return err
99+
}
82100
}
83101

84102
return nil

0 commit comments

Comments
 (0)
Please sign in to comment.