@@ -274,7 +274,7 @@ WHERE oid = $1::regclass`,
274274 params : [ { value : table . qualifiedName , type : 'varchar' } ]
275275 } ) ;
276276 const row = results . rows [ 0 ] ;
277- if ( row ?. [ 0 ] ?? - 1n == - 1n ) {
277+ if ( ( row ?. [ 0 ] ?? - 1n ) == - 1n ) {
278278 return '?' ;
279279 } else {
280280 return `~${ row [ 0 ] } ` ;
@@ -374,8 +374,12 @@ WHERE oid = $1::regclass`,
374374 micro . logger . info ( `${ this . slot_name } Replicating ${ table . qualifiedName } ` ) ;
375375 const estimatedCount = await this . estimatedCount ( db , table ) ;
376376 let at = 0 ;
377+ let lastLogIndex = 0 ;
377378 const cursor = await db . stream ( { statement : `SELECT * FROM ${ table . escapedIdentifier } ` } ) ;
378379 let columns : { i : number ; name : string } [ ] = [ ] ;
380+ // pgwire streams rows in chunks.
381+ // These chunks can be quite small (as little as 16KB), so we don't flush chunks automatically.
382+
379383 for await ( let chunk of cursor ) {
380384 if ( chunk . tag == 'RowDescription' ) {
381385 let i = 0 ;
@@ -392,22 +396,21 @@ WHERE oid = $1::regclass`,
392396 }
393397 return q ;
394398 } ) ;
395- if ( at % 5000 == 0 && rows . length > 0 ) {
399+ if ( rows . length > 0 && at - lastLogIndex >= 5000 ) {
396400 micro . logger . info ( `${ this . slot_name } Replicating ${ table . qualifiedName } ${ at } /${ estimatedCount } ` ) ;
401+ lastLogIndex = at ;
397402 }
398403 if ( this . abort_signal . aborted ) {
399404 throw new Error ( `Aborted initial replication of ${ this . slot_name } ` ) ;
400405 }
401406
402407 for ( let record of WalStream . getQueryData ( rows ) ) {
408+ // This auto-flushes when the batch reaches its size limit
403409 await batch . save ( { tag : 'insert' , sourceTable : table , before : undefined , after : record } ) ;
404410 }
405411 at += rows . length ;
406412 Metrics . getInstance ( ) . rows_replicated_total . add ( rows . length ) ;
407413
408- // pgwire streaming uses reasonable chunk sizes, so we flush at the end
409- // of each chunk.
410- await batch . flush ( ) ;
411414 await touch ( ) ;
412415 }
413416
0 commit comments