-
Notifications
You must be signed in to change notification settings - Fork 76
Expand file tree
/
Copy pathbatch.go
More file actions
376 lines (339 loc) · 10.2 KB
/
Copy pathbatch.go
File metadata and controls
376 lines (339 loc) · 10.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
/*******************************************************************************
The MIT License (MIT)
Copyright (c) 2026 Alexey Kovyazin
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*******************************************************************************/
package firebirdsql
import (
"context"
"database/sql/driver"
"errors"
"fmt"
)
const defaultPreparedBatchFlushSize = 128 * 1024
// ErrBatchRowFailed marks a simplified per-row batch failure (no status vector).
var ErrBatchRowFailed = errors.New("batch row failed")
// BatchOptions configures batches created with PrepareBatch.
type BatchOptions struct {
BufferBytes int
ContinueOnError bool
DetailedErrors int
RecordCounts bool // default true when using zero value via PrepareBatch defaults
}
// BatchResult describes server completion from PreparedBatch.Exec.
type BatchResult struct {
Affected int64
UpdateCounts []int64
}
// BatchError is one row error from batch execution.
type BatchError struct {
Row int
Err error
}
// BatchExecutionError reports one or more row errors from batch execution.
type BatchExecutionError struct {
Errors []BatchError
}
func (e *BatchExecutionError) Error() string {
if e == nil || len(e.Errors) == 0 {
return "batch failed"
}
return fmt.Sprintf("batch failed at row %d: %v", e.Errors[0].Row, e.Errors[0].Err)
}
func (e *BatchExecutionError) Unwrap() []error {
if e == nil {
return nil
}
out := make([]error, len(e.Errors))
for i, be := range e.Errors {
out[i] = be.Err
}
return out
}
// PreparedBatch is a Firebird protocol-16+ DML batch. Obtain via PrepareBatch on
// the driver connection (sql.Conn.Raw).
type PreparedBatch struct {
fc *firebirdsqlConn
stmt *firebirdsqlStmt
opts BatchOptions
created bool
closed bool
encodedRows [][]byte
pendingBytes int
autoFlushSize int
paramBlr []byte
msgLen int32
}
// PrepareBatch prepares sql for batch DML (INSERT/UPDATE/DELETE with parameters).
// Requires negotiated wire protocol >= 16.
func (fc *firebirdsqlConn) PrepareBatch(ctx context.Context, sql string, opts BatchOptions) (*PreparedBatch, error) {
if fc == nil || fc.wp == nil {
return nil, driver.ErrBadConn
}
if fc.wp.protocolVersion < PROTOCOL_VERSION16 {
return nil, fmt.Errorf("firebirdsql: batch requires wire protocol 16+, got %d", fc.wp.protocolVersion)
}
if fc.tx.needBegin {
if err := fc.tx.begin(); err != nil {
return nil, err
}
}
stmt, err := newFirebirdsqlStmt(fc, sql)
if err != nil {
return nil, err
}
xs, err := fc.wp._fetchBindXsqlda(stmt.stmtHandle)
if err != nil {
_ = stmt.Close()
return nil, err
}
if xs == nil {
xs = []xSQLVAR{}
}
stmt.inputXsqlda = xs
if err := validateBatchStatement(stmt); err != nil {
_ = stmt.Close()
return nil, err
}
opts = normalizeBatchOptions(opts)
b := &PreparedBatch{
fc: fc,
stmt: stmt,
opts: opts,
autoFlushSize: defaultPreparedBatchFlushSize,
paramBlr: calcBlr(stmt.inputXsqlda),
msgLen: int32(calculateBatchMessageLength(stmt.inputXsqlda)),
}
stmt.activeBatch = b
_ = ctx
return b, nil
}
// normalizeBatchOptions applies fbx-compatible defaults: RecordCounts on,
// DetailedErrors=1 (or server default when ContinueOnError).
func normalizeBatchOptions(opts BatchOptions) BatchOptions {
opts.RecordCounts = true
if opts.ContinueOnError {
if opts.DetailedErrors == 0 {
opts.DetailedErrors = -1 // omit tag; use server default
}
} else if opts.DetailedErrors == 0 {
opts.DetailedErrors = 1
}
return opts
}
func validateBatchStatement(stmt *firebirdsqlStmt) error {
if len(stmt.inputXsqlda) == 0 {
return fmt.Errorf("statement used in batch must have parameters")
}
for i, x := range stmt.inputXsqlda {
if x.sqltype == SQL_TYPE_BLOB {
return fmt.Errorf("batch does not support blob parameters (arg %d)", i)
}
if x.sqltype == SQL_TYPE_ARRAY {
return fmt.Errorf("batch does not support array parameters (arg %d)", i)
}
}
if len(stmt.resultXsqlda) > 0 {
return fmt.Errorf("batch supports only insert, update, and delete statements without result sets")
}
switch stmt.stmtType {
case isc_info_sql_stmt_insert, isc_info_sql_stmt_update, isc_info_sql_stmt_delete:
return nil
default:
return fmt.Errorf("batch supports only insert, update, and delete statements without result sets")
}
}
func (b *PreparedBatch) parameterBuffer() []byte {
pb := newBatchPBWriter()
if b.opts.ContinueOnError {
pb.putInt32(batchTagMultiError, 1)
}
if b.opts.RecordCounts {
pb.putInt32(batchTagRecordCounts, 1)
}
if b.opts.DetailedErrors >= 0 {
pb.putInt32(batchTagDetailedErrors, int32(b.opts.DetailedErrors))
}
if b.opts.BufferBytes > 0 {
pb.putInt32(batchTagBufferBytes, int32(b.opts.BufferBytes))
}
pb.putByte(batchTagBlobPolicy, batchBlobIDUser)
return pb.bytes()
}
func (b *PreparedBatch) ensureCreated() error {
if b.closed {
return fmt.Errorf("prepared batch is closed")
}
if b.created {
return nil
}
if err := b.fc.wp.opBatchCreate(b.stmt.stmtHandle, b.paramBlr, b.msgLen, b.parameterBuffer()); err != nil {
return err
}
b.created = true
return nil
}
// PendingBytes returns the size of locally queued (unflushed) row data.
func (b *PreparedBatch) PendingBytes() int {
if b == nil {
return 0
}
return b.pendingBytes
}
// Add queues one parameter row.
func (b *PreparedBatch) Add(args ...driver.Value) error {
if b == nil || b.closed {
return fmt.Errorf("prepared batch is closed")
}
if len(args) != len(b.stmt.inputXsqlda) {
return fmt.Errorf("expected %d arguments, got %d", len(b.stmt.inputXsqlda), len(args))
}
for i, x := range b.stmt.inputXsqlda {
if x.sqltype == SQL_TYPE_BLOB || x.sqltype == SQL_TYPE_ARRAY {
return fmt.Errorf("batch does not support blob/array parameters (arg %d)", i)
}
if args[i] != nil {
if _, ok := args[i].([]byte); ok && x.sqltype == SQL_TYPE_BLOB {
return fmt.Errorf("batch does not support blob parameters (arg %d)", i)
}
}
}
row, err := b.fc.wp.encodeBatchRow(b.stmt.inputXsqlda, args)
if err != nil {
return err
}
if b.autoFlushSize > 0 && b.pendingBytes > 0 && b.pendingBytes+len(row) > b.autoFlushSize {
if err := b.Flush(context.Background()); err != nil {
return err
}
}
b.encodedRows = append(b.encodedRows, row)
b.pendingBytes += len(row)
return nil
}
// Flush sends queued rows to the server batch buffer without executing.
func (b *PreparedBatch) Flush(ctx context.Context) error {
if b == nil || b.closed {
return fmt.Errorf("prepared batch is closed")
}
if len(b.encodedRows) == 0 {
return nil
}
if err := b.ensureCreated(); err != nil {
return err
}
rows := b.encodedRows
b.encodedRows = nil
b.pendingBytes = 0
_ = ctx
return b.fc.wp.opBatchMsg(b.stmt.stmtHandle, rows)
}
// Exec flushes remaining rows, executes the batch, and releases the server batch.
func (b *PreparedBatch) Exec(ctx context.Context) (*BatchResult, error) {
if b == nil || b.closed {
return nil, fmt.Errorf("prepared batch is closed")
}
if err := b.Flush(ctx); err != nil {
return nil, err
}
if !b.created {
return &BatchResult{}, nil
}
if err := b.fc.wp.opBatchExec(b.stmt.stmtHandle, b.fc.tx.transHandle); err != nil {
return nil, err
}
var completion *batchCompletion
defer b.stmt.enforceDeadline(ctx)()
err := b.stmt.withCancelWatcher(ctx, func() error {
var e error
completion, e = b.fc.wp.opBatchCompletion()
return e
})
if err != nil {
_ = b.fc.wp.opBatchRelease(b.stmt.stmtHandle, op_batch_rls)
b.created = false
return nil, err
}
res := &BatchResult{Affected: completion.affected()}
if len(completion.UpdateCounts) > 0 {
res.UpdateCounts = make([]int64, len(completion.UpdateCounts))
for i, u := range completion.UpdateCounts {
res.UpdateCounts[i] = int64(u)
}
}
var batchErr error
if completion.hasErrors() {
be := &BatchExecutionError{}
for _, de := range completion.DetailedErrors {
be.Errors = append(be.Errors, BatchError{Row: int(de.Row), Err: de.Err})
}
for _, row := range completion.SimplifiedErrors {
be.Errors = append(be.Errors, BatchError{Row: int(row), Err: ErrBatchRowFailed})
}
batchErr = be
}
// Release server batch after exec (fbx high-level always closes wire batch).
_ = b.fc.wp.opBatchRelease(b.stmt.stmtHandle, op_batch_rls)
b.created = false
if b.fc.tx.isAutocommit {
if batchErr != nil {
_ = b.fc.tx.Rollback()
} else if cerr := b.fc.tx.commitRetainging(); cerr != nil {
return res, cerr
}
}
if batchErr != nil {
return res, batchErr
}
return res, nil
}
// Cancel clears local queue and releases the server batch (op_batch_rls).
func (b *PreparedBatch) Cancel(ctx context.Context) error {
if b == nil || b.closed {
return nil
}
b.encodedRows = nil
b.pendingBytes = 0
if !b.created {
return nil
}
err := b.fc.wp.opBatchRelease(b.stmt.stmtHandle, op_batch_rls)
b.created = false
_ = ctx
return err
}
// Close releases resources. Safe to call multiple times.
func (b *PreparedBatch) Close() error {
if b == nil || b.closed {
return nil
}
_ = b.Cancel(context.Background())
b.closed = true
if b.stmt != nil {
b.stmt.activeBatch = nil
err := b.stmt.Close()
b.stmt = nil
return err
}
return nil
}
func (b *PreparedBatch) releaseBeforeFree() {
if b == nil || !b.created {
return
}
_ = b.fc.wp.opBatchRelease(b.stmt.stmtHandle, op_batch_rls)
b.created = false
}