@@ -237,6 +237,8 @@ export const dbTestUtilFactory = (): any => ({
237237 let hasIndexTables = false
238238
239239 const tablesToTruncate : string [ ] = [ ]
240+ const allTablesToVerify : string [ ] = [ ]
241+
240242 for ( const { table_name } of tableNames ) {
241243 if ( mainPartitionTables . includes ( table_name ) ) {
242244 hasIndexTables = true
@@ -246,20 +248,61 @@ export const dbTestUtilFactory = (): any => ({
246248 table_name . startsWith ( skipIndexPartitionPrefix ) ||
247249 mainPartitionTables . includes ( table_name )
248250 ) {
251+ allTablesToVerify . push ( table_name )
249252 continue
250253 }
251254
252255 tablesToTruncate . push ( `${ schema } ."${ table_name } "` )
256+ allTablesToVerify . push ( table_name )
253257 }
254- if ( tablesToTruncate . length > 0 ) {
255- await runRawQuery ( `TRUNCATE ${ tablesToTruncate . join ( ", " ) } ;` )
258+
259+ const allTablesToTruncase = [
260+ ...tablesToTruncate ,
261+ ...( hasIndexTables ? mainPartitionTables : [ ] ) ,
262+ ] . join ( ", " )
263+
264+ if ( allTablesToTruncase ) {
265+ await runRawQuery ( `TRUNCATE ${ allTablesToTruncase } ;` )
256266 }
257267
258- if ( hasIndexTables ) {
259- await runRawQuery (
260- `TRUNCATE ${ schema } .index_data, ${ schema } .index_relation;`
261- )
268+ const verifyEmpty = async ( maxRetries = 5 ) => {
269+ for ( let retry = 0 ; retry < maxRetries ; retry ++ ) {
270+ const countQueries = allTablesToVerify . map (
271+ ( tableName ) =>
272+ `SELECT '${ tableName } ' as table_name, COUNT(*) as count FROM ${ schema } ."${ tableName } "`
273+ )
274+
275+ const { rows : counts } = await runRawQuery (
276+ countQueries . join ( " UNION ALL " )
277+ )
278+
279+ const nonEmptyTables = counts . filter (
280+ ( row : { table_name : string ; count : string } ) =>
281+ parseInt ( row . count ) > 0
282+ )
283+
284+ if ( nonEmptyTables . length === 0 ) {
285+ return true
286+ }
287+
288+ if ( retry < maxRetries - 1 ) {
289+ await new Promise ( ( resolve ) => setTimeout ( resolve , 100 ) )
290+ } else {
291+ const tableList = nonEmptyTables
292+ . map (
293+ ( t : { table_name : string ; count : string } ) =>
294+ `${ t . table_name } (${ t . count } )`
295+ )
296+ . join ( ", " )
297+ logger . warn (
298+ `Some tables still contain data after truncate: ${ tableList } `
299+ )
300+ }
301+ }
302+ return false
262303 }
304+
305+ await verifyEmpty ( )
263306 } catch ( error ) {
264307 logger . error ( "Error during database teardown:" , error )
265308 throw error
0 commit comments