cap not applied * SELECT "LIMIT" AS a FROM wp_posts -> cap not applied * * This anchors to the end of the statement, past an optional trailing semicolon and whitespace, * and accepts the `LIMIT n` and `LIMIT off, n` forms. A `LIMIT` buried mid-statement no longer * suppresses the cap. * * Appending is only an optimisation either way: the caller enforces the cap by slicing the rows * it got back, so a wrong answer here costs a wider fetch, never a missing cap. * * @since 0.0.44 * @param string $sql Raw statement. * @return bool */ public static function has_trailing_limit( string $sql ): bool { $stripped = rtrim( self::strip_comments( $sql ) ); return 1 === preg_match( '/\bLIMIT\s+\d+(\s*,\s*\d+)?\s*;?\s*$/i', $stripped ); } /** * Append a `LIMIT` when the statement has none and the verb accepts one. * * `SHOW`, `DESCRIBE` and `EXPLAIN` either reject `LIMIT` or ignore it, so they are left alone. * * @since 0.0.44 * @param string $sql Raw statement. * @param int $limit Row ceiling; zero or less appends nothing. * @return string */ public static function with_limit( string $sql, int $limit ): string { if ( $limit < 1 || 'SELECT' !== self::first_verb( $sql ) || self::has_trailing_limit( $sql ) ) { return $sql; } return rtrim( $sql, "; \t\n\r" ) . ' LIMIT ' . $limit; } }