WordPress-Coding-Standards icon indicating copy to clipboard operation
WordPress-Coding-Standards copied to clipboard

SQL queries should not use hardcoded table names

Open increddibelly opened this issue 4 years ago • 2 comments

Is your feature request related to a problem?

Using hardcoded table names in SQL queries causes problems for multisite installations, or users who have changed the default table prefix.

Describe the solution you'd like

Queries that do not use the $wpdb->prefix to determine table names, should trigger a CS error.

$wpdb->prepare( "SELECT * FROM wordpress.wp_posts WHERE id = %d", $id);

Additional context (optional)

see also (loosely related) https://github.com/WordPress/WordPress-Coding-Standards/issues/1589

increddibelly avatar Sep 13 '21 14:09 increddibelly

Marked as valid feature request.

Some notes:

  1. The sniff should look for FROM, but also for LEFT JOIN and other variants of that. Needs some investigation in the MySQL manual to find every keyword the sniff should look for. The sniff will probably need to strictly look for the uppercase keywords used in text strings, but that will be prone to false positives.
  2. I think the sniff should verify that table names are not 100% hard-coded, but that the first part is always dynamic. I know there are quite some plugins which abstract things out a bit more, which could result in $this->wpdb->prefix or $this->get_table_prefix(). The sniff should probably differentiate in error code for these, like TableNameHardCoded and TableNamePrefixNotUsingWpdb. Plugins/themes using extra abstractions could then ignore the second error code from their custom ruleset.
  3. For the "standard" WP table names, the sniff should probably trigger an error if these are not 100% dynamic, i.e. $wpdb->posts, not $wpdb->prefix . 'posts'
  4. This sniff would need lots and lots of tests as queries can be build up in so many different ways (concatenation, prepared queries, interpolation etc) and the sniff would need to try and detect this issue in as many situations as possible with a minimum of false positives.

jrfnl avatar Sep 13 '21 14:09 jrfnl

+1 for this request, we just faced a bug with hardcoded prefixes and this would have helped.

Luc45 avatar Dec 20 '22 15:12 Luc45