Wp-cli's wp db query fails to connect when executing SQL on the command line

Bug Summary

When trying to run a shell script that queries the database via WP-CLI’s wp db query comamnd, theconnection fails. Error: Failed to get current SQL modes. Reason: ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2)

This is due to the way that wp-cli connects to MySQL via the settings in the wp-config.php file.

I resolved this by setting the wp-config.php database hostname to localhost:/THEPATH/TO/PROJECTS/Local/run/cRMxNZCsF/mysql/mysqld.sock

Steps to reproduce

Create a new site.
Open the Site Shell.
Execute a SQL command such as wp db query "SELECT * from wp_options"
You should see the connection error.

Change the hostname to localhost:Path/tothe/socket that is listed on the Database tab in Local, and rerun the command and you should get back the contents of the options table.

Environment Info

Describe your environment.

  • What Operating System are you using? MacOS 13.7.4 (22H420)
  • What versions of site software (Nginx, Apache, PHP, MySQL) is used? 8.0 for PHP and 8.0.16 for MySQL
  • What version of Local is installed? Version 9.0.5+6706

Supporting info

My suggestion to resolve this would be for Local to automatically use the full socket path in the wp-config.php file rather than just “localhost”