Skip to content

Commit

Permalink
Allow usage of column alias in WHERE expression
Browse files Browse the repository at this point in the history
  • Loading branch information
wsporto committed Nov 27, 2024
1 parent ea21578 commit 02a2f09
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 13 deletions.
26 changes: 13 additions & 13 deletions src/sqlite-query-analyzer/traverse.ts
Original file line number Diff line number Diff line change
Expand Up @@ -292,32 +292,32 @@ function traverse_select_core(
}
});

const newColumns = listType.map((selectField) => {
const col: ColumnDef = {
columnName: selectField.name,
table: selectField.table,
columnType: selectField.type,
notNull: selectField.notNull,
columnKey: '',
hidden: selectField.hidden || 0
};
return col;
});
const whereExpr = select_core._whereExpr;
if (whereExpr) {
traverse_expr(whereExpr, {
...traverseContext,
fromColumns: fromColumns
fromColumns: fromColumns.concat(newColumns)
});
if (!traverseContext.subQuery) {
const { relations, params } = extractRelationsAndParams(whereExpr, fromColumns, traverseContext.parameters);
const { relations, params } = extractRelationsAndParams(whereExpr, fromColumns.concat(newColumns), traverseContext.parameters);
traverseContext.dynamicSqlInfo2.where.push({
fragment: `AND ${extractOriginalSql(whereExpr)}`,
dependOnRelations: [...new Set(relations)], //remove duplicated
parameters: params
});
}
}
const newColumns = listType.map((selectField) => {
const col: ColumnDef = {
columnName: selectField.name,
table: selectField.table,
columnType: selectField.type,
notNull: selectField.notNull,
columnKey: '',
hidden: selectField.hidden || 0
};
return col;
});
const groupByExprList = select_core._groupByExpr || [];
groupByExprList.forEach((groupByExpr) => {
traverse_expr(groupByExpr, {
Expand Down
25 changes: 25 additions & 0 deletions tests/sqlite/sqlite-parse-select-single-table.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1890,4 +1890,29 @@ describe('sqlite-Test simple select statements', () => {
}
assert.deepStrictEqual(actual.right, expected);
});

it('SELECT 1 + 1 as col_alias WHERE col_alias > 0', async () => {
const sql = 'SELECT 1 + 1 as col_alias WHERE col_alias > 0';

const actual = await parseSql(sql, sqliteDbSchema);
const expected: SchemaDef = {
sql,
queryType: 'Select',
multipleRowsResult: false,
columns: [
{
columnName: 'col_alias',
type: 'INTEGER',
notNull: true,
table: ''
}
],
parameters: []
};

if (isLeft(actual)) {
assert.fail(`Shouldn't return an error: ${actual.left.description}`);
}
assert.deepStrictEqual(actual.right, expected);
});
});

0 comments on commit 02a2f09

Please sign in to comment.