last), so the * cost of a batch does not grow with how deep into the table it is. Tables with no * primary key fall back to LIMIT/OFFSET, which is only stable if the table is not * being written to during the export. * * The caller owns the file handle and the cursor; nothing here keeps state between * calls except schema caches. */ final class DumpWriter { /** @var \wpdb */ private $db; /** @var TableInfo */ private $info; /** @var array|null */ private $avg_row_length = null; /** @var callable|null fn( string $table ): string, an extra WHERE condition. */ private $filter; /** @var callable|null fn( string $table, string $column, string $type, string $value ): string */ private $transform; public function __construct( \wpdb $db, TableInfo $info, ?callable $filter = null, ?callable $transform = null ) { $this->db = $db; $this->info = $info; $this->filter = $filter; $this->transform = $transform; } /** * @param resource $handle */ public function writeHeader( $handle, string $charset ): void { SafeFile::writeAll( $handle, "-- MigrateX database dump\n" . '-- Created ' . gmdate( 'c' ) . "\n" . '-- Charset ' . $charset . "\n\n" ); } /** * @param resource $handle * @throws \RuntimeException */ public function writeStructure( $handle, string $table ): void { $row = $this->db->get_row( 'SHOW CREATE TABLE ' . Sql::ident( $table ), ARRAY_N ); if ( '' !== $this->db->last_error || ! is_array( $row ) || ! isset( $row[1] ) ) { throw new \RuntimeException( sprintf( 'Cannot read the structure of table %s: %s', esc_html( $table ), esc_html( $this->db->last_error ) ) ); } SafeFile::writeAll( $handle, '-- Table ' . $table . "\n" . 'DROP TABLE IF EXISTS ' . Sql::ident( $table ) . ";\n" . $row[1] . ";\n\n" ); } /** * Dumps up to $limit rows after the given position. * * @param resource $handle * @param array $after Primary key values of the last row already dumped, or empty. * @param int $offset Rows already dumped; only used for tables without a primary key. * @param int $max_stmt Soft cap on the bytes of one INSERT statement. * @return array{rows:int,after:array,done:bool} * @throws \RuntimeException */ public function writeRows( $handle, string $table, array $after, int $offset, int $limit, int $max_stmt ): array { $columns = array_values( array_filter( $this->info->columns( $table ), static function ( $c ) { return ! $c['generated']; } ) ); if ( ! $columns ) { return array( 'rows' => 0, 'after' => array(), 'done' => true, ); } $key = $this->info->primaryKey( $table ); $limit = $this->capLimit( $table, $limit ); $select = 'SELECT ' . implode( ',', array_map( array( Sql::class, 'ident' ), array_column( $columns, 'name' ) ) ) . ' FROM ' . Sql::ident( $table ); $extra = null !== $this->filter ? (string) ( $this->filter )( $table ) : ''; $conditions = array(); if ( $key && $after ) { $conditions[] = Keyset::after( $this->info, $table, $key, $after ); } if ( '' !== $extra ) { $conditions[] = '(' . $extra . ')'; } if ( $conditions ) { $select .= ' WHERE ' . implode( ' AND ', $conditions ); } if ( $key ) { $select .= ' ORDER BY ' . implode( ',', array_map( array( Sql::class, 'ident' ), $key ) ) . ' LIMIT ' . (int) $limit; } else { $select .= ' LIMIT ' . (int) $limit . ' OFFSET ' . (int) $offset; } // Not $wpdb->get_results(): it holds a second reference to every row (a 10 MB value could not // be freed while it was written) and refuses table or column names with unusual characters. $conn = new Connection( $this->db ); $rows = $conn->select( $select, true ); if ( null === $rows ) { throw new \RuntimeException( sprintf( 'Cannot read rows of %s: %s', esc_html( $table ), esc_html( $conn->error() ) ) ); } $count = count( $rows ); $names = array_column( $columns, 'name' ); $types = array_column( $columns, 'type' ); $head = 'INSERT INTO ' . Sql::ident( $table ) . ' (' . implode( ',', array_map( array( Sql::class, 'ident' ), $names ) ) . ') VALUES '; $positions = array(); if ( $count && $key ) { foreach ( $key as $column ) { $position = array_search( $column, $names, true ); if ( false === $position ) { throw new \RuntimeException( sprintf( 'Primary key column %s of %s cannot be read.', esc_html( $column ), esc_html( $table ) ) ); } $positions[ $column ] = $position; } } $new_after = $after; $statement = ''; for ( $n = 0; $n < $count; $n++ ) { $row = $rows[ $n ]; $rows[ $n ] = null; if ( $positions && $n === $count - 1 ) { $new_after = array(); foreach ( $positions as $column => $position ) { $new_after[ $column ] = (string) $row[ $position ]; } } $values = array(); $length = 1 + count( $types ); // the two parentheses and the commas between values. foreach ( $types as $i => $type ) { $value = isset( $row[ $i ] ) ? (string) $row[ $i ] : null; if ( null !== $value && null !== $this->transform ) { $value = (string) ( $this->transform )( $table, $names[ $i ], $type, $value ); } $row[ $i ] = null; $literal = Sql::literal( $value, $type ); unset( $value ); $length += strlen( $literal ); $values[] = $literal; } if ( $length > $max_stmt ) { // Larger than a whole statement is allowed to be, so it is a statement of its own. Write // it value by value: gluing it into a tuple and then onto a statement would hold three // more copies of it in memory at once. if ( '' !== $statement ) { SafeFile::writeAll( $handle, $statement . ";\n" ); $statement = ''; } SafeFile::writeAll( $handle, $head . '(' ); foreach ( $values as $i => $literal ) { SafeFile::writeAll( $handle, ( $i > 0 ? ',' : '' ) . $literal ); $values[ $i ] = null; } SafeFile::writeAll( $handle, ");\n" ); continue; } $tuple = '(' . implode( ',', $values ) . ')'; if ( '' !== $statement && strlen( $statement ) + strlen( $tuple ) > $max_stmt ) { SafeFile::writeAll( $handle, $statement . ";\n" ); $statement = ''; } $statement .= ( '' === $statement ? $head : ',' ) . $tuple; } if ( '' !== $statement ) { SafeFile::writeAll( $handle, $statement . ";\n" ); } return array( 'rows' => $count, 'after' => $new_after, 'done' => $count < $limit, ); } /** * Keeps a batch of wide rows from exceeding roughly 8 MB in memory. */ private function capLimit( string $table, int $limit ): int { if ( null === $this->avg_row_length ) { $this->avg_row_length = $this->info->averageRowLengths(); } $avg = $this->avg_row_length[ $table ] ?? 0; if ( $avg > 0 ) { $limit = min( $limit, max( 10, (int) floor( 8 * 1024 * 1024 / $avg ) ) ); } return max( 1, $limit ); } }