Skip to content

Commit de10767

Browse files
committed
Fix incorrect column names for string literals without alias
1 parent b0ca303 commit de10767

File tree

3 files changed

+18
-2
lines changed

3 files changed

+18
-2
lines changed

tests/WP_SQLite_Driver_Tests.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3799,7 +3799,7 @@ public function testHavingWithoutGroupBy() {
37993799
$this->assertEquals(
38003800
array(
38013801
(object) array(
3802-
"'T'" => 'T',
3802+
'T' => 'T',
38033803
),
38043804
),
38053805
$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-sqlite-driver.php

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

4103+
/*
4104+
* When the select item is a text string literal, we need to use an alias
4105+
* to ensure that the column name is the same as it would be in MySQL.
4106+
* In MySQL, the column name is the original text string literal value
4107+
* without quotes and escaping, but in SQLite, it is the quoted value.
4108+
*
4109+
* For example, for "SELECT 'abc'", the resulting column name is "abc"
4110+
* in MySQL, but would be "'abc'" in SQLite if an alias was not used.
4111+
*/
4112+
$text_string_literal = $node->get_first_descendant_node( 'textStringLiteral' );
4113+
$is_text_string_literal = $text_string_literal && $item === $this->translate( $text_string_literal );
4114+
if ( $is_text_string_literal ) {
4115+
$alias = $text_string_literal->get_first_child_token()->get_value();
4116+
return sprintf( '%s AS %s', $item, $this->quote_sqlite_identifier( $alias ) );
4117+
}
4118+
41034119
/*
41044120
* When the select item has no explicit alias, we need to ensure that the
41054121
* returned column name is equivalent to what MySQL infers from the input.

0 commit comments

Comments
 (0)