refactor(migration): 回填 Migration Phase Strategy 體系(PR-D)
A v3.0.1 把 orchestrator 的 11 個 phase 抽成可注入的 Phase 物件,B 仍是 1107 行單體、以 'phase_' . $current 字串魔法分派、completed 甚至 inline 在 tick() 裡。本 commit 對齊: 新增 13 檔 - includes/migration/interface-migration-phase.php - includes/migration/class-tmdo-migration-phase-base.php(log/get_managed_keys/ execute_bulk_pivot/values_loose_equal 等共用 helper) - includes/migration/phases/ 11 個 phase 類別 orchestrator 1107 → 640 行 - tick() 改 make_phase() 工廠 + $phase->execute($job) - 移除 final、self::ENTITY_TYPE → static::(A v3.3.0 late static binding) - 保留 B 原有的 '✓ %s (%.2fs)' 耗時 log(改為 tick 自行量測,A 版已簡化掉) - 公開介面(preflight/start/tick/get_status/cancel/resume/needs_attention/ cron_tick)經 diff 確認與 A 完全一致,呼叫端零影響 連帶 - Schema_Manager 補 table_exists 的 request-scoped cache 與 flush_table_exists_cache()(A v3.1.6 + v3.4.6),Phase 測試需要它 - back-compat 補 12 個 Phase 類別的 WPDO_ alias - 移植 MigrationPhaseTest + MigrationPhaseRemainingTest(527 行) 測試隔離差異(B 的 unit bootstrap 會載入 Member_Fields / Post_Fields, A 的不會):MigrationPhaseRemainingTest 的 setUp 需額外清空 Entity_Registry 與 wpdo_register_entity_fields listener,否則 install_schema 會真的走進 dbDelta。MigrationPhaseTest 的 interface 斷言改用 TMDO_ 正式名稱 (PHP 無法 class_alias 介面,且該契約是核心內部擴充點)。 unit 451 / integration 398 GREEN Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01TbG1keQQ7XBa7qMQY16KCY
This commit is contained in:
@@ -0,0 +1,62 @@
|
||||
<?php
|
||||
/**
|
||||
* Migration phase: bulk pivot text-only meta groups via INSERT … SELECT.
|
||||
*
|
||||
* @package TMDO
|
||||
* @since 3.0.1
|
||||
*/
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit;
|
||||
}
|
||||
|
||||
/**
|
||||
* Iterates all registered groups for the entity type and pivots each
|
||||
* text-only group in a single INSERT … SELECT … ON DUPLICATE KEY UPDATE.
|
||||
*/
|
||||
class TMDO_Phase_Backfill_Bulk extends TMDO_Migration_Phase_Base {
|
||||
|
||||
/**
|
||||
* Returns the phase slug.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function name(): string {
|
||||
return 'backfill_bulk';
|
||||
}
|
||||
|
||||
/**
|
||||
* Executes the phase.
|
||||
*
|
||||
* @param array $job Job array (by reference).
|
||||
* @return array{status: string}
|
||||
* @throws \RuntimeException On DB pivot failure.
|
||||
*/
|
||||
public function execute( array &$job ): array {
|
||||
if ( ! empty( $job['options']['dry_run'] ) ) {
|
||||
$this->log( $job, '↪ Backfill bulk skipped (dry_run)' );
|
||||
return array( 'status' => 'ok' );
|
||||
}
|
||||
|
||||
$total_groups = 0;
|
||||
$total_rows = 0;
|
||||
|
||||
foreach ( TMDO_Entity_Registry::get_groups_for_type( $this->entity_type ) as $group ) {
|
||||
if ( $this->group_has_json_field( $group ) ) {
|
||||
continue; // Handled in backfill_unserialize.
|
||||
}
|
||||
$rows = $this->execute_bulk_pivot( $group );
|
||||
$total_rows += $rows;
|
||||
++$total_groups;
|
||||
$this->log( $job, sprintf( ' • bulk pivot %s: %d row(s)', $group, $rows ) );
|
||||
}
|
||||
|
||||
$this->log( $job, sprintf( 'Bulk backfill: %d groups, %d rows total', $total_groups, $total_rows ) );
|
||||
|
||||
$preflight = TMDO_Migration_Orchestrator::preflight();
|
||||
$job['metrics']['eav_rows_now'] = $preflight['eav_rows'];
|
||||
$job['metrics']['ratio_now'] = $preflight['ratio'];
|
||||
|
||||
return array( 'status' => 'ok' );
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
<?php
|
||||
/**
|
||||
* Migration phase: row-by-row backfill for groups with JSON/serialized fields.
|
||||
*
|
||||
* @package TMDO
|
||||
* @since 3.0.1
|
||||
*/
|
||||
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit;
|
||||
}
|
||||
|
||||
/**
|
||||
* Uses TMDO_Entity_Migration_Engine for groups whose fields contain JSON type,
|
||||
* which cannot be bulk-pivoted via INSERT … SELECT.
|
||||
*/
|
||||
class TMDO_Phase_Backfill_Unserialize extends TMDO_Migration_Phase_Base {
|
||||
|
||||
/**
|
||||
* Returns the phase slug.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function name(): string {
|
||||
return 'backfill_unserialize';
|
||||
}
|
||||
|
||||
/**
|
||||
* Executes the phase.
|
||||
*
|
||||
* @param array $job Job array (by reference).
|
||||
* @return array{status: string}
|
||||
* @throws \RuntimeException On migration engine failure.
|
||||
*/
|
||||
public function execute( array &$job ): array {
|
||||
if ( ! empty( $job['options']['dry_run'] ) ) {
|
||||
$this->log( $job, '↪ Backfill unserialize skipped (dry_run)' );
|
||||
return array( 'status' => 'ok' );
|
||||
}
|
||||
|
||||
$total_rows = 0;
|
||||
|
||||
foreach ( TMDO_Entity_Registry::get_groups_for_type( $this->entity_type ) as $group ) {
|
||||
if ( ! $this->group_has_json_field( $group ) ) {
|
||||
continue; // Handled in backfill_bulk.
|
||||
}
|
||||
|
||||
$result = TMDO_Entity_Migration_Engine::migrate_group(
|
||||
$this->entity_type,
|
||||
$group,
|
||||
array( 'sleep_ms' => 0 )
|
||||
);
|
||||
|
||||
if ( ! empty( $result['error'] ) ) {
|
||||
throw new \RuntimeException( "Row-by-row backfill {$group} failed: " . $result['error'] );
|
||||
}
|
||||
if ( ( $result['errors'] ?? 0 ) > 0 && 0 === ( $result['migrated'] ?? 0 ) ) {
|
||||
throw new \RuntimeException( "All rows failed during {$group} backfill — see error_log" );
|
||||
}
|
||||
|
||||
$total_rows += (int) ( $result['migrated'] ?? 0 );
|
||||
$this->log( $job, sprintf( ' • row-by-row %s: %d row(s)', $group, $result['migrated'] ?? 0 ) );
|
||||
}
|
||||
|
||||
$this->log( $job, sprintf( 'Row-by-row backfill: %d rows total', $total_rows ) );
|
||||
return array( 'status' => 'ok' );
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,158 @@
|
||||
<?php
|
||||
/**
|
||||
* Migration phase: back up the native meta table before destructive cleanup.
|
||||
*
|
||||
* @package TMDO
|
||||
* @since 3.0.1
|
||||
*/
|
||||
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit;
|
||||
}
|
||||
|
||||
/**
|
||||
* Writes a mysqldump-style SQL file of the usermeta table to wp-content/uploads/wpdo-backups/.
|
||||
*/
|
||||
class TMDO_Phase_Backup extends TMDO_Migration_Phase_Base {
|
||||
|
||||
/**
|
||||
* Relative path under wp-content/uploads/ for backup files.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
const BACKUP_DIR_REL = 'wpdo-backups';
|
||||
|
||||
/**
|
||||
* Returns the phase slug.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function name(): string {
|
||||
return 'backup';
|
||||
}
|
||||
|
||||
/**
|
||||
* Executes the phase.
|
||||
*
|
||||
* @param array $job Job array (by reference).
|
||||
* @return array{status: string}
|
||||
* @throws \RuntimeException If backup directory or file cannot be created.
|
||||
*/
|
||||
public function execute( array &$job ): array {
|
||||
if ( empty( $job['options']['auto_backup'] ) ) {
|
||||
$this->log( $job, '↪ Backup skipped (auto_backup=false)' );
|
||||
return array( 'status' => 'ok' );
|
||||
}
|
||||
|
||||
$upload_dir = wp_upload_dir();
|
||||
$backup_dir = trailingslashit( $upload_dir['basedir'] ) . self::BACKUP_DIR_REL;
|
||||
|
||||
if ( ! wp_mkdir_p( $backup_dir ) ) {
|
||||
throw new \RuntimeException( "Cannot create backup directory: {$backup_dir}" );
|
||||
}
|
||||
|
||||
$this->write_web_deny_files( $backup_dir );
|
||||
|
||||
$filename = sprintf( 'wp_usermeta_%s_%s.sql', gmdate( 'Ymd_His' ), $job['job_id'] );
|
||||
$backup_path = $backup_dir . '/' . $filename;
|
||||
|
||||
global $wpdb;
|
||||
$rows = $wpdb->get_results(
|
||||
"SELECT umeta_id, user_id, meta_key, meta_value FROM {$wpdb->usermeta} ORDER BY umeta_id ASC", // phpcs:ignore WPDO.AntiEAV.no-direct-usermeta-select -- migration backup: must read raw usermeta to create full SQL dump before schema change
|
||||
ARRAY_A
|
||||
);
|
||||
|
||||
$fp = fopen( $backup_path, 'wb' );
|
||||
if ( ! $fp ) {
|
||||
throw new \RuntimeException( "Cannot open backup file for writing: {$backup_path}" );
|
||||
}
|
||||
// Owner-only read/write — backup contains user PII (emails, billing
|
||||
// addresses, OAuth tokens, session blobs).
|
||||
@chmod( $backup_path, 0600 );
|
||||
|
||||
fwrite( $fp, "-- WPDO migration backup of {$wpdb->usermeta}\n" );
|
||||
fwrite( $fp, '-- Job: ' . $job['job_id'] . "\n" );
|
||||
fwrite( $fp, '-- Generated: ' . gmdate( 'c' ) . "\n" );
|
||||
fwrite( $fp, "-- Restore: mysql ... < this_file.sql\n\n" );
|
||||
fwrite( $fp, "/*!40101 SET NAMES utf8mb4 */;\n" );
|
||||
fwrite( $fp, "/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;\n" );
|
||||
fwrite( $fp, "SET FOREIGN_KEY_CHECKS=0;\n" );
|
||||
fwrite( $fp, "LOCK TABLES `{$wpdb->usermeta}` WRITE;\n" );
|
||||
|
||||
$batch = array();
|
||||
$count = 0;
|
||||
foreach ( (array) $rows as $row ) {
|
||||
// UNHEX-encode meta_value: avoids escape edge cases (binary, embedded
|
||||
// NULs, non-UTF8, sql_mode mismatches at restore time).
|
||||
$batch[] = sprintf(
|
||||
"(%d,%d,'%s',UNHEX('%s'))",
|
||||
(int) $row['umeta_id'],
|
||||
(int) $row['user_id'],
|
||||
esc_sql( (string) $row['meta_key'] ),
|
||||
bin2hex( (string) ( $row['meta_value'] ?? '' ) )
|
||||
);
|
||||
++$count;
|
||||
if ( count( $batch ) >= 500 ) {
|
||||
fwrite( $fp, "INSERT INTO `{$wpdb->usermeta}` (umeta_id,user_id,meta_key,meta_value) VALUES\n" . implode( ",\n", $batch ) . ";\n" );
|
||||
$batch = array();
|
||||
}
|
||||
}
|
||||
if ( $batch ) {
|
||||
fwrite( $fp, "INSERT INTO `{$wpdb->usermeta}` (umeta_id,user_id,meta_key,meta_value) VALUES\n" . implode( ",\n", $batch ) . ";\n" );
|
||||
}
|
||||
fwrite( $fp, "UNLOCK TABLES;\n" );
|
||||
fwrite( $fp, "SET FOREIGN_KEY_CHECKS=1;\n" );
|
||||
fwrite( $fp, "/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;\n" );
|
||||
fclose( $fp );
|
||||
|
||||
$job['backup_path'] = $backup_path;
|
||||
$this->log(
|
||||
$job,
|
||||
sprintf(
|
||||
'Backup written: %s (%d rows, %s, chmod 0600)',
|
||||
$filename,
|
||||
$count,
|
||||
size_format( filesize( $backup_path ) )
|
||||
)
|
||||
);
|
||||
|
||||
$server = isset( $_SERVER['SERVER_SOFTWARE'] )
|
||||
? strtolower( sanitize_text_field( wp_unslash( (string) $_SERVER['SERVER_SOFTWARE'] ) ) )
|
||||
: '';
|
||||
if ( str_contains( $server, 'nginx' ) ) {
|
||||
$this->log( $job, '⚠ nginx detected: add `location ~ /wp-content/uploads/wpdo-backups/ { deny all; }` to your nginx config — .htaccess does not apply.' );
|
||||
}
|
||||
|
||||
return array( 'status' => 'ok' );
|
||||
}
|
||||
|
||||
/**
|
||||
* Writes .htaccess, web.config, and index.php deny files into the backup directory.
|
||||
*
|
||||
* @param string $backup_dir Absolute path to the backup directory.
|
||||
* @return void
|
||||
*/
|
||||
private function write_web_deny_files( string $backup_dir ): void {
|
||||
$htaccess = $backup_dir . '/.htaccess';
|
||||
if ( ! file_exists( $htaccess ) ) {
|
||||
file_put_contents( $htaccess, "Require all denied\n" );
|
||||
@chmod( $htaccess, 0644 );
|
||||
}
|
||||
|
||||
$webconfig = $backup_dir . '/web.config';
|
||||
if ( ! file_exists( $webconfig ) ) {
|
||||
file_put_contents(
|
||||
$webconfig,
|
||||
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<configuration><system.webServer><authorization><deny users=\"*\"/></authorization></system.webServer></configuration>\n"
|
||||
);
|
||||
@chmod( $webconfig, 0644 );
|
||||
}
|
||||
|
||||
$index = $backup_dir . '/index.php';
|
||||
if ( ! file_exists( $index ) ) {
|
||||
file_put_contents( $index, "<?php // Silence is golden.\n" );
|
||||
@chmod( $index, 0644 );
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
<?php
|
||||
/**
|
||||
* Migration phase: remove managed keys from the native meta table.
|
||||
*
|
||||
* @package TMDO
|
||||
* @since 3.0.1
|
||||
*/
|
||||
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit;
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes all managed meta keys from the EAV table after verifying aeav_only mode.
|
||||
*/
|
||||
class TMDO_Phase_Cleanup extends TMDO_Migration_Phase_Base {
|
||||
|
||||
/**
|
||||
* Returns the phase slug.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function name(): string {
|
||||
return 'cleanup';
|
||||
}
|
||||
|
||||
/**
|
||||
* Executes the phase.
|
||||
*
|
||||
* @param array $job Job array (by reference).
|
||||
* @return array{status: string}
|
||||
* @throws \RuntimeException If mode is not aeav_only or backup is missing.
|
||||
*/
|
||||
public function execute( array &$job ): array {
|
||||
global $wpdb;
|
||||
|
||||
if ( ! empty( $job['options']['dry_run'] ) ) {
|
||||
$this->log( $job, '↪ Cleanup skipped (dry_run)' );
|
||||
return array( 'status' => 'ok' );
|
||||
}
|
||||
|
||||
$mode = TMDO_Mode_Manager::get( $this->entity_type );
|
||||
if ( TMDO_Mode_Manager::MODE_AEAV_ONLY !== $mode ) {
|
||||
throw new \RuntimeException( "Refusing cleanup — mode is {$mode}, must be aeav_only" );
|
||||
}
|
||||
if ( ! empty( $job['options']['auto_backup'] ) && empty( $job['backup_path'] ) ) {
|
||||
throw new \RuntimeException( 'Refusing cleanup — auto_backup requested but no backup_path on record' );
|
||||
}
|
||||
|
||||
$keys = $this->get_managed_keys();
|
||||
if ( empty( $keys ) ) {
|
||||
$this->log( $job, '↪ No managed keys to clean' );
|
||||
return array( 'status' => 'ok' );
|
||||
}
|
||||
|
||||
$adapter = TMDO_Entity_Registry::get_adapter( $this->entity_type );
|
||||
$meta_table = $adapter->get_native_meta_table();
|
||||
$placeholders = implode( ',', array_fill( 0, count( $keys ), '%s' ) );
|
||||
$deleted = (int) $wpdb->query(
|
||||
$wpdb->prepare( "DELETE FROM `{$meta_table}` WHERE meta_key IN ({$placeholders})", ...$keys )
|
||||
);
|
||||
|
||||
$preflight = TMDO_Migration_Orchestrator::preflight();
|
||||
$job['metrics']['eav_rows_now'] = $preflight['eav_rows'];
|
||||
$job['metrics']['ratio_now'] = $preflight['ratio'];
|
||||
|
||||
$this->log( $job, sprintf( 'Cleanup: deleted %d EAV row(s); ratio now %s', $deleted, (string) $preflight['ratio'] ) );
|
||||
return array( 'status' => 'ok' );
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
<?php
|
||||
/**
|
||||
* Migration phase: terminal phase marking the job as successfully completed.
|
||||
*
|
||||
* @package TMDO
|
||||
* @since 3.0.1
|
||||
*/
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit;
|
||||
}
|
||||
|
||||
/**
|
||||
* Terminal phase — marks the job as successfully completed.
|
||||
*
|
||||
* Returns 'done' (instead of 'ok') so tick() knows to release the lock and
|
||||
* flush the attention cache without scheduling another tick.
|
||||
*/
|
||||
class TMDO_Phase_Completed extends TMDO_Migration_Phase_Base {
|
||||
|
||||
/**
|
||||
* Returns the phase slug.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function name(): string {
|
||||
return 'completed';
|
||||
}
|
||||
|
||||
/**
|
||||
* Executes the phase.
|
||||
*
|
||||
* @param array $job Job array (by reference).
|
||||
* @return array{status: 'done'}
|
||||
*/
|
||||
public function execute( array &$job ): array {
|
||||
$job['state'] = 'completed';
|
||||
$job['completed_at'] = time();
|
||||
$job['overall_progress'] = 100;
|
||||
|
||||
$this->log(
|
||||
$job,
|
||||
sprintf(
|
||||
'✅ Migration complete — ratio %s → %s (-%.0f%%)',
|
||||
$job['metrics']['ratio_start'],
|
||||
$job['metrics']['ratio_now'],
|
||||
( $job['metrics']['ratio_start'] - $job['metrics']['ratio_now'] ) / max( $job['metrics']['ratio_start'], 0.01 ) * 100
|
||||
)
|
||||
);
|
||||
|
||||
return array( 'status' => 'done' );
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
<?php
|
||||
/**
|
||||
* Migration phase: demote entity mode from aeav_only back to dual_write.
|
||||
*
|
||||
* @package TMDO
|
||||
* @since 3.0.1
|
||||
*/
|
||||
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit;
|
||||
}
|
||||
|
||||
/**
|
||||
* Two-step mode demotion: aeav_only → shadow_read → dual_write.
|
||||
*/
|
||||
class TMDO_Phase_Demote extends TMDO_Migration_Phase_Base {
|
||||
|
||||
/**
|
||||
* Returns the phase slug.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function name(): string {
|
||||
return 'demote';
|
||||
}
|
||||
|
||||
/**
|
||||
* Executes the phase.
|
||||
*
|
||||
* @param array $job Job array (by reference).
|
||||
* @return array{status: string}
|
||||
* @throws \RuntimeException If mode transition fails.
|
||||
*/
|
||||
public function execute( array &$job ): array {
|
||||
$current = TMDO_Mode_Manager::get( $this->entity_type );
|
||||
|
||||
if ( TMDO_Mode_Manager::MODE_AEAV_ONLY !== $current ) {
|
||||
$this->log( $job, "↪ Demote skipped (mode is {$current}, not aeav_only)" );
|
||||
return array( 'status' => 'ok' );
|
||||
}
|
||||
|
||||
// Two-step demotion: aeav_only → shadow_read → dual_write.
|
||||
$r = TMDO_Mode_Manager::set( $this->entity_type, TMDO_Mode_Manager::MODE_SHADOW_READ );
|
||||
if ( is_wp_error( $r ) ) {
|
||||
throw new \RuntimeException( 'Demote step 1 failed: ' . $r->get_error_message() );
|
||||
}
|
||||
|
||||
$r = TMDO_Mode_Manager::set( $this->entity_type, TMDO_Mode_Manager::MODE_DUAL_WRITE );
|
||||
if ( is_wp_error( $r ) ) {
|
||||
throw new \RuntimeException( 'Demote step 2 failed: ' . $r->get_error_message() );
|
||||
}
|
||||
|
||||
$this->log( $job, 'Mode: aeav_only → dual_write (reads now go to EAV)' );
|
||||
return array( 'status' => 'ok' );
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
<?php
|
||||
/**
|
||||
* Migration phase: diagnose current entity state.
|
||||
*
|
||||
* @package TMDO
|
||||
* @since 3.0.1
|
||||
*/
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit;
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads preflight metrics and records them in the job array.
|
||||
*/
|
||||
class TMDO_Phase_Diagnose extends TMDO_Migration_Phase_Base {
|
||||
|
||||
/**
|
||||
* Returns the phase slug.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function name(): string {
|
||||
return 'diagnose';
|
||||
}
|
||||
|
||||
/**
|
||||
* Executes the phase.
|
||||
*
|
||||
* @param array $job Job array (by reference).
|
||||
* @return array{status: string, message?: string}
|
||||
*/
|
||||
public function execute( array &$job ): array {
|
||||
$preflight = TMDO_Migration_Orchestrator::preflight();
|
||||
$job['metrics']['eav_rows_now'] = $preflight['eav_rows'];
|
||||
$job['metrics']['ratio_now'] = $preflight['ratio'];
|
||||
|
||||
$this->log(
|
||||
$job,
|
||||
sprintf(
|
||||
'Diagnose: %d EAV residue rows, %d users, ratio %s, mode %s',
|
||||
$preflight['eav_rows'],
|
||||
$preflight['users'],
|
||||
(string) $preflight['ratio'],
|
||||
$preflight['mode']
|
||||
)
|
||||
);
|
||||
|
||||
return array(
|
||||
'status' => 'ok',
|
||||
'message' => 'Diagnose complete',
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
<?php
|
||||
/**
|
||||
* Migration phase: install flat schema tables for the entity type.
|
||||
*
|
||||
* @package TMDO
|
||||
* @since 3.0.1
|
||||
*/
|
||||
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit;
|
||||
}
|
||||
|
||||
/**
|
||||
* Fires wpdo_register_entity_fields, runs schema migrations, verifies all tables exist.
|
||||
*/
|
||||
class TMDO_Phase_Install_Schema extends TMDO_Migration_Phase_Base {
|
||||
|
||||
/**
|
||||
* Returns the phase slug.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function name(): string {
|
||||
return 'install_schema';
|
||||
}
|
||||
|
||||
/**
|
||||
* Executes the phase.
|
||||
*
|
||||
* @param array $job Job array (by reference).
|
||||
* @return array{status: string}
|
||||
* @throws \RuntimeException If any required tables are missing after migration.
|
||||
*/
|
||||
public function execute( array &$job ): array {
|
||||
do_action( 'wpdo_register_entity_fields', TMDO_Entity_Registry::class );
|
||||
TMDO_Schema_Manager::process_pending_migrations();
|
||||
|
||||
$missing = array();
|
||||
foreach ( TMDO_Entity_Registry::get_groups_for_type( $this->entity_type ) as $group ) {
|
||||
$table = TMDO_Schema_Manager::get_table_name( $this->entity_type, $group );
|
||||
if ( ! TMDO_Schema_Manager::table_exists( $table ) ) {
|
||||
$missing[] = $group;
|
||||
}
|
||||
}
|
||||
|
||||
if ( $missing ) {
|
||||
throw new \RuntimeException( 'Schema migration failed; missing tables: ' . implode( ',', $missing ) );
|
||||
}
|
||||
|
||||
$count = count( TMDO_Entity_Registry::get_groups_for_type( $this->entity_type ) );
|
||||
$this->log( $job, "Schema migration ok ({$count} flat tables verified)" );
|
||||
return array( 'status' => 'ok' );
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
<?php
|
||||
/**
|
||||
* Migration phase: promote entity mode to aeav_only (cutover complete).
|
||||
*
|
||||
* @package TMDO
|
||||
* @since 3.0.1
|
||||
*/
|
||||
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit;
|
||||
}
|
||||
|
||||
/**
|
||||
* Transitions mode from shadow_read → aeav_only.
|
||||
*/
|
||||
class TMDO_Phase_Promote_Aeav extends TMDO_Migration_Phase_Base {
|
||||
|
||||
/**
|
||||
* Returns the phase slug.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function name(): string {
|
||||
return 'promote_aeav';
|
||||
}
|
||||
|
||||
/**
|
||||
* Executes the phase.
|
||||
*
|
||||
* @param array $job Job array (by reference).
|
||||
* @return array{status: string}
|
||||
* @throws \RuntimeException If mode transition fails.
|
||||
*/
|
||||
public function execute( array &$job ): array {
|
||||
$current = TMDO_Mode_Manager::get( $this->entity_type );
|
||||
|
||||
if ( TMDO_Mode_Manager::MODE_AEAV_ONLY === $current ) {
|
||||
$this->log( $job, '↪ Already aeav_only' );
|
||||
return array( 'status' => 'ok' );
|
||||
}
|
||||
|
||||
$r = TMDO_Mode_Manager::set( $this->entity_type, TMDO_Mode_Manager::MODE_AEAV_ONLY );
|
||||
if ( is_wp_error( $r ) ) {
|
||||
throw new \RuntimeException( 'Promote to aeav_only failed: ' . $r->get_error_message() );
|
||||
}
|
||||
|
||||
$this->log( $job, 'Mode: shadow_read → aeav_only (cutover complete)' );
|
||||
return array( 'status' => 'ok' );
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
<?php
|
||||
/**
|
||||
* Migration phase: promote entity mode to shadow_read.
|
||||
*
|
||||
* @package TMDO
|
||||
* @since 3.0.1
|
||||
*/
|
||||
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit;
|
||||
}
|
||||
|
||||
/**
|
||||
* Transitions mode from dual_write → shadow_read (flat table serves reads).
|
||||
*/
|
||||
class TMDO_Phase_Promote_Shadow extends TMDO_Migration_Phase_Base {
|
||||
|
||||
/**
|
||||
* Returns the phase slug.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function name(): string {
|
||||
return 'promote_shadow';
|
||||
}
|
||||
|
||||
/**
|
||||
* Executes the phase.
|
||||
*
|
||||
* @param array $job Job array (by reference).
|
||||
* @return array{status: string}
|
||||
* @throws \RuntimeException If mode transition fails.
|
||||
*/
|
||||
public function execute( array &$job ): array {
|
||||
$current = TMDO_Mode_Manager::get( $this->entity_type );
|
||||
|
||||
if ( TMDO_Mode_Manager::MODE_DUAL_WRITE === $current ) {
|
||||
$r = TMDO_Mode_Manager::set( $this->entity_type, TMDO_Mode_Manager::MODE_SHADOW_READ );
|
||||
if ( is_wp_error( $r ) ) {
|
||||
throw new \RuntimeException( 'Promote to shadow_read failed: ' . $r->get_error_message() );
|
||||
}
|
||||
$this->log( $job, 'Mode: dual_write → shadow_read (verifying flat reads)' );
|
||||
} else {
|
||||
$this->log( $job, "↪ Already at {$current}; skip promote_shadow" );
|
||||
}
|
||||
|
||||
return array( 'status' => 'ok' );
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,140 @@
|
||||
<?php
|
||||
/**
|
||||
* Migration phase: sample-verify flat table vs EAV for data integrity.
|
||||
*
|
||||
* @package TMDO
|
||||
* @since 3.0.1
|
||||
*/
|
||||
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit;
|
||||
}
|
||||
|
||||
/**
|
||||
* Samples a subset of entities and compares flat vs EAV values.
|
||||
* Aborts with RuntimeException if any divergences are found.
|
||||
*/
|
||||
class TMDO_Phase_Verify_Sample extends TMDO_Migration_Phase_Base {
|
||||
|
||||
/**
|
||||
* Minimum sample size regardless of total entity count.
|
||||
*
|
||||
* @var int
|
||||
*/
|
||||
const VERIFY_SAMPLE_MIN = 500;
|
||||
|
||||
/**
|
||||
* Fraction of total entities to sample in strict mode.
|
||||
*
|
||||
* @var float
|
||||
*/
|
||||
const VERIFY_SAMPLE_RATIO = 0.10;
|
||||
|
||||
/**
|
||||
* Returns the phase slug.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function name(): string {
|
||||
return 'verify_sample';
|
||||
}
|
||||
|
||||
/**
|
||||
* Executes the phase.
|
||||
*
|
||||
* @param array $job Job array (by reference).
|
||||
* @return array{status: string}
|
||||
* @throws \RuntimeException If verification divergences are found.
|
||||
*/
|
||||
public function execute( array &$job ): array {
|
||||
global $wpdb;
|
||||
|
||||
if ( ! empty( $job['options']['verify_24h'] ) ) {
|
||||
$elapsed = time() - ( $job['phase_started_at'] ?? time() );
|
||||
if ( ! isset( $job['phase_started_at'] ) ) {
|
||||
$job['phase_started_at'] = time();
|
||||
$this->log( $job, '⏸ 24h shadow_read window started — wizard will resume after window elapses.' );
|
||||
return array( 'status' => 'in_progress' );
|
||||
}
|
||||
if ( $elapsed < DAY_IN_SECONDS ) {
|
||||
return array( 'status' => 'in_progress' );
|
||||
}
|
||||
$this->log( $job, '⏳ 24h shadow_read window complete; running sample compare' );
|
||||
}
|
||||
|
||||
$strict = ! empty( $job['options']['verify_strict'] );
|
||||
$users_total = (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->users}" );
|
||||
$sample_size = $strict
|
||||
? (int) max( self::VERIFY_SAMPLE_MIN, ceil( $users_total * self::VERIFY_SAMPLE_RATIO ) )
|
||||
: 100;
|
||||
$sample_size = min( $sample_size, $users_total );
|
||||
$sample_ids = $wpdb->get_col(
|
||||
$wpdb->prepare( "SELECT ID FROM {$wpdb->users} ORDER BY RAND() LIMIT %d", $sample_size )
|
||||
);
|
||||
|
||||
$diffs = 0;
|
||||
$compared = 0;
|
||||
$managed_keys = $this->get_managed_keys();
|
||||
|
||||
foreach ( $sample_ids as $uid ) {
|
||||
foreach ( $managed_keys as $key ) {
|
||||
$eav = $wpdb->get_var(
|
||||
$wpdb->prepare(
|
||||
"SELECT meta_value FROM {$wpdb->usermeta} WHERE user_id = %d AND meta_key = %s LIMIT 1", // phpcs:ignore WPDO.AntiEAV.no-direct-usermeta-select -- verify phase: must compare EAV source against flat table to confirm migration correctness
|
||||
$uid,
|
||||
$key
|
||||
)
|
||||
);
|
||||
|
||||
// Skip keys with no EAV source-of-truth — only flag when EAV has data
|
||||
// but flat doesn't match (real backfill error).
|
||||
if ( null === $eav || '' === $eav ) {
|
||||
continue;
|
||||
}
|
||||
|
||||
++$compared;
|
||||
$flat = TMDO_Hook_Bus::direct_read( $this->entity_type, (int) $uid, $key );
|
||||
|
||||
if ( ! $this->values_loose_equal( $flat, $eav ) ) {
|
||||
++$diffs;
|
||||
if ( $diffs <= 3 ) {
|
||||
$this->log(
|
||||
$job,
|
||||
sprintf(
|
||||
' ! diff uid=%d key=%s flat=%s eav=%s',
|
||||
$uid,
|
||||
$key,
|
||||
is_scalar( $flat ) ? (string) $flat : gettype( $flat ),
|
||||
is_scalar( $eav ) ? (string) $eav : gettype( $eav )
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
$this->log(
|
||||
$job,
|
||||
sprintf(
|
||||
'Verify: sampled %d users × %d keys = %d compares, %d diff(s)',
|
||||
count( $sample_ids ),
|
||||
count( $managed_keys ),
|
||||
$compared,
|
||||
$diffs
|
||||
)
|
||||
);
|
||||
|
||||
if ( $diffs > 0 ) {
|
||||
throw new \RuntimeException(
|
||||
sprintf(
|
||||
'Verification found %d divergence(s) across %d compares — aborting before destructive cleanup.',
|
||||
$diffs,
|
||||
$compared
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
return array( 'status' => 'ok' );
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user