Skip to content

Code Quality: Type wpdb query results from the columns selected - #16260

Draft
westonruter wants to merge 21 commits into
WordPress:trunkfrom
westonruter:add/phpstan-wpdb-query-types
Draft

westonruter wants to merge 21 commits into
WordPress:trunkfrom
westonruter:add/phpstan-wpdb-query-types

Conversation

@westonruter

@westonruter westonruter commented Nov 26, 2026 •

Copy link
Copy Markdown
Member

This PR was developed from the following prompt to Claude Code:

I want you to work on a PHPStan extension for $wpdb query methods (like get_var, get_row, get_results, etc) which eliminates the need for hard-coding types in @var tags like this. For core's built-in fields, we should be able to look at what fields are being SELECT'ed to know what the types are.

The "like this" referred to the following selection in WP_REST_Comments_Controller:

$query = "SELECT r.comment_parent, r.comment_content, COUNT(*) AS reaction_count $from $where GROUP BY r.comment_parent, r.comment_content";
/** @var list<object{ comment_parent: decimal-int-string, comment_content: string, reaction_count: decimal-int-string }&stdClass>|null $counts */
$counts = $wpdb->get_results( $query );

This adds a PHPStan extension that types the results of $wpdb->get_var(), get_row(), get_col(), and get_results() from the columns their query selects, so that they no longer need an inline @var tag. For example, in WP_REST_Comments_Controller the reactions query had to be annotated by hand as list<object{ comment_parent: decimal-int-string, ... }&stdClass>|null, and is now inferred as exactly that, even though the query is built up from $from and $where with .= and $wpdb->prepare().

The extension is made of four parts in tests/phpstan/:

  • WpdbQueryVisitor rebuilds the query text from the syntax tree before analysis, since a query's type is almost never a constant string once it interpolates $wpdb->posts. It joins strings, interpolation, and concatenation, unwraps $wpdb->prepare() (each placeholder becoming one unknown value), and follows a variable back through the = and .= statements before the call. It gives up where a write may not be straight-line, such as in a loop, a branch that does more than append, an if condition, or the call's own statement.
  • WpdbSchema reads the column types from the CREATE TABLE statements in wp_get_db_schema(), so a new column needs no change here. Since mysqli returns every value as a string or null, an integer column is a decimal-int-string, a DATETIME column a non-falsy-string, and a column without NOT NULL is nullable. The multisite-only users.spam and users.deleted columns are optional.
  • WpdbSelectParser reads the select list and the FROM clause: * and alias.*, table aliases, joins (with the outer side of a LEFT or RIGHT JOIN made nullable), names and quoted strings as aliases, COUNT(), SUM(), AVG(), MIN(), MAX(), and literals. Anything else is string|null, and a column whose name includes unknown text has an unknown name.
  • WpdbQueryDynamicMethodReturnTypeExtension refines the declared conditional return type rather than replacing it, so the cases in which a method returns null or an empty array stay as declared. It turns each stdClass row into an object shape, ARRAY_A and ARRAY_N rows into array shapes, and OBJECT_K keys into the type of the row's first value. Positional access (ARRAY_N and the column index of get_var() and get_col()) follows array_values( get_object_vars( $row ) ), so repeated column names collapse, and rows with the multisite columns are typed both with and without them.

Wherever the columns cannot be determined, for example for a table that is not a core table, a select list holding a variable, or an $output that is not one constant, the declared return type is used as before. The README documents the extension, including two limits: the types assume wpdb itself rather than a db.php drop-in, and after a change to schema.php the result cache must be cleared, since PHPStan does not know that analyzed files depend on it.

Six inline @var tags made redundant by the extension are removed, in taxonomy.php, ms-functions.php, post.php, class-wp-comment.php, and class-wp-rest-comments-controller.php. The one in WP_Term_Query::get_terms() is kept, since its query is in $this->request, whose text is unknown, and the tag deliberately excludes null.

The sharper types change the argument.type baseline: 20 existing messages become more precise (mostly string|null to string, since get_col() of a NOT NULL column cannot hold null), and 19 more errors surface where numeric strings from query results are passed to int parameters, such as wp_delete_post( $id ) in wp_delete_user(). Those are left for follow-up fixes. No other baseline changes.

The extension was reviewed twice with dumpType() probes, and the wrong types found (outer-join nullability, quoted aliases, placeholders, duplicate column names, multisite column positions, missed writes, arrow function parameters, alias heuristics, OBJECT_K keys, table names extended by more text, and number literals) are each fixed in their own commit.

Trac ticket: https://core.trac.wordpress.org/ticket/66739

Use of AI Tools

AI assistance: Yes
Tool(s): Claude Code
Model(s): Claude Opus 5.5 (medium effort), with a review by Claude Fable 5.2
Used for: Implementing the extension, removing the redundant @var tags, regenerating the baseline, reviewing the extension with PHPStan probes, fixing the review findings, and writing the documentation and this description.


This Pull Request is for code review only. Please keep all other discussion in the Trac ticket. Do not merge this Pull Request. See GitHub Pull Requests for Code Review in the Core Handbook for more details.

westonruter and others added 21 commits November 25, 2026 14:48
Add a PHPStan extension that types the results of `wpdb::get_var()`,
`get_row()`, `get_col()` and `get_results()` from the columns their query
selects, so that they no longer need an inline `@var` tag.

`WpdbQueryVisitor` reconstructs the query text from the syntax tree,
following the variables it is built up in. `WpdbSchema` reads the column
types of the core tables from the `CREATE TABLE` statements in
`wp_get_db_schema()`. `WpdbSelectParser` reads the select list and the
tables in the `FROM` clause. The extension then refines the declared
return type: each `stdClass` row becomes an object shape, each row array
an array shape, and `OBJECT_K` results are keyed by the first column.

The sharper types expose more cases of numeric strings from query results
being passed to `int` parameters, so the `argument.type` baseline is
regenerated.

Co-Authored-By: Claude Opus 5.5 (medium effort) <noreply@anthropic.com>
Claude-Code-Session-Id: d0b08a9d-fb94-402f-be41-5a31f807320c
The PHPStan extension for `wpdb` query methods now derives these types from
the columns each query selects, as precisely or more so than the tags did.
For example, the rows of `SELECT *` queries now have `decimal-int-string`
for integer columns and `non-falsy-string` for datetime columns.

The `@var` tag in `WP_Term_Query::get_terms()` stays, since its query is in
`$this->request`, whose text is not known, and since the tag deliberately
excludes null.

Co-Authored-By: Claude Opus 5.5 (medium effort) <noreply@anthropic.com>
Claude-Code-Session-Id: d0b08a9d-fb94-402f-be41-5a31f807320c
A table on the outer side of a `LEFT JOIN` or `RIGHT JOIN` has no row to
match for some rows of the result, so each of its columns is null there.
`WpdbSelectParser` now records which tables these are, and adds null to the
types of their columns, including those a `*` or `alias.*` expands to.

`LEFT` and `RIGHT` are also functions, so they now only start a join when
`JOIN` or `OUTER` follows, and not in an `ON` condition.

Co-Authored-By: Claude Opus 5.5 (medium effort) <noreply@anthropic.com>
Claude-Code-Session-Id: d0b08a9d-fb94-402f-be41-5a31f807320c
MySQL accepts a quoted string as a column alias, as in
`SELECT TABLE_ROWS AS 'rows'` in `WP_Site_Health`, but `WpdbSelectParser`
only took a name as one, and so named such a column by the whole text of
the expression and its alias. It now reads a single- or double-quoted
alias, with or without `AS`, and removes its quotes. Without `AS`, a quoted
string following a string literal is not an alias, since MySQL joins the
two strings.

Co-Authored-By: Claude Opus 5.5 (medium effort) <noreply@anthropic.com>
Claude-Code-Session-Id: d0b08a9d-fb94-402f-be41-5a31f807320c
…b query types.

`WpdbQueryVisitor` replaced `$wpdb->prepare()` by its format, placeholders
and all, so that a placeholder in the select list read as a column: for
`SELECT %i FROM ...`, a column named `%i`, rather than whichever column the
argument names.

Each placeholder now becomes `{value}`, a single value whose text is not
known, and each `%%` becomes `%`. `WpdbSelectParser` types such a value as
`string|null`, and leaves its name unknown unless it has an alias. Unlike
`{?}`, it is one column, so the columns after it stay known.

Co-Authored-By: Claude Opus 5.5 (medium effort) <noreply@anthropic.com>
Claude-Code-Session-Id: d0b08a9d-fb94-402f-be41-5a31f807320c
…mns.

The `spam` and `deleted` columns of the users table only exist on
multisite, so on a single site each column after them in a row from
`ARRAY_N` is two positions earlier. The extension typed such a row with
those two columns as optional offsets, but each column after them at a
fixed offset, which is only right on multisite.

The values of a row are now typed in two variants, one with the multisite
columns and one without, and an `ARRAY_N` row is the union of the two. The
column index of `get_var()` and `get_col()` is typed from both variants
too, which replaces stopping at the first such column, and so types the
columns after it as well.

Co-Authored-By: Claude Opus 5.5 (medium effort) <noreply@anthropic.com>
Claude-Code-Session-Id: d0b08a9d-fb94-402f-be41-5a31f807320c
…types.

`wpdb` makes an `ARRAY_N` row, and finds the value at the column index of
`get_var()` and `get_col()`, from `array_values( get_object_vars( $row ) )`.
The row object has one property for each column name, so a column with the
name of an earlier one, like `term_id` in `SELECT t.*, tt.*`, replaces the
earlier one's value in its position, and is not a value of its own. The
extension counted each column in the select list instead, so typed such a
row with too many values, and the values after a repeated name at the wrong
index.

The values of a row now have one per column name, with the type of the last
column of that name, at the position of the first.

Co-Authored-By: Claude Opus 5.5 (medium effort) <noreply@anthropic.com>
Claude-Code-Session-Id: d0b08a9d-fb94-402f-be41-5a31f807320c
…b queries.

In following a variable back to its value, `WpdbQueryVisitor` missed two
kinds of write in the statements the query method call is in, and so typed
the result from a value the variable no longer had:

* An `if` the call is in was exempt from the check for writes, as only the
  branch the call is in has run, but its conditions have run too, as in
  `if ( $query = get_option( 'query' ) )`.
* A loop whose condition the call is in, as in `while ( $wpdb->get_var( $sql ) )`,
  was not checked at all, though its body may have run before the
  condition, in an earlier iteration, or for a `do` loop, the first one.

The conditions of an enclosing `if`, and the whole of a loop the call is
in directly, are now checked for writes as well.

Co-Authored-By: Claude Opus 5.5 (medium effort) <noreply@anthropic.com>
Claude-Code-Session-Id: d0b08a9d-fb94-402f-be41-5a31f807320c
An arrow function has no statements of its own, so `WpdbQueryVisitor`
follows the variables in it to the statements outside it, as it should for
the variables the arrow function captures. But its parameters shadow the
variables outside it of the same name, so for
`fn( $sql ) => $wpdb->get_var( $sql )` the visitor typed the result from an
assignment to `$sql` outside, rather than from the argument.

The parameters of the arrow functions a call is in are now unknown. The
variables outside are still followed for the rest.

Co-Authored-By: Claude Opus 5.5 (medium effort) <noreply@anthropic.com>
Claude-Code-Session-Id: d0b08a9d-fb94-402f-be41-5a31f807320c
`WpdbSelectParser` took the name at the end of a select expression as its
alias whenever a name, literal, or `)` came before it. But a keyword ends
some expressions, which so read as their alias:

* the unit of an interval, as in `post_date + INTERVAL 1 DAY`, and
* the operand of a keyword like `COLLATE` or `BINARY`, as in
  `post_title COLLATE utf8mb4_bin`, or as in `BINARY post_name`, which then
  also read as a reference to the `post_name` column.

A name following such a keyword, and the unit of an interval outside any
parentheses, is no longer taken as an alias, so the expression is named by
its text.

A string literal without an alias was also named by its text, quotes and
all, but MySQL names it by its value, or by the first of adjacent strings it
joins, as it now is here.

Co-Authored-By: Claude Opus 5.5 (medium effort) <noreply@anthropic.com>
Claude-Code-Session-Id: d0b08a9d-fb94-402f-be41-5a31f807320c
…own line.

Two statements shared a line, joined by a run of tabs.

Co-Authored-By: Claude Opus 5.5 (medium effort) <noreply@anthropic.com>
Claude-Code-Session-Id: d0b08a9d-fb94-402f-be41-5a31f807320c
Co-Authored-By: Claude Opus 5.5 (medium effort) <noreply@anthropic.com>
Claude-Code-Session-Id: d0b08a9d-fb94-402f-be41-5a31f807320c
Describe in the README how the extension now types outer-joined columns,
`ARRAY_N` rows with the multisite columns, quoted aliases, string literals,
repeated column names, and `prepare()` placeholders, and when it no longer
follows a variable: past an `if` condition assigning it, and for an arrow
function's parameter.

Co-Authored-By: Claude Opus 5.5 (medium effort) <noreply@anthropic.com>
Claude-Code-Session-Id: d0b08a9d-fb94-402f-be41-5a31f807320c
…utput`.

When the `$output` argument of `get_row()` or `get_results()` may be more
than one value, as for `'ARRAY_A'|'ARRAY_N'` or any `string`, the declared
conditional return type joins the row arrays of the two into one
`array<mixed>`. The extension then refined that as an `ARRAY_A` row alone,
so an `ARRAY_N` row, which the call may well return, was left out of the
type.

The result is now left as declared unless `$output` is absent or one
constant value.

Co-Authored-By: Claude Opus 5.5 (medium effort) <noreply@anthropic.com>
Claude-Code-Session-Id: d0b08a9d-fb94-402f-be41-5a31f807320c
… query types.

`WpdbSelectParser` left a column's name unknown when it was the text of an
expression with a placeholder in it, but not otherwise. So a placeholder
inside a backtick-quoted name or a string, as in ``SELECT `$column` `` or
`SELECT '%s'`, or a `wpdb` property other than a table, as in
`SELECT $wpdb->blogid`, became a column named `{?}`, `{value}`, or
`{wpdb:blogid}`. The real column has another name, and two such columns
shared the one name, so were taken as a single value of the row.

Any column name holding a placeholder is now unknown, whether it comes from
an alias, a column reference, a string, or the text of an expression.

Co-Authored-By: Claude Opus 5.5 (medium effort) <noreply@anthropic.com>
Claude-Code-Session-Id: d0b08a9d-fb94-402f-be41-5a31f807320c
`WpdbQueryVisitor` did not check the statement a query method call is in
for writes to the query's variable, unless it was a loop or an `if`, so it
missed a write made earlier in the same statement, as in
`( $sql = get_option( 'query' ) ) && $wpdb->get_var( $sql )`, and typed the
result from the value assigned before it.

A write to the variable anywhere in that statement now makes its value
unknown, since the visitor does not follow the order in which the parts of
a statement run. An assignment to the variable of a value holding the call,
as in `$sql = $wpdb->get_var( $sql )`, is the exception, as its write is
made after the call.

Co-Authored-By: Claude Opus 5.5 (medium effort) <noreply@anthropic.com>
Claude-Code-Session-Id: d0b08a9d-fb94-402f-be41-5a31f807320c
`wpdb::get_results()` keys `OBJECT_K` rows by the first value of each row
object, not by its first select column. The two differ when a later column
has the first column's name, as in `SELECT ID, post_title AS ID`, whose
value then replaces the first, and so whose type the keys have.

The key is now typed from the first value of the row, as the positional
types are, in each variant of the row. This also types the keys when the
first column is one of the multisite columns of the users table, which
were left as declared.

Co-Authored-By: Claude Opus 5.5 (medium effort) <noreply@anthropic.com>
Claude-Code-Session-Id: d0b08a9d-fb94-402f-be41-5a31f807320c
…ore table.

`WpdbSelectParser` split a table placeholder from the name characters next
to it, so `{$wpdb->posts}_archive` read as the posts table with the alias
`_archive`, and its columns were typed from the posts schema, though it is
another table.

A table placeholder with name characters on either side is now one token
with them, which is not a core table.

Co-Authored-By: Claude Opus 5.5 (medium effort) <noreply@anthropic.com>
Claude-Code-Session-Id: d0b08a9d-fb94-402f-be41-5a31f807320c
For a column index which may be any integer, the extension typed the values
of `get_col()` from the types of the columns alone. But an index past the
last column gives a value of null in every row, as `get_var()` does for
it, so null is now included in their type too.

Co-Authored-By: Claude Opus 5.5 (medium effort) <noreply@anthropic.com>
Claude-Code-Session-Id: d0b08a9d-fb94-402f-be41-5a31f807320c
…query types.

`WpdbSelectParser` read the digits at the start of a number as the number,
and the rest as an alias, so `SELECT 0x41` was typed as the constant `'0'`
in a column named `x41`, and `SELECT 1e3` as `'1'` in a column named `e3`.
And it typed any run of digits as the same constant string, though MySQL
gives back `007` as `'7'`. Likewise a string with a prefix, like `x'41'` or
`_utf8mb4'text'`, read as a column reference with the string as its alias.

Hexadecimal numbers, decimal numbers with an exponent, and strings with a
prefix are now each one token. Only an integer written as MySQL gives it
back is typed as a constant string, and the name of a prefixed string,
which this does not follow, is left unknown.

Co-Authored-By: Claude Opus 5.5 (medium effort) <noreply@anthropic.com>
Claude-Code-Session-Id: d0b08a9d-fb94-402f-be41-5a31f807320c
@github-actions

Copy link
Copy Markdown

Test using WordPress Playground

The changes in this pull request can previewed and tested using a WordPress Playground instance.

WordPress Playground is an experimental project that creates a full WordPress instance entirely within the browser.

Some things to be aware of

  • All changes will be lost when closing a tab with a Playground instance.
  • All changes will be lost when refreshing the page.
  • A fresh instance is created each time the link below is clicked.
  • Every time this pull request is updated, a new ZIP file containing all changes is created. If changes are not reflected in the Playground instance,
    it's possible that the most recent build failed, or has not completed. Check the list of workflow runs to be sure.

For more details about these limitations and more, check out the Limitations page in the WordPress Playground documentation.

Test this pull request with WordPress Playground.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant