WP_CLI\Utils
run_mysql_command()
Run a MySQL command and optionally return the output.
No Hooks.
Returns
Array. Associative array containing STDOUT and STDERR output.
Usage
run_mysql_command( $cmd, $assoc_args, $_, $send_to_shell, $interactive );
- $cmd(string) (required)
- Command to run.
- $assoc_args(required)
- .
- $_(mixed)
- Deprecated. Former $descriptors argument.
Default: null - $send_to_shell(true|false)
- Whether to send STDOUT and STDERR immediately to the shell.
Default: true - $interactive(true|false)
- Whether MySQL is meant to be executed as an interactive process.
Default: false
Changelog
| Since 2.5.0 | Introduced. |
run_mysql_command() run mysql command code WP-CLI 2.13.0-alpha
function run_mysql_command( $cmd, $assoc_args, $_ = null, $send_to_shell = true, $interactive = false ) {
check_proc_available( 'run_mysql_command' );
$descriptors = ( $interactive || $send_to_shell ) ?
[
0 => STDIN,
1 => STDOUT,
2 => STDERR,
] :
[
0 => STDIN,
1 => [ 'pipe', 'w' ],
2 => [ 'pipe', 'w' ],
];
$stdout = '';
$stderr = '';
$pipes = [];
if ( isset( $assoc_args['host'] ) ) {
// phpcs:ignore WordPress.DB.RestrictedFunctions.mysql_mysql_host_to_cli_args -- Misidentified as PHP native MySQL function.
$assoc_args = array_merge( $assoc_args, mysql_host_to_cli_args( $assoc_args['host'] ) );
}
if ( isset( $assoc_args['pass'] ) ) {
$old_password = getenv( 'MYSQL_PWD' );
putenv( 'MYSQL_PWD=' . $assoc_args['pass'] );
unset( $assoc_args['pass'] );
}
$final_cmd = force_env_on_nix_systems( $cmd ) . assoc_args_to_str( $assoc_args );
WP_CLI::debug( 'Final MySQL command: ' . $final_cmd, 'db' );
$process = proc_open_compat( $final_cmd, $descriptors, $pipes );
if ( isset( $old_password ) ) {
putenv( 'MYSQL_PWD=' . $old_password );
}
if ( ! $process ) {
WP_CLI::debug( 'Failed to create a valid process using proc_open_compat()', 'db' );
exit( 1 );
}
if ( is_resource( $process ) && ! $send_to_shell && ! $interactive ) {
$stdout = stream_get_contents( $pipes[1] );
$stderr = stream_get_contents( $pipes[2] );
fclose( $pipes[1] );
fclose( $pipes[2] );
}
$exit_code = proc_close( $process );
if ( $exit_code && ( $send_to_shell || $interactive ) ) {
exit( $exit_code );
}
return [
$stdout,
$stderr,
$exit_code,
];
}