Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Custom DB CLI command to query a database that you can customize to set the default connection info or pass additional associative arguments to override Host, Database, User, Password, and/or Charset used.
<?php
/**
* Custom DB CLI command
*/
class My_DB_CLI extends \WP_CLI_Command {
/**
* Execute a MySQL query against a custom database.
*
* Executes an arbitrary MySQL query using `DB_HOST`, `DB_NAME`, `DB_USER`
* and `DB_PASSWORD` database credentials specified in wp-config.php.
*
* ## OPTIONS
*
* [<sql>]
* : A SQL query. If not passed, will try to read from STDIN.
*
* [--host=<host>]
* : DB Host to use
*
* [--database=<database>]
* : DB to use
*
* [--user=<user>]
* : DB User to use
*
* [--pass=<pass>]
* : DB Password to use
*
* [--charset=<charset>]
* : DB Charset to use
*
* ## EXAMPLES
*
* # execute a query stored in a file
* wp my-db query < debug.sql
*
* # check all tables in the database
* wp my-db query "CHECK TABLE $(wp db tables | paste -s -d',');"
*/
public function query( $args, $assoc_args ) {
$cmd = 'mysql --no-defaults --no-auto-rehash';
$final_args = array(
'host' => DB_HOST,
'database' => DB_NAME,
'user' => DB_USER,
'pass' => DB_PASSWORD,
);
if ( ! empty( $assoc_args['host'] ) ) {
$final_args['host'] = $assoc_args['host'];
}
if ( ! empty( $assoc_args['database'] ) ) {
$final_args['database'] = $assoc_args['database'];
}
if ( ! empty( $assoc_args['user'] ) ) {
$final_args['user'] = $assoc_args['user'];
}
if ( ! empty( $assoc_args['pass'] ) ) {
$final_args['pass'] = $assoc_args['pass'];
}
if ( defined( 'DB_CHARSET' ) && constant( 'DB_CHARSET' ) ) {
$final_args['default-character-set'] = constant( 'DB_CHARSET' );
}
if ( ! empty( $assoc_args['charset'] ) ) {
$final_args['default-character-set'] = $assoc_args['charset'];
}
if ( ! empty( $args ) ) {
$final_args['execute'] = $args[0];
}
\WP_CLI\Utils\run_mysql_command( $cmd, $final_args );
}
}
\WP_CLI::add_command( 'my-db', 'My_DB_CLI' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.