Giter Site home page Giter Site logo

wp-cli / db-command Goto Github PK

View Code? Open in Web Editor NEW
71.0 11.0 58.0 8.98 MB

Performs basic database operations using credentials stored in wp-config.php.

License: MIT License

PHP 50.66% Gherkin 49.34%
wp-cli wp-cli-package wordpress cli db mysql mariadb hacktoberfest

db-command's Introduction

wp-cli/db-command

Performs basic database operations using credentials stored in wp-config.php.

Testing

Quick links: Using | Installing | Contributing | Support

Using

This package implements the following commands:

wp db

Performs basic database operations using credentials stored in wp-config.php.

wp db

EXAMPLES

# Create a new database.
$ wp db create
Success: Database created.

# Drop an existing database.
$ wp db drop --yes
Success: Database dropped.

# Reset the current database.
$ wp db reset --yes
Success: Database reset.

# Execute a SQL query stored in a file.
$ wp db query < debug.sql

wp db clean

Removes all tables with $table_prefix from the database.

wp db clean [--dbuser=<value>] [--dbpass=<value>] [--yes] [--defaults]

Runs DROP_TABLE for each table that has a $table_prefix as specified in wp-config.php.

OPTIONS

[--dbuser=<value>]
	Username to pass to mysql. Defaults to DB_USER.

[--dbpass=<value>]
	Password to pass to mysql. Defaults to DB_PASSWORD.

[--yes]
	Answer yes to the confirmation message.

[--defaults]
	Loads the environment's MySQL option files. Default behavior is to skip loading them to avoid failures due to misconfiguration.

EXAMPLES

# Delete all tables that match the current site prefix.
$ wp db clean --yes
Success: Tables dropped.

wp db create

Creates a new database.

wp db create [--dbuser=<value>] [--dbpass=<value>] [--defaults]

Runs CREATE_DATABASE SQL statement using DB_HOST, DB_NAME, DB_USER and DB_PASSWORD database credentials specified in wp-config.php.

OPTIONS

[--dbuser=<value>]
	Username to pass to mysql. Defaults to DB_USER.

[--dbpass=<value>]
	Password to pass to mysql. Defaults to DB_PASSWORD.

[--defaults]
	Loads the environment's MySQL option files. Default behavior is to skip loading them to avoid failures due to misconfiguration.

EXAMPLES

$ wp db create
Success: Database created.

wp db drop

Deletes the existing database.

wp db drop [--dbuser=<value>] [--dbpass=<value>] [--yes] [--defaults]

Runs DROP_DATABASE SQL statement using DB_HOST, DB_NAME, DB_USER and DB_PASSWORD database credentials specified in wp-config.php.

OPTIONS

[--dbuser=<value>]
	Username to pass to mysql. Defaults to DB_USER.

[--dbpass=<value>]
	Password to pass to mysql. Defaults to DB_PASSWORD.

[--yes]
	Answer yes to the confirmation message.

[--defaults]
	Loads the environment's MySQL option files. Default behavior is to skip loading them to avoid failures due to misconfiguration.

EXAMPLES

$ wp db drop --yes
Success: Database dropped.

wp db reset

Removes all tables from the database.

wp db reset [--dbuser=<value>] [--dbpass=<value>] [--yes] [--defaults]

Runs DROP_DATABASE and CREATE_DATABASE SQL statements using DB_HOST, DB_NAME, DB_USER and DB_PASSWORD database credentials specified in wp-config.php.

OPTIONS

[--dbuser=<value>]
	Username to pass to mysql. Defaults to DB_USER.

[--dbpass=<value>]
	Password to pass to mysql. Defaults to DB_PASSWORD.

[--yes]
	Answer yes to the confirmation message.

[--defaults]
	Loads the environment's MySQL option files. Default behavior is to skip loading them to avoid failures due to misconfiguration.

EXAMPLES

$ wp db reset --yes
Success: Database reset.

wp db check

Checks the current status of the database.

wp db check [--dbuser=<value>] [--dbpass=<value>] [--<field>=<value>] [--defaults]

Runs mysqlcheck utility with --check using DB_HOST, DB_NAME, DB_USER and DB_PASSWORD database credentials specified in wp-config.php.

See docs for more details on the CHECK TABLE statement.

This command does not check whether WordPress is installed; to do that run wp core is-installed.

OPTIONS

[--dbuser=<value>]
	Username to pass to mysqlcheck. Defaults to DB_USER.

[--dbpass=<value>]
	Password to pass to mysqlcheck. Defaults to DB_PASSWORD.

[--<field>=<value>]
	Extra arguments to pass to mysqlcheck. [Refer to mysqlcheck docs](https://dev.mysql.com/doc/en/mysqlcheck.html).

[--defaults]
	Loads the environment's MySQL option files. Default behavior is to skip loading them to avoid failures due to misconfiguration.

EXAMPLES

$ wp db check
Success: Database checked.

wp db optimize

Optimizes the database.

wp db optimize [--dbuser=<value>] [--dbpass=<value>] [--<field>=<value>] [--defaults]

Runs mysqlcheck utility with --optimize=true using DB_HOST, DB_NAME, DB_USER and DB_PASSWORD database credentials specified in wp-config.php.

See docs for more details on the OPTIMIZE TABLE statement.

OPTIONS

[--dbuser=<value>]
	Username to pass to mysqlcheck. Defaults to DB_USER.

[--dbpass=<value>]
	Password to pass to mysqlcheck. Defaults to DB_PASSWORD.

[--<field>=<value>]
	Extra arguments to pass to mysqlcheck. [Refer to mysqlcheck docs](https://dev.mysql.com/doc/en/mysqlcheck.html).

[--defaults]
	Loads the environment's MySQL option files. Default behavior is to skip loading them to avoid failures due to misconfiguration.

EXAMPLES

$ wp db optimize
Success: Database optimized.

wp db prefix

Displays the database table prefix.

wp db prefix 

Display the database table prefix, as defined by the database handler's interpretation of the current site.

EXAMPLES

$ wp db prefix
wp_

wp db repair

Repairs the database.

wp db repair [--dbuser=<value>] [--dbpass=<value>] [--<field>=<value>] [--defaults]

Runs mysqlcheck utility with --repair=true using DB_HOST, DB_NAME, DB_USER and DB_PASSWORD database credentials specified in wp-config.php.

See docs for more details on the REPAIR TABLE statement.

OPTIONS

[--dbuser=<value>]
	Username to pass to mysqlcheck. Defaults to DB_USER.

[--dbpass=<value>]
	Password to pass to mysqlcheck. Defaults to DB_PASSWORD.

[--<field>=<value>]
	Extra arguments to pass to mysqlcheck. [Refer to mysqlcheck docs](https://dev.mysql.com/doc/en/mysqlcheck.html).

[--defaults]
	Loads the environment's MySQL option files. Default behavior is to skip loading them to avoid failures due to misconfiguration.

EXAMPLES

$ wp db repair
Success: Database repaired.

wp db cli

Opens a MySQL console using credentials from wp-config.php

wp db cli [--database=<database>] [--default-character-set=<character-set>] [--dbuser=<value>] [--dbpass=<value>] [--<field>=<value>] [--defaults]

OPTIONS

[--database=<database>]
	Use a specific database. Defaults to DB_NAME.

[--default-character-set=<character-set>]
	Use a specific character set. Defaults to DB_CHARSET when defined.

[--dbuser=<value>]
	Username to pass to mysql. Defaults to DB_USER.

[--dbpass=<value>]
	Password to pass to mysql. Defaults to DB_PASSWORD.

[--<field>=<value>]
	Extra arguments to pass to mysql. [Refer to mysql docs](https://dev.mysql.com/doc/en/mysql-command-options.html).

[--defaults]
	Loads the environment's MySQL option files. Default behavior is to skip loading them to avoid failures due to misconfiguration.

EXAMPLES

# Open MySQL console
$ wp db cli
mysql>

wp db query

Executes a SQL query against the database.

wp db query [<sql>] [--dbuser=<value>] [--dbpass=<value>] [--<field>=<value>] [--defaults]

Executes an arbitrary SQL query using DB_HOST, DB_NAME, DB_USER and DB_PASSWORD database credentials specified in wp-config.php.

Use the --skip-column-names MySQL argument to exclude the headers from a SELECT query. Pipe the output to remove the ASCII table entirely.

OPTIONS

[<sql>]
	A SQL query. If not passed, will try to read from STDIN.

[--dbuser=<value>]
	Username to pass to mysql. Defaults to DB_USER.

[--dbpass=<value>]
	Password to pass to mysql. Defaults to DB_PASSWORD.

[--<field>=<value>]
	Extra arguments to pass to mysql. [Refer to mysql docs](https://dev.mysql.com/doc/en/mysql-command-options.html).

[--defaults]
	Loads the environment's MySQL option files. Default behavior is to skip loading them to avoid failures due to misconfiguration.

EXAMPLES

# Execute a query stored in a file
$ wp db query < debug.sql

# Query for a specific value in the database (pipe the result to remove the ASCII table borders)
$ wp db query 'SELECT option_value FROM wp_options WHERE option_name="home"' --skip-column-names
+---------------------+
| https://example.com |
+---------------------+

# Check all tables in the database
$ wp db query "CHECK TABLE $(wp db tables | paste -s -d, -);"
+---------------------------------------+-------+----------+----------+
| Table                                 | Op    | Msg_type | Msg_text |
+---------------------------------------+-------+----------+----------+
| wordpress_dbase.wp_users              | check | status   | OK       |
| wordpress_dbase.wp_usermeta           | check | status   | OK       |
| wordpress_dbase.wp_posts              | check | status   | OK       |
| wordpress_dbase.wp_comments           | check | status   | OK       |
| wordpress_dbase.wp_links              | check | status   | OK       |
| wordpress_dbase.wp_options            | check | status   | OK       |
| wordpress_dbase.wp_postmeta           | check | status   | OK       |
| wordpress_dbase.wp_terms              | check | status   | OK       |
| wordpress_dbase.wp_term_taxonomy      | check | status   | OK       |
| wordpress_dbase.wp_term_relationships | check | status   | OK       |
| wordpress_dbase.wp_termmeta           | check | status   | OK       |
| wordpress_dbase.wp_commentmeta        | check | status   | OK       |
+---------------------------------------+-------+----------+----------+

# Pass extra arguments through to MySQL
$ wp db query 'SELECT * FROM wp_options WHERE option_name="home"' --skip-column-names
+---+------+------------------------------+-----+
| 2 | home | http://wordpress-develop.dev | yes |
+---+------+------------------------------+-----+

MULTISITE USAGE

Please note that the global --url parameter will have no effect on this command. In order to query for data in a site other than your primary site, you will need to manually modify the table names to use the prefix that includes the site's ID.

For example, to get the home option for your second site, modify the example above like so:

$ wp db query 'SELECT option_value FROM wp_2_options WHERE option_name="home"' --skip-column-names
+----------------------+
| https://example2.com |
+----------------------+

To confirm the ID for the site you want to query, you can use the wp site list command:

# wp site list --fields=blog_id,url
+---------+-----------------------+
| blog_id | url                   |
+---------+-----------------------+
| 1       | https://example1.com/ |
| 2       | https://example2.com/ |
+---------+-----------------------+

wp db export

Exports the database to a file or to STDOUT.

wp db export [<file>] [--dbuser=<value>] [--dbpass=<value>] [--<field>=<value>] [--tables=<tables>] [--exclude_tables=<tables>] [--include-tablespaces] [--porcelain] [--add-drop-table] [--defaults]

Runs mysqldump utility using DB_HOST, DB_NAME, DB_USER and DB_PASSWORD database credentials specified in wp-config.php. Accepts any valid mysqldump flags.

OPTIONS

[<file>]
	The name of the SQL file to export. If '-', then outputs to STDOUT. If
	omitted, it will be '{dbname}-{Y-m-d}-{random-hash}.sql'.

[--dbuser=<value>]
	Username to pass to mysqldump. Defaults to DB_USER.

[--dbpass=<value>]
	Password to pass to mysqldump. Defaults to DB_PASSWORD.

[--<field>=<value>]
	Extra arguments to pass to mysqldump. [Refer to mysqldump docs](https://dev.mysql.com/doc/en/mysqldump.html#mysqldump-option-summary).

[--tables=<tables>]
	The comma separated list of specific tables to export. Excluding this parameter will export all tables in the database.

[--exclude_tables=<tables>]
	The comma separated list of specific tables that should be skipped from exporting. Excluding this parameter will export all tables in the database.

[--include-tablespaces]
	Skips adding the default --no-tablespaces option to mysqldump.

[--porcelain]
	Output filename for the exported database.

[--add-drop-table]
	Include a `DROP TABLE IF EXISTS` statement before each `CREATE TABLE` statement.

[--defaults]
	Loads the environment's MySQL option files. Default behavior is to skip loading them to avoid failures due to misconfiguration.

EXAMPLES

# Export database with drop query included
$ wp db export --add-drop-table
Success: Exported to 'wordpress_dbase-db72bb5.sql'.

# Export certain tables
$ wp db export --tables=wp_options,wp_users
Success: Exported to 'wordpress_dbase-db72bb5.sql'.

# Export all tables matching a wildcard
$ wp db export --tables=$(wp db tables 'wp_user*' --format=csv)
Success: Exported to 'wordpress_dbase-db72bb5.sql'.

# Export all tables matching prefix
$ wp db export --tables=$(wp db tables --all-tables-with-prefix --format=csv)
Success: Exported to 'wordpress_dbase-db72bb5.sql'.

# Export certain posts without create table statements
$ wp db export --no-create-info=true --tables=wp_posts --where="ID in (100,101,102)"
Success: Exported to 'wordpress_dbase-db72bb5.sql'.

# Export relating meta for certain posts without create table statements
$ wp db export --no-create-info=true --tables=wp_postmeta --where="post_id in (100,101,102)"
Success: Exported to 'wordpress_dbase-db72bb5.sql'.

# Skip certain tables from the exported database
$ wp db export --exclude_tables=wp_options,wp_users
Success: Exported to 'wordpress_dbase-db72bb5.sql'.

# Skip all tables matching a wildcard from the exported database
$ wp db export --exclude_tables=$(wp db tables 'wp_user*' --format=csv)
Success: Exported to 'wordpress_dbase-db72bb5.sql'.

# Skip all tables matching prefix from the exported database
$ wp db export --exclude_tables=$(wp db tables --all-tables-with-prefix --format=csv)
Success: Exported to 'wordpress_dbase-db72bb5.sql'.

# Export database to STDOUT.
$ wp db export -
-- MySQL dump 10.13  Distrib 5.7.19, for osx10.12 (x86_64)
--
-- Host: localhost    Database: wpdev
-- ------------------------------------------------------
-- Server version    5.7.19
...

wp db import

Imports a database from a file or from STDIN.

wp db import [<file>] [--dbuser=<value>] [--dbpass=<value>] [--<field>=<value>] [--skip-optimization] [--defaults]

Runs SQL queries using DB_HOST, DB_NAME, DB_USER and DB_PASSWORD database credentials specified in wp-config.php. This does not create database by itself and only performs whatever tasks are defined in the SQL.

OPTIONS

[<file>]
	The name of the SQL file to import. If '-', then reads from STDIN. If omitted, it will look for '{dbname}.sql'.

[--dbuser=<value>]
	Username to pass to mysql. Defaults to DB_USER.

[--dbpass=<value>]
	Password to pass to mysql. Defaults to DB_PASSWORD.

[--<field>=<value>]
	Extra arguments to pass to mysql. [Refer to mysql binary docs](https://dev.mysql.com/doc/refman/8.0/en/mysql-command-options.html).

[--skip-optimization]
	When using an SQL file, do not include speed optimization such as disabling auto-commit and key checks.

[--defaults]
	Loads the environment's MySQL option files. Default behavior is to skip loading them to avoid failures due to misconfiguration.

EXAMPLES

# Import MySQL from a file.
$ wp db import wordpress_dbase.sql
Success: Imported from 'wordpress_dbase.sql'.

wp db search

Finds a string in the database.

wp db search <search> [<tables>...] [--network] [--all-tables-with-prefix] [--all-tables] [--before_context=<num>] [--after_context=<num>] [--regex] [--regex-flags=<regex-flags>] [--regex-delimiter=<regex-delimiter>] [--table_column_once] [--one_line] [--matches_only] [--stats] [--table_column_color=<color_code>] [--id_color=<color_code>] [--match_color=<color_code>] [--fields=<fields>] [--format=<format>]

Searches through all of the text columns in a selection of database tables for a given string, Outputs colorized references to the string.

Defaults to searching through all tables registered to $wpdb. On multisite, this default is limited to the tables for the current site.

OPTIONS

<search>
	String to search for. The search is case-insensitive by default.

[<tables>...]
	One or more tables to search through for the string.

[--network]
	Search through all the tables registered to $wpdb in a multisite install.

[--all-tables-with-prefix]
	Search through all tables that match the registered table prefix, even if not registered on $wpdb. On one hand, sometimes plugins use tables without registering them to $wpdb. On another hand, this could return tables you don't expect. Overrides --network.

[--all-tables]
	Search through ALL tables in the database, regardless of the prefix, and even if not registered on $wpdb. Overrides --network and --all-tables-with-prefix.

[--before_context=<num>]
	Number of characters to display before the match.
	---
	default: 40
	---

[--after_context=<num>]
	Number of characters to display after the match.
	---
	default: 40
	---

[--regex]
	Runs the search as a regular expression (without delimiters). The search becomes case-sensitive (i.e. no PCRE flags are added). Delimiters must be escaped if they occur in the expression. Because the search is run on individual columns, you can use the `^` and `$` tokens to mark the start and end of a match, respectively.

[--regex-flags=<regex-flags>]
	Pass PCRE modifiers to the regex search (e.g. 'i' for case-insensitivity).

[--regex-delimiter=<regex-delimiter>]
	The delimiter to use for the regex. It must be escaped if it appears in the search string. The default value is the result of `chr(1)`.

[--table_column_once]
	Output the 'table:column' line once before all matching row lines in the table column rather than before each matching row.

[--one_line]
	Place the 'table:column' output on the same line as the row id and match ('table:column:id:match'). Overrides --table_column_once.

[--matches_only]
	Only output the string matches (including context). No 'table:column's or row ids are outputted.

[--stats]
	Output stats on the number of matches found, time taken, tables/columns/rows searched, tables skipped.

[--table_column_color=<color_code>]
	Percent color code to use for the 'table:column' output. For a list of available percent color codes, see below. Default '%G' (bright green).

[--id_color=<color_code>]
	Percent color code to use for the row id output. For a list of available percent color codes, see below. Default '%Y' (bright yellow).

[--match_color=<color_code>]
	Percent color code to use for the match (unless both before and after context are 0, when no color code is used). For a list of available percent color codes, see below. Default '%3%k' (black on a mustard background).

[--fields=<fields>]
	Get a specific subset of the fields.

[--format=<format>]
	Render output in a particular format.
	---
	options:
	  - table
	  - csv
	  - json
	  - yaml
	  - ids
	  - count
	---

The percent color codes available are:

Code Color
%y Yellow (dark) (mustard)
%g Green (dark)
%b Blue (dark)
%r Red (dark)
%m Magenta (dark)
%c Cyan (dark)
%w White (dark) (light gray)
%k Black
%Y Yellow (bright)
%G Green (bright)
%B Blue (bright)
%R Red (bright)
%M Magenta (bright)
%C Cyan (bright)
%W White
%K Black (bright) (dark gray)
%3 Yellow background (dark) (mustard)
%2 Green background (dark)
%4 Blue background (dark)
%1 Red background (dark)
%5 Magenta background (dark)
%6 Cyan background (dark)
%7 White background (dark) (light gray)
%0 Black background
%8 Reverse
%U Underline
%F Blink (unlikely to work)

They can be concatenated. For instance, the default match color of black on a mustard (dark yellow) background %3%k can be made black on a bright yellow background with %Y%0%8.

AVAILABLE FIELDS

These fields will be displayed by default for each result:

  • table
  • column
  • match
  • primary_key_name
  • primary_key_value

EXAMPLES

# Search through the database for the 'wordpress-develop' string
$ wp db search wordpress-develop
wp_options:option_value
1:http://wordpress-develop.dev
wp_options:option_value
1:https://example.com/foo
    ...

# Search through a multisite database on the subsite 'foo' for the 'example.com' string
$ wp db search example.com --url=example.com/foo
wp_2_comments:comment_author_url
1:https://example.com/
wp_2_options:option_value
    ...

# Search through the database for the 'https?://' regular expression, printing stats.
$ wp db search 'https?://' --regex --stats
wp_comments:comment_author_url
1:https://wordpress.org/
    ...
Success: Found 99146 matches in 10.752s (10.559s searching). Searched 12 tables, 53 columns, 1358907 rows. 1 table skipped: wp_term_relationships.

# SQL search database table 'wp_options' where 'option_name' match 'foo'
wp db query 'SELECT * FROM wp_options WHERE option_name like "%foo%"' --skip-column-names
+----+--------------+--------------------------------+-----+
| 98 | foo_options  | a:1:{s:12:"_multiwidget";i:1;} | yes |
| 99 | foo_settings | a:0:{}                         | yes |
+----+--------------+--------------------------------+-----+

# SQL search and delete records from database table 'wp_options' where 'option_name' match 'foo'
wp db query "DELETE from wp_options where option_id in ($(wp db query "SELECT GROUP_CONCAT(option_id SEPARATOR ',') from wp_options where option_name like '%foo%';" --silent --skip-column-names))"

# Search for a string and print the result as a table
$ wp db search https://localhost:8889 --format=table --fields=table,column,match
+------------+--------------+-----------------------------+
| table      | column       | match                       |
+------------+--------------+-----------------------------+
| wp_options | option_value | https://localhost:8889      |
| wp_options | option_value | https://localhost:8889      |
| wp_posts   | guid         | https://localhost:8889/?p=1 |
| wp_users   | user_url     | https://localhost:8889      |
+------------+--------------+-----------------------------+

# Search for a string and get only the IDs (only works for a single table)
$ wp db search https://localhost:8889 wp_options --format=ids
1 2

wp db tables

Lists the database tables.

wp db tables [<table>...] [--scope=<scope>] [--network] [--all-tables-with-prefix] [--all-tables] [--format=<format>]

Defaults to all tables registered to the $wpdb database handler.

OPTIONS

[<table>...]
	List tables based on wildcard search, e.g. 'wp_*_options' or 'wp_post?'.

[--scope=<scope>]
	Can be all, global, ms_global, blog, or old tables. Defaults to all.

[--network]
	List all the tables in a multisite install.

[--all-tables-with-prefix]
	List all tables that match the table prefix even if not registered on $wpdb. Overrides --network.

[--all-tables]
	List all tables in the database, regardless of the prefix, and even if not registered on $wpdb. Overrides --all-tables-with-prefix.

[--format=<format>]
	Render output in a particular format.
	---
	default: list
	options:
	  - list
	  - csv
	---

EXAMPLES

# List tables for a single site, without shared tables like 'wp_users'
$ wp db tables --scope=blog --url=sub.example.com
wp_3_posts
wp_3_comments
wp_3_options
wp_3_postmeta
wp_3_terms
wp_3_term_taxonomy
wp_3_term_relationships
wp_3_termmeta
wp_3_commentmeta

# Export only tables for a single site
$ wp db export --tables=$(wp db tables --url=sub.example.com --format=csv)
Success: Exported to wordpress_dbase.sql

wp db size

Displays the database name and size.

wp db size [--size_format=<format>] [--tables] [--human-readable] [--format=<format>] [--scope=<scope>] [--network] [--decimals=<decimals>] [--all-tables-with-prefix] [--all-tables] [--order=<order>] [--orderby=<orderby>]

Display the database name and size for DB_NAME specified in wp-config.php. The size defaults to a human-readable number.

Available size formats include:

  • b (bytes)
  • kb (kilobytes)
  • mb (megabytes)
  • gb (gigabytes)
  • tb (terabytes)
  • B (ISO Byte setting, with no conversion)
  • KB (ISO Kilobyte setting, with 1 KB = 1,000 B)
  • KiB (ISO Kibibyte setting, with 1 KiB = 1,024 B)
  • MB (ISO Megabyte setting, with 1 MB = 1,000 KB)
  • MiB (ISO Mebibyte setting, with 1 MiB = 1,024 KiB)
  • GB (ISO Gigabyte setting, with 1 GB = 1,000 MB)
  • GiB (ISO Gibibyte setting, with 1 GiB = 1,024 MiB)
  • TB (ISO Terabyte setting, with 1 TB = 1,000 GB)
  • TiB (ISO Tebibyte setting, with 1 TiB = 1,024 GiB)

OPTIONS

[--size_format=<format>]
	Display the database size only, as a bare number.
	---
	options:
	  - b
	  - kb
	  - mb
	  - gb
	  - tb
	  - B
	  - KB
	  - KiB
	  - MB
	  - MiB
	  - GB
	  - GiB
	  - TB
	  - TiB
	---

[--tables]
	Display each table name and size instead of the database size.

[--human-readable]
	Display database sizes in human readable formats.

[--format=<format>]
	Render output in a particular format.
	---
	options:
	  - table
	  - csv
	  - json
	  - yaml
	---

[--scope=<scope>]
	Can be all, global, ms_global, blog, or old tables. Defaults to all.

[--network]
	List all the tables in a multisite install.

[--decimals=<decimals>]
	Number of digits after decimal point. Defaults to 0.

[--all-tables-with-prefix]
	List all tables that match the table prefix even if not registered on $wpdb. Overrides --network.

[--all-tables]
	List all tables in the database, regardless of the prefix, and even if not registered on $wpdb. Overrides --all-tables-with-prefix.

[--order=<order>]
	Ascending or Descending order.
	---
	default: asc
	options:
	  - asc
	  - desc
	---

[--orderby=<orderby>]
	Order by fields.
	---
	default: name
	options:
	  - name
	  - size
	---

EXAMPLES

$ wp db size
+-------------------+------+
| Name              | Size |
+-------------------+------+
| wordpress_default | 6 MB |
+-------------------+------+

$ wp db size --tables
+-----------------------+-------+
| Name                  | Size  |
+-----------------------+-------+
| wp_users              | 64 KB |
| wp_usermeta           | 48 KB |
| wp_posts              | 80 KB |
| wp_comments           | 96 KB |
| wp_links              | 32 KB |
| wp_options            | 32 KB |
| wp_postmeta           | 48 KB |
| wp_terms              | 48 KB |
| wp_term_taxonomy      | 48 KB |
| wp_term_relationships | 32 KB |
| wp_termmeta           | 48 KB |
| wp_commentmeta        | 48 KB |
+-----------------------+-------+

$ wp db size --size_format=b
5865472

$ wp db size --size_format=kb
5728

$ wp db size --size_format=mb
6

wp db columns

Displays information about a given table.

wp db columns <table> [--format]

OPTIONS

<table>
	Name of the database table.

[--format]
	Render output in a particular format.
	---
	default: table
	options:
	  - table
	  - csv
	  - json
	  - yaml
	---

EXAMPLES

$ wp db columns wp_posts
+-----------------------+---------------------+------+-----+---------------------+----------------+
|         Field         |        Type         | Null | Key |       Default       |     Extra      |
+-----------------------+---------------------+------+-----+---------------------+----------------+
| ID                    | bigint(20) unsigned | NO   | PRI |                     | auto_increment |
| post_author           | bigint(20) unsigned | NO   | MUL | 0                   |                |
| post_date             | datetime            | NO   |     | 0000-00-00 00:00:00 |                |
| post_date_gmt         | datetime            | NO   |     | 0000-00-00 00:00:00 |                |
| post_content          | longtext            | NO   |     |                     |                |
| post_title            | text                | NO   |     |                     |                |
| post_excerpt          | text                | NO   |     |                     |                |
| post_status           | varchar(20)         | NO   |     | publish             |                |
| comment_status        | varchar(20)         | NO   |     | open                |                |
| ping_status           | varchar(20)         | NO   |     | open                |                |
| post_password         | varchar(255)        | NO   |     |                     |                |
| post_name             | varchar(200)        | NO   | MUL |                     |                |
| to_ping               | text                | NO   |     |                     |                |
| pinged                | text                | NO   |     |                     |                |
| post_modified         | datetime            | NO   |     | 0000-00-00 00:00:00 |                |
| post_modified_gmt     | datetime            | NO   |     | 0000-00-00 00:00:00 |                |
| post_content_filtered | longtext            | NO   |     |                     |                |
| post_parent           | bigint(20) unsigned | NO   | MUL | 0                   |                |
| guid                  | varchar(255)        | NO   |     |                     |                |
| menu_order            | int(11)             | NO   |     | 0                   |                |
| post_type             | varchar(20)         | NO   | MUL | post                |                |
| post_mime_type        | varchar(100)        | NO   |     |                     |                |
| comment_count         | bigint(20)          | NO   |     | 0                   |                |
+-----------------------+---------------------+------+-----+---------------------+----------------+

Installing

This package is included with WP-CLI itself, no additional installation necessary.

To install the latest version of this package over what's included in WP-CLI, run:

wp package install [email protected]:wp-cli/db-command.git

Contributing

We appreciate you taking the initiative to contribute to this project.

Contributing isnโ€™t limited to just code. We encourage you to contribute in the way that best fits your abilities, by writing tutorials, giving a demo at your local meetup, helping other users with their support questions, or revising our documentation.

For a more thorough introduction, check out WP-CLI's guide to contributing. This package follows those policy and guidelines.

Reporting a bug

Think youโ€™ve found a bug? Weโ€™d love for you to help us get it fixed.

Before you create a new issue, you should search existing issues to see if thereโ€™s an existing resolution to it, or if itโ€™s already been fixed in a newer version.

Once youโ€™ve done a bit of searching and discovered there isnโ€™t an open or fixed issue for your bug, please create a new issue. Include as much detail as you can, and clear steps to reproduce if possible. For more guidance, review our bug report documentation.

Creating a pull request

Want to contribute a new feature? Please first open a new issue to discuss whether the feature is a good fit for the project.

Once you've decided to commit the time to seeing your pull request through, please follow our guidelines for creating a pull request to make sure it's a pleasant experience. See "Setting up" for details specific to working on this package locally.

Support

GitHub issues aren't for general support questions, but there are other venues you can try: https://wp-cli.org/#support

This README.md is generated dynamically from the project's codebase using wp scaffold package-readme (doc). To suggest changes, please submit a pull request against the corresponding part of the codebase.

db-command's People

Contributors

abhijitrakas avatar austinginder avatar chriswiegman avatar clemens-tolboom avatar danielbachhuber avatar ernilambar avatar francescolaffi avatar gitlost avatar itsananderson avatar janw-me avatar lkwdwrd avatar lukecav avatar marksabbath avatar matiskay avatar miya0001 avatar mmcev106 avatar mpeshev avatar mwilliamson avatar natewr avatar nikschavan avatar nyordanov avatar petenelson avatar pmgarman avatar schlessera avatar scribu avatar swissspidy avatar szepeviktor avatar thrijith avatar westonruter avatar wojsmol avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

db-command's Issues

db size does not work with Bedrock

Hi,

I'm using Bedrock as project boilerplate, so wp-config.php in WordPress root directory acts only as loader for actual configuration files that are included via require_once.

When running wp db size, I get:

Error: The site you have requested is not installed.
Run `wp core install`.

For some reason, $table_prefix is not read from config. Here's the stack trace:

[06-Jun-2017 08:35:08 UTC] PHP Notice:  Undefined variable: table_prefix in /[...]/wordpress/wp-settings.php on line 110
[06-Jun-2017 08:35:08 UTC] PHP Stack trace:
[06-Jun-2017 08:35:08 UTC] PHP   1. {main}() /[...]/wp-cli/wp-cli.phar:0
[06-Jun-2017 08:35:08 UTC] PHP   2. include() /[...]/wp-cli/wp-cli.phar:4
[06-Jun-2017 08:35:08 UTC] PHP   3. include() phar:///[...]/wp-cli/wp-cli.phar/php/boot-phar.php:8
[06-Jun-2017 08:35:08 UTC] PHP   4. WP_CLI\bootstrap() phar:///[...]/wp-cli/wp-cli.phar/php/wp-cli.php:23
[06-Jun-2017 08:35:08 UTC] PHP   5. WP_CLI\Bootstrap\LaunchRunner->process($state = class WP_CLI\Bootstrap\BootstrapState { private $state = array (...) }) phar:///[...]/wp-cli/wp-cli.phar/php/bootstrap.php:75
[06-Jun-2017 08:35:08 UTC] PHP   6. WP_CLI\Runner->start() phar:///[...]/wp-cli/wp-cli.phar/php/WP_CLI/Bootstrap/LaunchRunner.php:23
[06-Jun-2017 08:35:08 UTC] PHP   7. WP_CLI\Runner->_run_command() phar:///[...]/wp-cli/wp-cli.phar/php/WP_CLI/Runner.php:883
[06-Jun-2017 08:35:08 UTC] PHP   8. WP_CLI\Runner->run_command($args = array (0 => 'db', 1 => 'size'), $assoc_args = array (), $options = *uninitialized*) phar:///[...]/wp-cli/wp-cli.phar/php/WP_CLI/Runner.php:328
[06-Jun-2017 08:35:08 UTC] PHP   9. WP_CLI\Dispatcher\Subcommand->invoke($args = array (), $assoc_args = array (), $extra_args = array ()) phar:///[...]/wp-cli/wp-cli.phar/php/WP_CLI/Runner.php:321
[06-Jun-2017 08:35:08 UTC] PHP  10. call_user_func:{phar:///[...]/wp-cli/wp-cli.phar/php/WP_CLI/Dispatcher/Subcommand.php:401}(class Closure { public $static = array (...); public $parameter = array (...) }, array (), array ()) phar:///[...]/wp-cli/wp-cli.phar/php/WP_CLI/Dispatcher/Subcommand.php:401
[06-Jun-2017 08:35:08 UTC] PHP  11. WP_CLI\Dispatcher\CommandFactory::WP_CLI\Dispatcher\{closure}($args = array (), $assoc_args = array ()) phar:///[...]/wp-cli/wp-cli.phar/php/WP_CLI/Dispatcher/Subcommand.php:401
[06-Jun-2017 08:35:08 UTC] PHP  12. call_user_func:{phar:///[...]/wp-cli/wp-cli.phar/php/WP_CLI/Dispatcher/CommandFactory.php:67}(array (0 => class DB_Command { ... }, 1 => 'size'), array (), array ()) phar:///[...]/wp-cli/wp-cli.phar/php/WP_CLI/Dispatcher/CommandFactory.php:67
[06-Jun-2017 08:35:08 UTC] PHP  13. DB_Command->size($args = array (), $assoc_args = array ()) phar:///[...]/wp-cli/wp-cli.phar/php/WP_CLI/Dispatcher/CommandFactory.php:67
[06-Jun-2017 08:35:08 UTC] PHP  14. WP_CLI\Runner->load_wordpress() /[...]/.wp-cli/packages/vendor/wp-cli/db-command/src/DB_Command.php:566
[06-Jun-2017 08:35:08 UTC] PHP  15. require() phar:///[...]/wp-cli/wp-cli.phar/php/WP_CLI/Runner.php:988

Some more observations:

  1. I have no problem running other commands, db size is the only one causing this issue.
  2. I'm using WP-CLI via phar downloadable, but I manually installed latest dev version of db-command package.
  3. If files in wp-config.php are included via require instead of require_once, the issue is gone.

Avoid use of `@WP_CLI::get_runner()->load_wordpress();` in `wp db *` commands

wp db search (and other wp db * commands) call @WP_CLI::get_runner()->load_wordpress(); because WP-CLI executes wp db * commands after wp-config.php has loaded but before the rest of WordPress has loaded: https://github.com/wp-cli/wp-cli/blob/d9d405a4ca01ba23e80277b8cb9000857e84e0cd/php/WP_CLI/Runner.php#L875

Calling @WP_CLI::get_runner()->load_wordpress(); to avoid redefinition of constants in wp-config.php is a hack. Instead, these commands should continue loading WordPress without loading wp-config.php again.

Related #15

Feature Request: Return number of rows affected by update/delete queries.

Hello.

I recently used WP-CLI to run some SQL queries.
After they run, I only got a success or failure message.
If it was a success, I did not receive any feedback about how many rows were affected.
Running the query directly in MySQL, it lets me know how many rows were affected.

It was would nice to have that metric returned or optionally returned.

Not sure if that would be part of the normal output or added as a new switch.

Thank you for your time.

`wp db tables` does not obey prefix when using table wildcards

Default behaviour of wp db tables is to only show tables that match the prefix that is set in the wp-config.php file.

However, if a wildcard is added to only retrieve a specific subset of tables, the prefix in wp-config.php is ignored, and all matching tables are shown.

image 2017-12-21 at 11 44 50 am

In the above screenshot, the queries with a wildcard not only show as_wp_posts, but also wp_posts. The expected behavior would be to only show as_wp_posts. Even trying to force the (default) option to obey the prefix does not produce the expected result.

Provide parameters for DB user/password

There's the need for parameters to specify database username and password other than the ones in wp-config.php.

The --<field>=<value> syntax works for the password, but it fails for the user because the --user parameter is already taken to specify the WordPress user.

See here for more details.

I suggest to create new parameters, namely --dbuser and --dbpass and bind them to the --user and --password parameters of mysqldump respectively (albeit a new mapping for --password is not strictly required, but adding it nonetheless makes things cleaner).

Move command over to new v2 structure

The following changes need to be made to move the command over to the v2 structure:

  • Make sure the correct framework is required:
    composer require wp-cli/wp-cli:^2
    
  • Require the testing framework as a dev dependency:
    composer require --dev wp-cli/wp-cli-tests:^0
    
  • Use the .travis.yml file from wp-cli/wp-cli:
    wget https://raw.githubusercontent.com/wp-cli/wp-cli/master/.travis.yml
    
  • Add the default script configuration to Composer file:
      "scripts": {
          "lint": "run-linter-tests",
          "phpcs": "run-phpcs-tests",
          "phpunit": "run-php-unit-tests",
          "behat": "run-behat-tests",
          "prepare-tests": "install-package-tests",
          "test": [
              "@lint",
              "@phpcs",
              "@phpunit",
              "@behat"
          ]
      },
    
  • Remove scaffolded binary files:
    git rm bin/install-package-tests.sh
    git rm bin/test.sh
    
  • Remove scaffolded Behat setup:
    git rm features/bootstrap/*
    git rm features/extra/*
    git rm features/steps/*
    
  • Remove scaffolded Behat tags util script:
    git rm utils/behat-tags.php
    
  • Add command packages that are needed for Behat tests as --dev dependencies.
    The following commands are already available, anything else needs to be explicitly required:
    • cli *
    • config *
    • core *
    • eval
    • eval-file
    • help
  • Update all dependencies:
    composer update
    
  • Optional - Add PHPCS rule set to enable CS & compatibility sniffing:
    wget https://raw.githubusercontent.com/wp-cli/wp-cli/master/phpcs.xml.dist
    
  • Run and adapt tests to make sure they all pass:
    composer test
    

Suggestion for size command to make the default size_format KB or MB

I'm loving this new db size command and I always find myself adding the --size_format flag because bytes are not very human-readable friendly. I'd like to suggest making the default size_format KB or MB, personally I think megabytes make more sense. Here is the output from the three commands for a default WordPress installation.

wp db size --tables

+-----------------------+---------+
| Name                  | Size    |
+-----------------------+---------+
| wp_commentmeta        | 49152 B |
| wp_comments           | 98304 B |
| wp_links              | 32768 B |
| wp_options            | 65536 B |
| wp_postmeta           | 49152 B |
| wp_posts              | 81920 B |
| wp_term_relationships | 32768 B |
| wp_term_taxonomy      | 49152 B |
| wp_termmeta           | 49152 B |
| wp_terms              | 49152 B |
| wp_usermeta           | 49152 B |
| wp_users              | 65536 B |
+-----------------------+---------+

wp db size --tables --size_format=mb

+-----------------------+------+
| Name                  | Size |
+-----------------------+------+
| wp_commentmeta        | 1 MB |
| wp_comments           | 1 MB |
| wp_links              | 1 MB |
| wp_options            | 1 MB |
| wp_postmeta           | 1 MB |
| wp_posts              | 1 MB |
| wp_term_relationships | 1 MB |
| wp_term_taxonomy      | 1 MB |
| wp_termmeta           | 1 MB |
| wp_terms              | 1 MB |
| wp_usermeta           | 1 MB |
| wp_users              | 1 MB |
+-----------------------+------+

wp db size --tables --size_format=kb

+-----------------------+-------+
| Name                  | Size  |
+-----------------------+-------+
| wp_commentmeta        | 48 KB |
| wp_comments           | 96 KB |
| wp_links              | 32 KB |
| wp_options            | 64 KB |
| wp_postmeta           | 48 KB |
| wp_posts              | 80 KB |
| wp_term_relationships | 32 KB |
| wp_term_taxonomy      | 48 KB |
| wp_termmeta           | 48 KB |
| wp_terms              | 48 KB |
| wp_usermeta           | 48 KB |
| wp_users              | 64 KB |
+-----------------------+-------+

Table list can sometimes include tables that don't exist

When you run wp db tables on multisite, it can (erroneously) report the sitecategories table to exist when it's not actually created in the database.

Under the hood, wp db tables is reporting the tables registered to the $wpdb object. Apparently WordPress adds the sitecategories table to $wpdb when it's not actually in use.

I don't have a strong opinion on how to fix (or whether we should fix). Logging here for visibility.

Originally reported in https://wordpress.org/support/topic/wp-cli-db-tables-lists-non-existent-tables/

size_format not working correct for DB size

Using latest version:

$ wp cli version
WP-CLI 1.5.1

The tables shows correct format as fixed in #64 :

$ wp db size --format=csv --size_format=mb --tables
Name,Size
wp_commentmeta,"1 MB"
wp_comments,"1 MB"
wp_links,"1 MB"
wp_options,"5 MB"
wp_postmeta,"2018 MB"
wp_posts,"45 MB"
wp_term_relationships,"4 MB"
wp_term_taxonomy,"1 MB"
wp_termmeta,"1 MB"
wp_terms,"1 MB"
wp_usermeta,"1 MB"
wp_users,"1 MB"

but database name is not written

$ wp db size --format=csv --size_format=mb
4511

; without option it works fine:

$ wp db size --format=csv
Name,Size
wordpress_test,"4730109952 B"

size format option 'kb' actually returns value in Kib

I'm sure nobody notices or cares, but it did actually throw me for a loop trying to chase down a separate db related issue.

The CLI docs for db say size_format flag can return optional values as follows:

$ wp help db size
  ...
  [--size_format]
    Display the database size only, as a bare number.
    ---
    default: b
    options:
     - b (bytes)
     - kb (kilobytes)
     - mb (megabytes)
     - gb (gigabytes)
     - tb (terabytes)
     ---

Goes on to show an example of returned values for options =b, =kb, =mb where the kb value actually seems to be reporting in kibibytes

Solution: Add footnote or short blurb in the doc mentioning the returned value for kb will report what might be slightly lower than expected since its factored by 1024 (not 1000)

1 KiB (Kibibyte) = 1,024 B (Bytes) (2^10 Bytes)
1 kb  (Kilobit)  =   125 B (Bytes) (10^3 Bits รท (8 bits / byte) = 125 B)
1 kB  (Kilobyte) = 1,000 B (Bytes) (10^3 Bytes)

Logic in `DB_Command::esc_like()` WP polyfill is not robust

The logic in the DB_Command::esc_like() WP polyfile is not robust:

db-command/src/DB_Command.php

Lines 1075 to 1082 in a8a4a9d

// Remove notices in 4.0 and support backwards compatibility
if ( method_exists( $wpdb, 'esc_like' ) ) {
// 4.0
$old = $wpdb->esc_like( $old );
} else {
// 3.9 or less
$old = like_escape( esc_sql( $old ) );
}

The first conditional actually includes two requirements, but the else clause still fails for one of them.

For the first conditional to pass, the method needs not only to exist on the $wpdb variable, for this to be possible, $wpdb also needs to be a valid wpdb instance.

If $wpdb happens to be null for whatever reason (like calling DB_Command::esc_like() too early in the WP execution flow), then we'll call the deprecated like_escape() (and throw a notice), even though we might be on the latest WP version.

I'd suggest to throw a WP-CLI error inside of this polyfill if $wpdb happens to be null, to get rid of the notice and point to the correct issue.

Mention database name when confirming operation

When confirming an operation in the wp db * set of commands, it would be helpful to indicate the database name in the confirmation prompt.

Instead of:

$ wp db drop
Are you sure you want to drop the database? [y/n] y
Success: Database dropped

It would be:

$ wp db drop
Are you sure you want to drop the 'wpcli' database? [y/n] y
Success: Database dropped

This change should affect:

  • wp db drop
  • wp db reset

Automatically add the DB_PREFIX to the `columns` command.

Currently the column command requires the user to know the DB_PREFIX:

$ wp db columns posts
Error: Couldn't find any tables matching: posts

$ wp db columns wp_posts
Error: Couldn't find any tables matching: wp_posts

$ wp db columns foo_posts
+-----------------------+---------------------+------+-----+---------------------+----------------+
| Field                 | Type                | Null | Key | Default             | Extra          |
+-----------------------+---------------------+------+-----+---------------------+----------------
...
+

The command should accept the general posts parameter and add the proper DB_PREFIX.

wp db export <[file]> always fails when used with --tables

This may be intentional, but it is not mentioned in documentation that a custom file cannot be passed as <[file]> whilst using the --tables option. In other commands such as search-replace for example <[file]> can be passed.

Example

wp db export /srv/www/example.com/shared/exports/partial-export.sql --tables=$(wp db tables --scope=blog --url=sub.example.com  --format=csv)

Expected Result

Success: Exported to '/srv/www/example.com/shared/exports/partial-export.sql'

Actual Result

Error: Too many positional arguments:--tables='wp_*_commentmeta,wp_*_comments,fat_*_links,fat_*_options,fat_*_postmeta,fat_*_posts,fat_*_term_relationships,fat_*_term_taxonomy,fat_*_termmeta,fat_*_terms'

IDs obfuscated

Steps taken

  • Confirmed that $(wp db tables --scope=blog --url=sub.example.com --format=csv) returns CSV
  • Manually provided tables to db export tables flag (to eliminate escape / quote issues)
  • Escaped and quoted file names, directories etc
  • Confirmed that the table option works as expected when <[file]> isn't provided

Environment

OS:	Linux 4.4.0-38-generic #57-Ubuntu SMP Tue Sep 6 15:42:33 UTC 2016 x86_64
Shell:	/bin/bash
PHP binary:	/usr/bin/php7.2
PHP version:	7.2.5-1+ubuntu16.04.1+deb.sury.org+1
php.ini used:	/etc/php/7.2/cli/php.ini
WP-CLI root dir:	phar://wp-cli.phar/vendor/wp-cli/wp-cli
WP-CLI vendor dir:	phar://wp-cli.phar/vendor
WP_CLI phar path:	/mnt/www/example.com/releases/20190117153517
WP-CLI packages dir:
WP-CLI global config:
WP-CLI project config:	/mnt/www/example.com/releases/20190117153517/wp-cli.yml
WP-CLI version:	2.1.0

Progress on import?

Any possibility of adding a progress bar on import? When adding massive dbs it would be great to know how much of the file has been processed.

wp db export fails on Percona-XtraDB-Cluster โ€“ย mysqldump with --no-defaults

On Percona XtraDB Cluster with pxc_strict_mode = ENFORCING (the default)
wp db export - fails with the following error message:

mysqldump: Got error: 1105: "Percona-XtraDB-Cluster prohibits use of LOCK TABLE/FLUSH TABLE <table> WITH READ LOCK with pxc_strict_mode = ENFORCING" when using LOCK TABLES

For this Server/Server configuration mysqldump needs to be executed with an additional argument --lock-for-backup. Since wp db export calls mysqldump with the --no-defaults setting I cannot add this in a configuration file but need to provide it as a command line argument.

I think it would make sense to add the ability to append arbitrary command line arguments to the mysqldump call. This would be beneficial not only for this case but also for e.g. adding --no-lock-tables or --single-transaction to the mysqldump call and thus tweak the desired consistency and concurrency of the database backup.

Document that `wp db optimize` runs on the entire database

I have 2 separate installations of Wordpress (Multisite) in 2 different folders. wp-cli commands run differently under each folder.
Yet wp db optimize optimizes tables for both installations.

Not that I mind, but someone else may.

Absolute path to MySQL executable

After weeks tracking down an obscure error in our setup, we finally identified the cause of the problem.

  • The db module falls back to shell for commands such as self::run( 'mysql --no-defaults --no-auto-rehash', $assoc_args );
  • My bash profile had an alias for mysql that added an option --prompt='...' (the actual prompt was more complex, ommitted for simplicity.
  • The --no-defaults option demands to be the first option on the command line, but has a really unhelpful error message (it claims unknown option '--no-defaults', which isn't true for either MySQL or MariaDB).

Steps to reproduce:

  1. Set an alias in your bash profile such as:
    alias mysql='/usr/bin/mysql --prompt='mysql> '
  2. Open a new shell that picks up that alias
  3. Call wp db cli

Fix:

On our own side, the fix is simply to remove the alias so the environment is normal.

But it also seems that WP-CLI should be calling the MySQL executable absolutely rather than relying on the individual's environment. Any code that references mysql, mysqlcheck, mysqldump etc should instead use env, eg:

self::run( '/usr/bin/env mysql --no-defaults --no-auto-rehash', $assoc_args );

db reset shouldn't drop the db

wp db reset drops the entire database and recreates it. However, if you have multiple WP instances sharing the same DB (using different table prefixes) that kills all the instances, not just the one you need to reset.

Please either change the semantics of wp db reset or provide a new wp db clean command (or similar command name) that only drops the tables.

wp db limit to db prefix

Usually wp cli commands are limited in scope to the db prefix of the current installation, unless using e.g. --all-tables flag (e.g. in wp search-replace)

I suggest to also limit wp db reset (and perhaps also the other wp db commands) to the current page prefix (unless --all-tables is specified), as it will happen that people use wp db reset and, without realizing, delete ALL tables in the current database, instead of only the tables of the current installation.

Add example of how to search and delete results

For those wanting to clean up parts of their database, it'd be neat to have a wp db search example indicating how to search for a string and delete the resulting database entry.

danhgilmore [7:14 AM] I think I've asked this in the past, but I'm just now getting back to working with wp-cli....is there a way to search/delete instead of search/replace?
[7:15] I am cleaning up our DB, and there's a lot of things orphaned in the wp_X_options tables that I'd like to search for and then remove.
janw.oostendorp [7:37 AM] pass an empty string within quotes? Won't delete empty meta/options
danhgilmore [7:38 AM] Yeah, I'm trying to remove the records from the database ๐Ÿ˜•

From https://wordpress.slack.com/archives/C02RP4T41/p1506435293000491

wp db size doesn't like if-statements in wp-config.php

I have the following in my wp-config.php file:

if ( WP_DEBUG ) {
        @error_reporting( E_ALL );
        @ini_set( 'log_errors', true );
        @ini_set( 'log_errors_max_len', '0' );
        if ( !defined('WP_DEBUG_LOG' ) ) define( 'WP_DEBUG_LOG', true );
        if ( !defined('WP_DEBUG_DISPLAY' ) ) define( 'WP_DEBUG_DISPLAY', false);
        if ( !defined('CONCATENATE_SCRIPTS' ) ) define( 'CONCATENATE_SCRIPTS', false );
        if ( !defined('SAVEQUERIES' ) ) define( 'SAVEQUERIES', true );
}

If I have any defines after that section, any time I run wp db size I'll get this:

$ wp db size
PHP Notice:  Constant Mika_Test already defined in /usr/local/wp/php/WP_CLI/Runner.php(1070) : eval()'d code on line 99

Notice: Constant Mika_Test already defined in /usr/local/wp/php/WP_CLI/Runner.php(1070) : eval()'d code on line 99
+------------------+-------+
| Name             | Size  |
+------------------+-------+
| my_test_domain  | 40 MB |
+------------------+-------+

However all other commands I've tested work.

If WP_DEBUG is false, there's no error.

Command for fetching the table prefix

wp db query <query> is handy when you know the table prefix, or when it's set to the default wp_. If not, then there's no built-in way to write a portable version of something like wp db query "SELECT * FROM wp_posts" which uses the correct name for the posts table according to the table prefix.

It would be handy to have a command to fetch the database prefix:

wp db query "SELECT * FROM $(wp db prefix)posts"

My current workaround is:

wp db query "SELECT * FROM $(wp db tables *posts)"

While this does work, it seems fragile. Another option might be a command to fetch the complete table name:

wp db query "SELECT * FROM $(wp db tablename posts)"

Large requests exhaust max_connections

Performing large requests vi wp db creates situations where the MySQL max_connections is exhausted. We have a shared DB server (MySQL 5.0.95-log) on CentOS 5.10.

Running wp db reset from a Wordpress app server takes a very long time (large multisite database), and requests pile up, eventually causing the MySQL max_connections limit (currently 160) to be reached.

Performing a drop table query directly on the sql server does not exhaust the connections.

Am I missing something regarding the usage of wp db commands and remote SQL servers?

Automatically rerun failed scenarios

The following changes need to be made:

  1. In the .travis.yml file, the - composer behat line in the script: section needs to be changed into the following:
- composer behat || composer behat-rerun
  1. In the composer-json file, the requirement on wp-cli/wp-cli-tests needs to be adapted to require at least v2.0.7:
"wp-cli/wp-cli-tests": "^2.0.7"
  1. In the composer-json file, the "scripts" section needs to be extended. Immediately after the line "behat": "run-behat-tests",, the following line needs to be inserted:
"behat-rerun": "rerun-behat-tests",

Here's an example of how this should look like:

Request adding `--where` to `wp db export`

I see wp db export uses mysqldump. I'd like to be able to pass a --where argument to the mysqldump's where option. The would allow for a selective data dumps. Examples of how I think it should work.

Export selective posts
wp db export --tables=wp_posts --where="ID in (100,101,102)" --no-create-info

Export relating meta for selective posts
wp db export --tables=wp_postmeta --where="post_id in (100,101,102)" --no-create-info

For reference the following mysqldump does work.

mysqldump -u$(wp config get DB_USER) -p$(wp config get DB_PASSWORD) $(wp config get DB_NAME) --no-create-info --tables wp_posts --where="ID in (100,101,102)"
mysqldump -u$(wp config get DB_USER) -p$(wp config get DB_PASSWORD) $(wp config get DB_NAME) --no-create-info --tables wp_postmeta --where="post_id in (100,101,102)"

Internalize `like_escape()` and `esc_sql()` functions to avoid `$wpdb` dependency

Received a Fatal Error when running the following command:

$ wp db search "hello" --path=/Users/andrew/wp/

Fatal error: Call to undefined function like_escape() in /Users/andrew/wp-cli/db-command/src/DB_Command.php on line 1081

Scenarios:

  1. When running the command inside the db-command directory, that is when the error appear.
  2. When running the command in my home directory, the error does not appear.

My environment:

$ wp --info
PHP binary:	/usr/bin/php
PHP version:	5.6.30
php.ini used:	
WP-CLI root dir:	phar://wp-cli.phar
WP-CLI vendor dir:	phar://wp-cli.phar/vendor
WP_CLI phar path:	/Users/andrew/wp-cli/db-command
WP-CLI packages dir:	
WP-CLI global config:	
WP-CLI project config:	/Users/andrew/wp-cli/db-command/wp-cli.yml
WP-CLI version:	1.4.1

Add --skip-tables argument to wp db export

It would be great to have an option to skip tables during a database export like so:

wp db export --skip-tables=<tables>

The main use case would be when you have too many tables to list that you want to include in an export, or you don't know what plugins your team or client will be adding before an export.

For example, you could exclude Wordfence tables by doing:

wp db export --skip-tables=$(wp db tables 'wp_wf*')

Is it possible to enhance table format with right-align numeric values easily?

because the length is already calculated / formatted correctly but is very unhandy to check/read while numbers are left-aligned like here:

root@test-server ~ # sudo -u www-data -s -- wp db size --path=/path/to/wordpress/staging/current --tables
+-----------------------+--------------+
| Name                  | Size         |
+-----------------------+--------------+
| wp_commentmeta        | 49152 B      |
| wp_comments           | 98304 B      |
| wp_links              | 32768 B      |
| wp_options            | 4751360 B    |
| wp_postmeta           | 2267021312 B |
| wp_posts              | 46792704 B   |
| wp_term_relationships | 3178496 B    |
| wp_term_taxonomy      | 507904 B     |
| wp_termmeta           | 950272 B     |
| wp_terms              | 573440 B     |
| wp_usermeta           | 425984 B     |
| wp_users              | 65536 B      |
+-----------------------+--------------+

As far I can see the table output is triggered in
https://github.com/wp-cli/db-command/blob/master/src/DB_Command.php#L875-L876

and uses Formatter object/functions (without orderby / include_totals) of this module:
https://github.com/wp-cli/profile-command/blob/master/inc/class-formatter.php#L77

(but not sure - normally using no PHP as system administrator ๐Ÿ˜„)

`wp db size --all-tables --size_format=mb` produces unexpected results

Current behavior on v2.1.0:

$ wp db size --all-tables --size_format=mb
924

Expected behavior would be something similar to this:

$ wp db size --scope=all --tables --size_format=mb
+-----------------------+--------+
| Name                  | Size   |
+-----------------------+--------+
| wp_commentmeta        | 56 MB  |
| wp_comments           | 72 MB  |
| wp_links              | 1 MB   |
| wp_options            | 8 MB   |
| wp_postmeta           | 76 MB  |
| wp_posts              | 300 MB |
| wp_term_relationships | 3 MB   |
| wp_term_taxonomy      | 4 MB   |
| wp_termmeta           | 1 MB   |
| wp_terms              | 5 MB   |
| wp_usermeta           | 1 MB   |
| wp_users              | 1 MB   |
| wp_yoast_seo_links    | 4 MB   |
| wp_yoast_seo_meta     | 1 MB   |
+-----------------------+--------+

Here's a truncated list of all of my tables:

$ wp db tables --all-tables
_mig_wpmdb_alter_statements
wp_ai_statistics
wp_commentmeta
wp_comments
wp_facetwp_index
wp_links
wp_nf3_action_meta
wp_nf3_actions
wp_nf3_chunks
[...]

Default value of size_format flag is incorrect

The help doc for wp db size states that the default value of the --size_format flag is b (for bytes), but that's not the case. The default size format appears to be the largest unit that fits the value.

WP DB won't work if db connection is secured

Hello guys and gals! Anyone got wp-cli to work with secured database connections? Seems not working and seems people are rarely using a secured database connections(for remote databases)?

Add `--human-readable` flag to `db size`

like many functions have like:

root@wordpress-test /var/lib/mysql/wordpress_test # du -h *.ibd
132K    wp_commentmeta.ibd
180K    wp_comments.ibd
112K    wp_links.ibd
15M     wp_options.ibd
2.2G    wp_postmeta.ibd
53M     wp_posts.ibd
996K    wp_termmeta.ibd
12M     wp_term_relationships.ibd
628K    wp_terms.ibd
564K    wp_term_taxonomy.ibd
484K    wp_usermeta.ibd
148K    wp_users.ibd

compared to default Bytes:

$ wp db size --format=csv --tables
Name,Size
wp_commentmeta,"49152 B"
wp_comments,"98304 B"
wp_links,"32768 B"
wp_options,"4751360 B"
wp_postmeta,"2116026368 B"
wp_posts,"46792704 B"
wp_term_relationships,"3178496 B"
wp_term_taxonomy,"507904 B"
wp_termmeta,"950272 B"
wp_terms,"573440 B"
wp_usermeta,"425984 B"
wp_users,"65536 B"

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.