Skip to content

Commit b9a78c4

Browse files
Copilotswissspidy
andauthored
Add wp db status command for database health overview (#307)
Co-authored-by: Pascal Birchler <pascal.birchler@gmail.com>
1 parent 9423837 commit b9a78c4

3 files changed

Lines changed: 302 additions & 1 deletion

File tree

‎composer.json‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,8 @@
5050
"db search",
5151
"db tables",
5252
"db size",
53-
"db columns"
53+
"db columns",
54+
"db status"
5455
]
5556
},
5657
"autoload": {

‎features/db-status.feature‎

Lines changed: 115 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,115 @@
1+
Feature: Display database status overview
2+
3+
@require-mysql-or-mariadb
4+
Scenario: Display database status for a WordPress install
5+
Given a WP install
6+
7+
When I run `wp db status`
8+
Then STDOUT should contain:
9+
"""
10+
Database Name: {DB_NAME}
11+
"""
12+
And STDOUT should match /^Tables:\s+\d+$/m
13+
And STDOUT should match /^Total Size:\s+[\d.]+ [KM]?B$/m
14+
And STDOUT should contain:
15+
"""
16+
Prefix: wp_
17+
"""
18+
And STDOUT should match /^Engine:\s+\w+$/m
19+
And STDOUT should match /^Charset:\s+\w+$/m
20+
And STDOUT should match /^Collation:\s+\w+$/m
21+
And STDOUT should contain:
22+
"""
23+
Check Status: OK
24+
"""
25+
26+
When I run `wp db status --skip-check --format=json`
27+
Then STDOUT should be JSON containing:
28+
"""
29+
{"database":"{DB_NAME}","prefix":"wp_","check":"Skipped"}
30+
"""
31+
And STDOUT should match /"tables":\d+,"size":\d+,/
32+
33+
@require-mysql-or-mariadb
34+
Scenario: Display database status before WordPress is installed
35+
Given an empty directory
36+
And WP files
37+
And wp-config.php
38+
And a database
39+
40+
When I run `wp db status`
41+
Then STDOUT should contain:
42+
"""
43+
Database Name: {DB_NAME}
44+
Tables: 0
45+
Total Size: 0 B
46+
Prefix: wp_
47+
Engine: N/A
48+
Charset: N/A
49+
Collation: N/A
50+
Check Status: N/A
51+
"""
52+
53+
@require-mysql-or-mariadb
54+
Scenario: Report mixed table engines
55+
Given a WP install
56+
57+
When I run `wp db query "CREATE TABLE wp_status_test (id INT) ENGINE=MyISAM"`
58+
And I run `wp db status --skip-check`
59+
Then STDOUT should contain:
60+
"""
61+
Engine: Mixed
62+
"""
63+
64+
@require-mysql-or-mariadb
65+
Scenario: Run db status with passed-in options
66+
Given a WP install
67+
68+
When I run `wp db status --defaults`
69+
Then STDOUT should contain:
70+
"""
71+
Check Status: OK
72+
"""
73+
74+
When I run `wp db status --no-defaults`
75+
Then STDOUT should contain:
76+
"""
77+
Check Status: OK
78+
"""
79+
80+
When I run `wp db status --dbuser={DB_USER} --dbpass=password1`
81+
Then STDOUT should contain:
82+
"""
83+
Check Status: OK
84+
"""
85+
86+
When I try `wp db status --dbuser=no_such_user`
87+
Then the return code should be 1
88+
And STDERR should contain:
89+
"""
90+
Error: Could not query the database:
91+
"""
92+
93+
When I try `wp db status --dbpass=no_such_pass`
94+
Then the return code should be 1
95+
And STDERR should contain:
96+
"""
97+
Error: Could not query the database:
98+
"""
99+
100+
@require-sqlite
101+
Scenario: Display database status for a SQLite install
102+
Given a WP install
103+
104+
When I run `wp db status`
105+
Then STDOUT should match /^Database Name:\s+\S+$/m
106+
And STDOUT should match /^Tables:\s+[1-9]\d*$/m
107+
And STDOUT should match /^Total Size:\s+[\d.]+ [KM]?B$/m
108+
And STDOUT should contain:
109+
"""
110+
Prefix: wp_
111+
Engine: SQLite
112+
Charset: N/A
113+
Collation: N/A
114+
Check Status: N/A
115+
"""

‎src/DB_Command.php‎

Lines changed: 185 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1520,6 +1520,191 @@ public function prefix() {
15201520
WP_CLI::log( $wpdb->prefix );
15211521
}
15221522

1523+
/**
1524+
* Displays an overview of the database.
1525+
*
1526+
* Shows the database name, the number of tables and their total size, the
1527+
* table prefix, the storage engine, character set and collation of the
1528+
* tables, and whether `mysqlcheck` reports any problems. Engine, charset
1529+
* and collation read "Mixed" when the tables don't all share the same one.
1530+
*
1531+
* Unlike `wp db size` or `wp db prefix`, this doesn't load WordPress, so it
1532+
* also works before WordPress is installed.
1533+
*
1534+
* For SQLite databases, the engine is reported as SQLite, and charset,
1535+
* collation and check status are not available.
1536+
*
1537+
* ## OPTIONS
1538+
*
1539+
* [--dbuser=<value>]
1540+
* : Username to pass to mysql and mysqlcheck. Defaults to DB_USER.
1541+
*
1542+
* [--dbpass=<value>]
1543+
* : Password to pass to mysql and mysqlcheck. Defaults to DB_PASSWORD.
1544+
*
1545+
* [--skip-check]
1546+
* : Don't run `mysqlcheck`, which reads every table and can take a while on large databases.
1547+
*
1548+
* [--format=<format>]
1549+
* : Render output in a particular format. The JSON output lists the total size in bytes.
1550+
* ---
1551+
* default: list
1552+
* options:
1553+
* - list
1554+
* - json
1555+
* ---
1556+
*
1557+
* [--defaults]
1558+
* : Loads the environment's MySQL option files. Default behavior is to skip loading them to avoid failures due to misconfiguration.
1559+
*
1560+
* ## EXAMPLES
1561+
*
1562+
* $ wp db status
1563+
* Database Name: wordpress_dbase
1564+
* Tables: 12
1565+
* Total Size: 868.35 KB
1566+
* Prefix: wp_
1567+
* Engine: InnoDB
1568+
* Charset: utf8mb4
1569+
* Collation: utf8mb4_unicode_520_ci
1570+
* Check Status: OK
1571+
*
1572+
* $ wp db status --skip-check --format=json
1573+
* {"database":"wordpress_dbase","tables":12,"size":868352,"prefix":"wp_","engine":"InnoDB","charset":"utf8mb4","collation":"utf8mb4_unicode_520_ci","check":"Skipped"}
1574+
*/
1575+
public function status( $_, $assoc_args ) {
1576+
global $table_prefix;
1577+
1578+
$format = Utils\get_flag_value( $assoc_args, 'format', 'list' );
1579+
$skip_check = Utils\get_flag_value( $assoc_args, 'skip-check', false );
1580+
1581+
$status = [
1582+
'database' => DB_NAME,
1583+
'tables' => 0,
1584+
'size' => 0,
1585+
'prefix' => isset( $table_prefix ) && is_string( $table_prefix ) ? $table_prefix : '',
1586+
'engine' => 'N/A',
1587+
'charset' => 'N/A',
1588+
'collation' => 'N/A',
1589+
'check' => $skip_check ? 'Skipped' : 'N/A',
1590+
];
1591+
1592+
$this->maybe_load_sqlite_dropin();
1593+
1594+
if ( $this->is_sqlite() ) {
1595+
global $wpdb;
1596+
1597+
$db_path = $this->get_sqlite_db_path();
1598+
$status['database'] = $db_path ? basename( $db_path ) : '';
1599+
$status['size'] = $this->sqlite_size();
1600+
$status['engine'] = 'SQLite';
1601+
1602+
if ( isset( $wpdb ) && $wpdb instanceof \WP_SQLite_DB ) {
1603+
$status['tables'] = count( $wpdb->get_col( 'SHOW TABLES' ) );
1604+
}
1605+
} else {
1606+
$defaults_flag = $this->get_defaults_flag_string( $assoc_args );
1607+
$mysql_args = self::get_dbuser_dbpass_args( $assoc_args );
1608+
1609+
$query = 'SELECT COUNT(*), COALESCE(SUM(DATA_LENGTH + INDEX_LENGTH), 0), '
1610+
. 'COUNT(DISTINCT ENGINE), MIN(ENGINE), '
1611+
. "COUNT(DISTINCT SUBSTRING_INDEX(TABLE_COLLATION, '_', 1)), MIN(SUBSTRING_INDEX(TABLE_COLLATION, '_', 1)), "
1612+
. 'COUNT(DISTINCT TABLE_COLLATION), MIN(TABLE_COLLATION) '
1613+
. "FROM information_schema.TABLES WHERE TABLE_SCHEMA = DATABASE() AND TABLE_TYPE = 'BASE TABLE'";
1614+
1615+
list( $stdout, $stderr, $exit_code ) = self::run(
1616+
sprintf(
1617+
'%s%s --no-auto-rehash --batch --skip-column-names',
1618+
Utils\get_mysql_binary_path(),
1619+
$defaults_flag
1620+
),
1621+
array_merge(
1622+
$mysql_args,
1623+
[
1624+
'database' => DB_NAME,
1625+
'execute' => $query,
1626+
]
1627+
),
1628+
false
1629+
);
1630+
1631+
if ( $exit_code ) {
1632+
WP_CLI::error( 'Could not query the database: ' . trim( $stderr ) );
1633+
}
1634+
1635+
$row = array_pad( explode( "\t", trim( $stdout ) ), 8, 'NULL' );
1636+
1637+
$status['tables'] = (int) $row[0];
1638+
$status['size'] = (int) $row[1];
1639+
1640+
$columns = [
1641+
'engine' => 2,
1642+
'charset' => 4,
1643+
'collation' => 6,
1644+
];
1645+
foreach ( $columns as $key => $index ) {
1646+
if ( (int) $row[ $index ] > 1 ) {
1647+
$status[ $key ] = 'Mixed';
1648+
} elseif ( '' !== $row[ $index + 1 ] && 'NULL' !== $row[ $index + 1 ] ) {
1649+
$status[ $key ] = $row[ $index + 1 ];
1650+
}
1651+
}
1652+
1653+
$check_command = Utils\get_sql_check_command();
1654+
if ( ! $skip_check && '' !== $check_command && $status['tables'] > 0 ) {
1655+
list( $stdout, , $exit_code ) = self::run(
1656+
Utils\esc_cmd( sprintf( '%s%s %s', $check_command, $defaults_flag, '%s' ), DB_NAME ),
1657+
array_merge(
1658+
$mysql_args,
1659+
[
1660+
'check' => true,
1661+
'silent' => true,
1662+
// A read-only status check must not repair tables, even if an option file enables auto-repair.
1663+
'skip-auto-repair' => true,
1664+
]
1665+
),
1666+
false
1667+
);
1668+
1669+
$status['check'] = ( 0 === $exit_code && ! preg_match( '/^error\s*:/mi', $stdout ) ) ? 'OK' : 'Error';
1670+
}
1671+
}
1672+
1673+
if ( 'json' === $format ) {
1674+
WP_CLI::line( (string) json_encode( $status ) );
1675+
return;
1676+
}
1677+
1678+
$status['size'] = self::format_size_si( $status['size'] );
1679+
1680+
$labels = [
1681+
'database' => 'Database Name',
1682+
'tables' => 'Tables',
1683+
'size' => 'Total Size',
1684+
'prefix' => 'Prefix',
1685+
'engine' => 'Engine',
1686+
'charset' => 'Charset',
1687+
'collation' => 'Collation',
1688+
'check' => 'Check Status',
1689+
];
1690+
foreach ( $labels as $key => $label ) {
1691+
WP_CLI::line( sprintf( '%-18s %s', $label . ':', $status[ $key ] ) );
1692+
}
1693+
}
1694+
1695+
/**
1696+
* Formats a number of bytes with SI units, like `wp db size --human-readable`.
1697+
*
1698+
* @param int $bytes Number of bytes.
1699+
* @return string
1700+
*/
1701+
private static function format_size_si( $bytes ) {
1702+
$sizes = [ 'B', 'KB', 'MB', 'GB', 'TB' ];
1703+
$key = $bytes > 0 ? (int) min( floor( log( $bytes, 1000 ) ), count( $sizes ) - 1 ) : 0;
1704+
1705+
return round( $bytes / pow( 1000, $key ), 2 ) . ' ' . $sizes[ $key ];
1706+
}
1707+
15231708
/**
15241709
* Finds a string in the database.
15251710
*

0 commit comments

Comments
 (0)