Repository navigation
Code Quality: Type wpdb query results from the columns selected - #16260
Draft
westonruter wants to merge 21 commits into
Draft
westonruter wants to merge 21 commits into
westonruter wants to merge 21 commits into
Conversation
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
Test using WordPress PlaygroundThe 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
For more details about these limitations and more, check out the Limitations page in the WordPress Playground documentation. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
This PR was developed from the following prompt to Claude Code:
The "like this" referred to the following selection in
WP_REST_Comments_Controller:This adds a PHPStan extension that types the results of
$wpdb->get_var(),get_row(),get_col(), andget_results()from the columns their query selects, so that they no longer need an inline@vartag. For example, inWP_REST_Comments_Controllerthe reactions query had to be annotated by hand aslist<object{ comment_parent: decimal-int-string, ... }&stdClass>|null, and is now inferred as exactly that, even though the query is built up from$fromand$wherewith.=and$wpdb->prepare().The extension is made of four parts in
tests/phpstan/:WpdbQueryVisitorrebuilds 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, anifcondition, or the call's own statement.WpdbSchemareads the column types from theCREATE TABLEstatements inwp_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 adecimal-int-string, aDATETIMEcolumn anon-falsy-string, and a column withoutNOT NULLis nullable. The multisite-onlyusers.spamandusers.deletedcolumns are optional.WpdbSelectParserreads the select list and theFROMclause:*andalias.*, table aliases, joins (with the outer side of aLEFTorRIGHT JOINmade nullable), names and quoted strings as aliases,COUNT(),SUM(),AVG(),MIN(),MAX(), and literals. Anything else isstring|null, and a column whose name includes unknown text has an unknown name.WpdbQueryDynamicMethodReturnTypeExtensionrefines 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 eachstdClassrow into an object shape,ARRAY_AandARRAY_Nrows into array shapes, andOBJECT_Kkeys into the type of the row's first value. Positional access (ARRAY_Nand the column index ofget_var()andget_col()) followsarray_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
$outputthat is not one constant, the declared return type is used as before. The README documents the extension, including two limits: the types assumewpdbitself rather than adb.phpdrop-in, and after a change toschema.phpthe result cache must be cleared, since PHPStan does not know that analyzed files depend on it.Six inline
@vartags made redundant by the extension are removed, intaxonomy.php,ms-functions.php,post.php,class-wp-comment.php, andclass-wp-rest-comments-controller.php. The one inWP_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.typebaseline: 20 existing messages become more precise (mostlystring|nulltostring, sinceget_col()of aNOT NULLcolumn cannot hold null), and 19 more errors surface where numeric strings from query results are passed tointparameters, such aswp_delete_post( $id )inwp_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_Kkeys, 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
@vartags, 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.