id() ) . '/staging/' . Format::DATABASE; $size = (int) filesize( $path ); $conn = new Connection( $wpdb, (string) $job->get( 'charset', '' ) ); $src = (string) $job->get( 'src_prefix' ); $dst = (string) $job->get( 'dst_prefix' ); if ( ! $job->cursor( 'started' ) ) { TempTables::dropAll( $wpdb, TempTables::TMP ); TempTables::dropAll( $wpdb, TempTables::OLD ); $job->set( 'tmp_tables', array() ); $job->setCursor( 'started', true ); $job->setCursor( 'off', 0 ); $job->setCursor( 'statements', 0 ); } $conn->prepareSession(); $handle = fopen( $path, 'rb' ); if ( false === $handle ) { return StageResult::fail( 'om_read', __( 'Cannot read the database file from the archive.', 'migratex' ) ); } $reader = new SqlReader( $handle, (int) $job->cursor( 'off', 0 ) ); $tables = (array) $job->get( 'tmp_tables', array() ); $count = (int) $job->cursor( 'statements', 0 ); $replay = null !== $job->cursor( 'pending_to' ); try { while ( ! $budget->exhausted() ) { $batch = array(); $offsets = array(); $bytes = 0; while ( count( $batch ) < self::BATCH_STATEMENTS && $bytes < self::BATCH_BYTES ) { $statement = $reader->next(); if ( null === $statement ) { break; } $batch[] = $statement; $offsets[] = $reader->offset(); $bytes += strlen( $statement ); } if ( ! $batch ) { return $this->finish( $job, $tables ); } $end = (int) end( $offsets ); if ( ! $replay ) { // Write-ahead: record where this batch ends before running it. $job->setCursor( 'pending_to', $end ); $budget->commit(); } foreach ( array_keys( $batch ) as $n ) { $error = $this->execute( $conn, $batch[ $n ], $src, $dst, $replay, $tables, $job ); if ( null !== $error ) { return StageResult::fail( 'om_sql', $error ); } } $count += count( $batch ); $replay = false; $job->set( 'tmp_tables', $tables ); $job->setCursor( 'off', $end ); $job->setCursor( 'pending_to', null ); $job->setCursor( 'statements', $count ); $job->setStageProgress( min( 0.99, $end / max( 1, $size ) ) ); $job->setDetail( array( 'tables' => count( $tables ), 'statements' => $count, 'bytes' => $end, 'total_bytes' => $size, ) ); $budget->commit(); $budget->unit(); } } catch ( \RuntimeException $e ) { return StageResult::fail( 'om_sql_file', $e->getMessage() ); } finally { fclose( $handle ); } return StageResult::more(); } /** * @param string $statement Taken by reference and emptied once its rewritten copy exists, so a * 10 MB INSERT is held once, not twice, while it runs. * @param string[] $tables Scratch tables created so far; appended to on CREATE. * @return string|null An error message, or null on success. */ private function execute( Connection $conn, string &$statement, string $src, string $dst, bool $replay, array &$tables, JobState $job ): ?string { if ( 1 !== preg_match( '/^(DROP TABLE IF EXISTS|CREATE TABLE|INSERT INTO)\s+`((?:[^`]|``)+)`/i', $statement, $m, PREG_OFFSET_CAPTURE ) ) { return null; // Not one of the three permitted kinds; ignore it. } $kind = strtoupper( preg_replace( '/\s+/', ' ', $m[1][0] ) ); $name = str_replace( '``', '`', $m[2][0] ); // Only the plain forms this plugin writes are accepted. That rules out // CREATE TABLE ... AS SELECT / LIKE and INSERT ... SELECT, which could copy // data between tables rather than restore it. $rest = substr( $statement, $m[2][1] + strlen( $m[2][0] ) + 1, 600 ); if ( ! $this->isPlainForm( $kind, $rest ) ) { Logger::log( $job->id(), 'Ignored an unexpected ' . $kind . ' form.' ); return null; } if ( 0 !== strpos( $name, $src ) ) { Logger::log( $job->id(), 'Ignored statement for a table outside the site prefix: ' . substr( $name, 0, 80 ) ); return null; } $destination = $dst . substr( $name, strlen( $src ) ); $scratch = TempTables::tmpName( $destination ); if ( null === $scratch ) { return sprintf( /* translators: %s: table name */ __( 'The table name "%s" is too long to restore safely.', 'migratex' ), $destination ); } $rewritten = substr_replace( $statement, Sql::ident( $scratch ), $m[2][1] - 1, strlen( $m[2][0] ) + 2 ); $snippet = substr( $statement, 0, 200 ); // all the error message below needs of it. $statement = ''; if ( 'CREATE TABLE' === $kind ) { $rewritten = $this->applyKnownFixes( $rewritten, $job ); } if ( ! $conn->exec( $rewritten ) ) { if ( 'CREATE TABLE' === $kind && $this->retryCreate( $conn, $rewritten, $job ) ) { // Created after adjusting collations; carry on. } elseif ( $replay && in_array( $conn->errno(), array( self::ER_DUP_ENTRY, self::ER_TABLE_EXISTS ), true ) ) { // Already applied by the attempt that was interrupted. } else { return sprintf( /* translators: 1: MySQL error, 2: start of the failing statement */ __( 'Database import failed: %1$s (near: %2$s)', 'migratex' ), $conn->error(), substr( preg_replace( '/\s+/', ' ', $snippet ), 0, 90 ) ); } } if ( 'CREATE TABLE' === $kind && ! in_array( $scratch, $tables, true ) ) { $tables[] = $scratch; } return null; } /** * @param string $rest The start of the statement after the table name. */ private function isPlainForm( string $kind, string $rest ): bool { switch ( $kind ) { case 'DROP TABLE IF EXISTS': return 1 === preg_match( '/^\s*$/', $rest ); case 'CREATE TABLE': return 1 === preg_match( '/^\s*\(/', $rest ); default: // INSERT INTO return 1 === preg_match( '/^\s*(?:\((?:\s*`(?:[^`]|``)+`\s*,?)+\s*\)\s*)?VALUES\s*\(/i', $rest ); } } /** * Archives from MySQL 8 or MariaDB may name collations an older server lacks. * Once a substitution has worked it is reused for every later table. */ private function retryCreate( Connection $conn, string $sql, JobState $job ): bool { if ( ! in_array( $conn->errno(), array( 1273, 1253, 1115, 1366 ), true ) ) { return false; } $fixed = (string) preg_replace( '/\butf8mb4_[a-z0-9_]*(?:0900|uca1400|520)[a-z0-9_]*/i', 'utf8mb4_unicode_ci', $sql ); if ( $fixed === $sql || ! $conn->exec( $fixed ) ) { return false; } $job->set( 'fix_collations', true ); Logger::log( $job->id(), 'Replaced a collation this server does not support with utf8mb4_unicode_ci.' ); return true; } private function applyKnownFixes( string $sql, JobState $job ): string { if ( ! $job->get( 'fix_collations' ) ) { return $sql; } return (string) preg_replace( '/\butf8mb4_[a-z0-9_]*(?:0900|uca1400|520)[a-z0-9_]*/i', 'utf8mb4_unicode_ci', $sql ); } /** * @param string[] $tables */ private function finish( JobState $job, array $tables ): StageResult { $dst = (string) $job->get( 'dst_prefix' ); foreach ( array( 'options', 'users', 'usermeta' ) as $required ) { if ( ! in_array( TempTables::TMP . $dst . $required, $tables, true ) ) { return StageResult::fail( 'om_incomplete_database', sprintf( /* translators: %s: table name */ __( 'The archive database is incomplete: the %s table is missing.', 'migratex' ), $dst . $required ) ); } } $job->set( 'tmp_tables', $tables ); return StageResult::next(); } }