@@ -3,13 +3,18 @@ package db
3
3
import (
4
4
"context"
5
5
"fmt"
6
+ "math"
6
7
"reflect"
7
8
"strings"
8
9
9
10
"github.com/jackc/pgx/v5"
10
11
"github.com/jackc/pgx/v5/pgconn"
11
12
)
12
13
14
+ const (
15
+ MaxPostgresParams = math .MaxUint16 // Max PostgreSQL limit
16
+ )
17
+
13
18
func getColumns (t interface {}) []string {
14
19
var fieldNames []string
15
20
tType := reflect .TypeOf (t )
@@ -75,10 +80,23 @@ func BulkInsert(parentCtx context.Context, dbTx Queryable, tableName string, col
75
80
return ErrorLengthMismatch
76
81
}
77
82
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
+ }
82
100
}
83
101
84
102
return nil
0 commit comments