Skip to content

Commit 91e0dc7

Browse files
committed
Fix incorrect column names for string literals without alias
1 parent da8dcc7 commit 91e0dc7

3 files changed

Lines changed: 18 additions & 2 deletions

File tree

tests/WP_SQLite_Driver_Tests.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3716,7 +3716,7 @@ public function testHavingWithoutGroupBy() {
37163716
$this->assertEquals(
37173717
array(
37183718
(object) array(
3719-
"'T'" => 'T',
3719+
'T' => 'T',
37203720
),
37213721
),
37223722
$result

tests/WP_SQLite_Driver_Translation_Tests.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1680,7 +1680,7 @@ public function testSelectOrderByAmbiguousColumnResolution(): void {
16801680
// Test a complex query with CTEs.
16811681
$this->assertQuery(
16821682
'WITH'
1683-
. " `cte1` ( `name` ) AS ( SELECT 'a' UNION ALL SELECT 'b' ) ,"
1683+
. " `cte1` ( `name` ) AS ( SELECT 'a' AS `a` UNION ALL SELECT 'b' AS `b` ) ,"
16841684
. ' `cte2` ( `name` ) AS ( SELECT `t2`.`name` FROM `t2` JOIN `t1` ON `t1`.`id` = `t2`.`id` ORDER BY `t2`.`name` )'
16851685
. ' SELECT `t1`.`name` , ( SELECT `name` FROM `cte1` WHERE `id` = 1 ) AS `cte1_name` , ( SELECT `name` FROM `cte2` WHERE `id` = 2 ) AS `cte2_name`'
16861686
. ' FROM `t1`'

wp-includes/sqlite-ast/class-wp-pdo-mysql-on-sqlite.php

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4238,6 +4238,22 @@ public function translate_select_item( WP_Parser_Node $node ): string {
42384238
return $item;
42394239
}
42404240

4241+
/*
4242+
* When the select item is a text string literal, we need to use an alias
4243+
* to ensure that the column name is the same as it would be in MySQL.
4244+
* In MySQL, the column name is the original text string literal value
4245+
* without quotes and escaping, but in SQLite, it is the quoted value.
4246+
*
4247+
* For example, for "SELECT 'abc'", the resulting column name is "abc"
4248+
* in MySQL, but would be "'abc'" in SQLite if an alias was not used.
4249+
*/
4250+
$text_string_literal = $node->get_first_descendant_node( 'textStringLiteral' );
4251+
$is_text_string_literal = $text_string_literal && $item === $this->translate( $text_string_literal );
4252+
if ( $is_text_string_literal ) {
4253+
$alias = $text_string_literal->get_first_child_token()->get_value();
4254+
return sprintf( '%s AS %s', $item, $this->quote_sqlite_identifier( $alias ) );
4255+
}
4256+
42414257
/*
42424258
* When the select item has no explicit alias, we need to ensure that the
42434259
* returned column name is equivalent to what MySQL infers from the input.

0 commit comments

Comments
 (0)