Advertisement
Guest User

Untitled

a guest
May 18th, 2016
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.86 KB | None | 0 0
  1. <?php
  2. /**
  3. * Custom DB CLI command
  4. */
  5. class My_DB_CLI extends \WP_CLI_Command {
  6.  
  7. /**
  8. * Execute a MySQL query against a custom database.
  9. *
  10. * Executes an arbitrary MySQL query using `DB_HOST`, `DB_NAME`, `DB_USER`
  11. * and `DB_PASSWORD` database credentials specified in wp-config.php.
  12. *
  13. * ## OPTIONS
  14. *
  15. * [<sql>]
  16. * : A SQL query. If not passed, will try to read from STDIN.
  17. *
  18. * [--host=<host>]
  19. * : DB Host to use
  20. *
  21. * [--database=<database>]
  22. * : DB to use
  23. *
  24. * [--user=<user>]
  25. * : DB User to use
  26. *
  27. * [--pass=<pass>]
  28. * : DB Password to use
  29. *
  30. * [--charset=<charset>]
  31. * : DB Charset to use
  32. *
  33. * ## EXAMPLES
  34. *
  35. * # execute a query stored in a file
  36. * wp my-db query < debug.sql
  37. *
  38. * # check all tables in the database
  39. * wp my-db query "CHECK TABLE $(wp db tables | paste -s -d',');"
  40. */
  41. public function query( $args, $assoc_args ) {
  42.  
  43. $cmd = 'mysql --no-defaults --no-auto-rehash';
  44.  
  45. $final_args = array(
  46. 'host' => DB_HOST,
  47. 'database' => DB_NAME,
  48. 'user' => DB_USER,
  49. 'pass' => DB_PASSWORD,
  50. );
  51.  
  52. if ( ! empty( $assoc_args['host'] ) ) {
  53. $final_args['host'] = $assoc_args['host'];
  54. }
  55.  
  56. if ( ! empty( $assoc_args['database'] ) ) {
  57. $final_args['database'] = $assoc_args['database'];
  58. }
  59.  
  60. if ( ! empty( $assoc_args['user'] ) ) {
  61. $final_args['user'] = $assoc_args['user'];
  62. }
  63.  
  64. if ( ! empty( $assoc_args['pass'] ) ) {
  65. $final_args['pass'] = $assoc_args['pass'];
  66. }
  67.  
  68. if ( defined( 'DB_CHARSET' ) && constant( 'DB_CHARSET' ) ) {
  69. $final_args['default-character-set'] = constant( 'DB_CHARSET' );
  70. }
  71.  
  72. if ( ! empty( $assoc_args['charset'] ) ) {
  73. $final_args['default-character-set'] = $assoc_args['charset'];
  74. }
  75.  
  76. if ( ! empty( $args ) ) {
  77. $final_args['execute'] = $args[0];
  78. }
  79.  
  80. \WP_CLI\Utils\run_mysql_command( $cmd, $final_args );
  81.  
  82. }
  83.  
  84. }
  85.  
  86. \WP_CLI::add_command( 'my-db', 'My_DB_CLI' );
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement