Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?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' );
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement