forked from xataio/pgstream
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpg_pg_batch_coalesce_integration_test.go
More file actions
360 lines (314 loc) · 10.8 KB
/
Copy pathpg_pg_batch_coalesce_integration_test.go
File metadata and controls
360 lines (314 loc) · 10.8 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
// SPDX-License-Identifier: Apache-2.0
package integration
import (
"context"
"fmt"
"os"
"strings"
"testing"
"time"
"github.com/stretchr/testify/require"
pglib "github.com/xataio/pgstream/internal/postgres"
"github.com/xataio/pgstream/pkg/backoff"
"github.com/xataio/pgstream/pkg/stream"
"github.com/xataio/pgstream/pkg/wal/processor/batch"
"github.com/xataio/pgstream/pkg/wal/processor/postgres"
)
// Test_PostgresToPostgres_BatchCoalesce validates that the batch writer correctly
// coalesces consecutive same-table DML events into bulk SQL statements.
// It uses a large batch size so multiple events accumulate in a single batch.
func Test_PostgresToPostgres_BatchCoalesce(t *testing.T) {
if os.Getenv("PGSTREAM_INTEGRATION_TESTS") == "" {
t.Skip("skipping integration test...")
}
cfg := &stream.Config{
Listener: testPostgresListenerCfg(t),
Processor: stream.ProcessorConfig{
Postgres: &stream.PostgresProcessorConfig{
BatchWriter: postgres.Config{
URL: targetPGURL,
BatchConfig: batch.Config{
// Large batch size to accumulate multiple events per batch.
// This forces the coalescing logic to run.
MaxBatchSize: 500,
BatchTimeout: 500 * time.Millisecond,
},
RetryPolicy: backoff.Config{
DisableRetries: true,
},
},
},
},
}
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
runStream(t, ctx, cfg)
testTable := "pg2pg_batch_coalesce_test"
targetConn, err := pglib.NewConn(ctx, targetPGURL)
require.NoError(t, err)
defer targetConn.Close(ctx)
// Step 1: Create the table
execQuery(t, ctx, fmt.Sprintf(
"CREATE TABLE %s (id serial PRIMARY KEY, name text, value int)", testTable))
defer execQuery(t, ctx, fmt.Sprintf("DROP TABLE IF EXISTS %s", testTable))
require.Eventually(t, func() bool {
cols := getInformationSchemaColumns(t, ctx, targetConn, testTable)
return len(cols) == 3
}, 20*time.Second, 200*time.Millisecond, "table schema not replicated")
// Step 2: Bulk insert — 200 rows in a single transaction so they arrive
// as a contiguous run of "I" events in one batch.
numRows := 200
execQuery(t, ctx, buildBulkInsert(testTable, numRows))
require.Eventually(t, func() bool {
var count int
err := targetConn.QueryRow(ctx, []any{&count},
fmt.Sprintf("SELECT count(*) FROM %s", testTable))
if err != nil {
return false
}
return count == numRows
}, 30*time.Second, 500*time.Millisecond, "bulk insert rows not replicated")
// Verify data integrity — spot-check first and last rows
require.Eventually(t, func() bool {
var name string
var value int
err := targetConn.QueryRow(ctx, []any{&name, &value},
fmt.Sprintf("SELECT name, value FROM %s WHERE id = 1", testTable))
if err != nil {
return false
}
return name == "row_1" && value == 1
}, 10*time.Second, 200*time.Millisecond)
require.Eventually(t, func() bool {
var name string
var value int
err := targetConn.QueryRow(ctx, []any{&name, &value},
fmt.Sprintf("SELECT name, value FROM %s WHERE id = %d", testTable, numRows))
if err != nil {
return false
}
return name == fmt.Sprintf("row_%d", numRows) && value == numRows
}, 10*time.Second, 200*time.Millisecond)
// Step 3: Bulk delete — delete 100 rows in a single transaction.
// These should coalesce into a bulk DELETE ... WHERE id = ANY($1::int4[]).
deleteCount := 100
execQuery(t, ctx, fmt.Sprintf(
"DELETE FROM %s WHERE id <= %d", testTable, deleteCount))
require.Eventually(t, func() bool {
var count int
err := targetConn.QueryRow(ctx, []any{&count},
fmt.Sprintf("SELECT count(*) FROM %s", testTable))
if err != nil {
return false
}
return count == numRows-deleteCount
}, 30*time.Second, 500*time.Millisecond, "bulk delete not replicated")
// Verify deleted rows are gone and remaining rows are intact
require.Eventually(t, func() bool {
var count int
err := targetConn.QueryRow(ctx, []any{&count},
fmt.Sprintf("SELECT count(*) FROM %s WHERE id <= %d", testTable, deleteCount))
if err != nil {
return false
}
return count == 0
}, 10*time.Second, 200*time.Millisecond)
require.Eventually(t, func() bool {
var minID int
err := targetConn.QueryRow(ctx, []any{&minID},
fmt.Sprintf("SELECT min(id) FROM %s", testTable))
if err != nil {
return false
}
return minID == deleteCount+1
}, 10*time.Second, 200*time.Millisecond)
// Step 4: Bulk update — update remaining rows. Updates are not coalesced
// (handled individually) so this tests the non-coalesced path in a batch.
execQuery(t, ctx, fmt.Sprintf(
"UPDATE %s SET name = 'updated_' || id::text", testTable))
require.Eventually(t, func() bool {
var count int
err := targetConn.QueryRow(ctx, []any{&count},
fmt.Sprintf("SELECT count(*) FROM %s WHERE name LIKE 'updated_%%'", testTable))
if err != nil {
return false
}
return count == numRows-deleteCount
}, 30*time.Second, 500*time.Millisecond, "bulk update not replicated")
// Step 5: Mixed operations — insert + update + delete interleaved.
// This tests that run boundaries are correctly flushed when the action changes.
execQuery(t, ctx, fmt.Sprintf(
"INSERT INTO %s(name, value) VALUES('mixed_1', 1000), ('mixed_2', 2000)", testTable))
execQuery(t, ctx, fmt.Sprintf(
"UPDATE %s SET value = 9999 WHERE name = 'mixed_1'", testTable))
execQuery(t, ctx, fmt.Sprintf(
"DELETE FROM %s WHERE name = 'mixed_2'", testTable))
require.Eventually(t, func() bool {
var name string
var value int
err := targetConn.QueryRow(ctx, []any{&name, &value},
fmt.Sprintf("SELECT name, value FROM %s WHERE name = 'mixed_1'", testTable))
if err != nil {
return false
}
return value == 9999
}, 20*time.Second, 500*time.Millisecond, "mixed insert+update not replicated")
require.Eventually(t, func() bool {
var count int
err := targetConn.QueryRow(ctx, []any{&count},
fmt.Sprintf("SELECT count(*) FROM %s WHERE name = 'mixed_2'", testTable))
if err != nil {
return false
}
return count == 0
}, 20*time.Second, 500*time.Millisecond, "mixed delete not replicated")
}
// Test_PostgresToPostgres_BatchCoalesce_WithCompositeKey validates coalescing
// for tables with composite primary keys.
func Test_PostgresToPostgres_BatchCoalesce_WithCompositeKey(t *testing.T) {
if os.Getenv("PGSTREAM_INTEGRATION_TESTS") == "" {
t.Skip("skipping integration test...")
}
cfg := &stream.Config{
Listener: testPostgresListenerCfg(t),
Processor: stream.ProcessorConfig{
Postgres: &stream.PostgresProcessorConfig{
BatchWriter: postgres.Config{
URL: targetPGURL,
BatchConfig: batch.Config{
MaxBatchSize: 500,
BatchTimeout: 500 * time.Millisecond,
},
RetryPolicy: backoff.Config{
DisableRetries: true,
},
},
},
},
}
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
runStream(t, ctx, cfg)
testTable := "pg2pg_batch_coalesce_composite_test"
targetConn, err := pglib.NewConn(ctx, targetPGURL)
require.NoError(t, err)
defer targetConn.Close(ctx)
// Create table with composite primary key
execQuery(t, ctx, fmt.Sprintf(
"CREATE TABLE %s (tenant_id int, item_id int, name text, PRIMARY KEY(tenant_id, item_id))",
testTable))
defer execQuery(t, ctx, fmt.Sprintf("DROP TABLE IF EXISTS %s", testTable))
require.Eventually(t, func() bool {
cols := getInformationSchemaColumns(t, ctx, targetConn, testTable)
return len(cols) == 3
}, 20*time.Second, 200*time.Millisecond, "table schema not replicated")
// Bulk insert rows with composite key
numRows := 50
execQuery(t, ctx, buildCompositeKeyBulkInsert(testTable, numRows))
require.Eventually(t, func() bool {
var count int
err := targetConn.QueryRow(ctx, []any{&count},
fmt.Sprintf("SELECT count(*) FROM %s", testTable))
if err != nil {
return false
}
return count == numRows
}, 30*time.Second, 500*time.Millisecond, "composite key bulk insert not replicated")
// Bulk delete half the rows — these use composite PK IN tuples path
execQuery(t, ctx, fmt.Sprintf(
"DELETE FROM %s WHERE item_id <= %d", testTable, numRows/2))
require.Eventually(t, func() bool {
var count int
err := targetConn.QueryRow(ctx, []any{&count},
fmt.Sprintf("SELECT count(*) FROM %s", testTable))
if err != nil {
return false
}
return count == numRows/2
}, 30*time.Second, 500*time.Millisecond, "composite key bulk delete not replicated")
}
// Test_PostgresToPostgres_BatchCoalesce_OnConflict validates coalesced inserts
// with ON CONFLICT DO NOTHING.
func Test_PostgresToPostgres_BatchCoalesce_OnConflict(t *testing.T) {
if os.Getenv("PGSTREAM_INTEGRATION_TESTS") == "" {
t.Skip("skipping integration test...")
}
cfg := &stream.Config{
Listener: testPostgresListenerCfg(t),
Processor: stream.ProcessorConfig{
Postgres: &stream.PostgresProcessorConfig{
BatchWriter: postgres.Config{
URL: targetPGURL,
OnConflictAction: "nothing",
BatchConfig: batch.Config{
MaxBatchSize: 500,
BatchTimeout: 500 * time.Millisecond,
},
RetryPolicy: backoff.Config{
DisableRetries: true,
},
},
},
},
}
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
runStream(t, ctx, cfg)
testTable := "pg2pg_batch_coalesce_conflict_test"
targetConn, err := pglib.NewConn(ctx, targetPGURL)
require.NoError(t, err)
defer targetConn.Close(ctx)
// Create table
execQuery(t, ctx, fmt.Sprintf(
"CREATE TABLE %s (id serial PRIMARY KEY, name text)", testTable))
defer execQuery(t, ctx, fmt.Sprintf("DROP TABLE IF EXISTS %s", testTable))
require.Eventually(t, func() bool {
cols := getInformationSchemaColumns(t, ctx, targetConn, testTable)
return len(cols) == 2
}, 20*time.Second, 200*time.Millisecond)
// Insert rows
numRows := 50
execQuery(t, ctx, buildSimpleBulkInsert(testTable, numRows))
require.Eventually(t, func() bool {
var count int
err := targetConn.QueryRow(ctx, []any{&count},
fmt.Sprintf("SELECT count(*) FROM %s", testTable))
if err != nil {
return false
}
return count == numRows
}, 30*time.Second, 500*time.Millisecond, "on-conflict insert rows not replicated")
}
func buildBulkInsert(table string, n int) string {
var b strings.Builder
fmt.Fprintf(&b, "INSERT INTO %s(name, value) VALUES", table)
for i := 1; i <= n; i++ {
if i > 1 {
b.WriteByte(',')
}
fmt.Fprintf(&b, "('row_%d', %d)", i, i)
}
return b.String()
}
func buildSimpleBulkInsert(table string, n int) string {
var b strings.Builder
fmt.Fprintf(&b, "INSERT INTO %s(name) VALUES", table)
for i := 1; i <= n; i++ {
if i > 1 {
b.WriteByte(',')
}
fmt.Fprintf(&b, "('row_%d')", i)
}
return b.String()
}
func buildCompositeKeyBulkInsert(table string, n int) string {
var b strings.Builder
fmt.Fprintf(&b, "INSERT INTO %s(tenant_id, item_id, name) VALUES", table)
for i := 1; i <= n; i++ {
if i > 1 {
b.WriteByte(',')
}
fmt.Fprintf(&b, "(1, %d, 'item_%d')", i, i)
}
return b.String()
}