Project

General

Profile

Feature #10684 » convert-tables.php

Boone Gorges, 2018-11-09 12:32 PM

 
1
<?php
2

    
3
if ( empty( $args[0] ) || empty( $args[1] ) ) {
4
	WP_CLI::error( 'Usage: wp eval-file convert-tables.php options /path/to/backups 100 0, where 100 is the batch count and 0 is the min blog ID' );
5
	die;
6
}
7

    
8
$table_short_name = $args[0];
9
$backup_dir = $args[1];
10

    
11
$batch_size = isset( $args[2] ) ? (int) $args[2] : 5;
12
$min_blog_id = isset( $args[3] ) ? (int) $args[3] : 1;
13
//var_dump( $table_short_name, $backup_dir, $batch_size, $min_blog_id );
14

    
15
global $wpdb;
16

    
17
if ( ! file_exists( $backup_dir ) ) {
18
	mkdir( $backup_dir );
19
}
20

    
21
$log_file = $backup_dir . '/convert.log';
22

    
23
$date = date( 'Y-m-d H:i:s' );
24
file_put_contents( $log_file, "Beginning conversion process at $date\n", FILE_APPEND );
25

    
26
$blog_id = $min_blog_id;
27
$max_blog_id = $blog_id + $batch_size;
28
while ( $blog_id < $max_blog_id ) {
29
	$prefix = $wpdb->get_blog_prefix( $blog_id );
30
	$table_name = $prefix . $table_short_name;
31
	$table_exists = $wpdb->get_var( "SHOW TABLES LIKE '$table_name'" );
32

    
33
	$blog_id++;
34

    
35
	if ( ! $table_exists ) {
36
		file_put_contents( $log_file, "$table_name: Does not exist\n", FILE_APPEND );
37
		continue;
38
	}
39

    
40
	// Create backup.
41
	$backup_file = $backup_dir . '/' . $table_name . '.sql';
42
	$command = "db export --tables=$table_name $backup_file";
43

    
44
	$backed_up = WP_CLI::runcommand( $command, [
45
		'return' => 'all',
46
		'launch' => true,
47
		'exit_error' => false,
48
	] );
49
	if ( 0 !== $backed_up->return_code ) {
50
		file_put_contents( $log_file, "$table_name: Could not create export\n", FILE_APPEND );
51
		continue;
52
	}
53

    
54
	$converted = maybe_convert_table_to_utf8mb4( $table_name );
55

    
56
	if ( $converted ) {
57
		file_put_contents( $log_file, "$table_name: Converted!\n", FILE_APPEND );
58
	} else {
59
		file_put_contents( $log_file, "$table_name: Could not convert.\n", FILE_APPEND );
60
	}
61
}
    (1-1/1)