get( 'db_tables' ) ) { $job->set( 'db_tables', $info->tables( $wpdb->base_prefix ) ); $job->set( 'db_rows_total', array_sum( array_intersect_key( $info->rowEstimates(), array_flip( $job->get( 'db_tables' ) ) ) ) ); $job->set( 'db_max_packet', (int) $wpdb->get_var( 'SELECT @@max_allowed_packet' ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Direct execution required for site migration/reset routines. } $tables = (array) $job->get( 'db_tables' ); $path = Paths::job( $job->id() ) . '/dump.sql'; $file = (int) $job->cursor( 'file', 0 ); $handle = SafeFile::openAppend( $path, $file ); $options = ExportOptions::fromArray( (array) $job->get( 'options', array() ) ); $writer = new DumpWriter( $wpdb, $info, array( $options, 'rowFilter' ), $options->hasReplacements() ? array( $options, 'transform' ) : null ); if ( 0 === $file ) { $writer->writeHeader( $handle, (string) $wpdb->charset ); } $index = (int) $job->cursor( 'table', 0 ); $begun = (bool) $job->cursor( 'begun', false ); $after = (array) $job->cursor( 'after', array() ); $offset = (int) $job->cursor( 'offset', 0 ); $rows = (int) $job->cursor( 'rows', 0 ); $batch = Environment::dbBatchRows(); $max_stm = Environment::maxStatementBytes( (int) $job->get( 'db_max_packet', 0 ) ); while ( $index < count( $tables ) && ! $budget->exhausted() ) { $table = (string) $tables[ $index ]; if ( ! $begun ) { $writer->writeStructure( $handle, $table ); $begun = true; } $result = $writer->writeRows( $handle, $table, $after, $offset, $batch, $max_stm ); $after = $result['after']; $offset += $result['rows']; $rows += $result['rows']; if ( $result['done'] ) { SafeFile::writeAll( $handle, "\n" ); ++$index; $begun = false; $after = array(); $offset = 0; } // Everything up to here is complete and ends on a statement boundary. fflush( $handle ); $job->setCursor( 'file', (int) ftell( $handle ) ); $job->setCursor( 'table', $index ); $job->setCursor( 'begun', $begun ); $job->setCursor( 'after', $after ); $job->setCursor( 'offset', $offset ); $job->setCursor( 'rows', $rows ); $this->reportProgress( $job, $tables, $index, $rows ); $budget->unit(); } fclose( $handle ); if ( $index >= count( $tables ) ) { $job->set( 'db_rows_dumped', $rows ); return StageResult::next(); } return StageResult::more(); } /** * @param string[] $tables */ private function reportProgress( JobState $job, array $tables, int $index, int $rows ): void { $total = max( 1, (int) $job->get( 'db_rows_total', 0 ) ); // Row counts from SHOW TABLE STATUS are estimates. Fall back to table count when they are zero. $fraction = $job->get( 'db_rows_total', 0 ) > 0 ? $rows / $total : ( count( $tables ) > 0 ? $index / count( $tables ) : 1 ); $job->setStageProgress( min( 0.99, $fraction ) ); $job->setDetail( array( 'table' => $tables[ min( $index, count( $tables ) - 1 ) ] ?? '', 'tables_done' => $index, 'tables_total' => count( $tables ), 'rows' => $rows, ) ); } }