Skip to content

Commit

Permalink
Merge pull request #2186 from taozhi8833998/feat-export-columnstosql
Browse files Browse the repository at this point in the history
feat: export columns method
  • Loading branch information
taozhi8833998 authored Oct 26, 2024
2 parents 1e35e11 + 7027ff4 commit a823aec
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 1 deletion.
1 change: 1 addition & 0 deletions src/column.js
Original file line number Diff line number Diff line change
Expand Up @@ -213,4 +213,5 @@ export {
columnOrderToSQL,
columnReferenceDefinitionToSQL,
fullTextSearchToSQL,
getDual,
}
8 changes: 8 additions & 0 deletions src/parser.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { columnToSQL, getDual } from './column'
import { exprToSQL } from './expr'
import parsers from './parser.all'
import astToSQL from './sql'
Expand All @@ -19,6 +20,13 @@ class Parser {
return exprToSQL(expr)
}

columnsToSQL(columns, tables, opt = DEFAULT_OPT) {
setParserOpt(opt)
if (!columns || columns === '*') return []
const isDual = getDual(tables)
return columns.map(col => columnToSQL(col, isDual))
}

parse(sql, opt = DEFAULT_OPT) {
const { database = (PARSER_NAME || 'mysql') } = opt
setParserOpt(opt)
Expand Down
24 changes: 23 additions & 1 deletion test/ast.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -1268,8 +1268,30 @@ describe('AST', () => {
const sql = parser.exprToSQL(ast.where);
expect(sql).to.equal('`id` = 1');
});

it('should be able to get columns from ast', () => {
const ast = parser.astify(`SELECT
campaign.id,
ad_group.id,
'http://' + ad_group_ad.ad.final_urls + '?tm=123' as url,
ad_group_ad.resource_name,
ad_group_ad.policy_summary.policy_topic_entries as policy_topic_entries,
ad_group_ad.policy_summary.policy_topic_entries:topic as topic,
ad_group_ad.policy_summary.policy_topic_entries:topic + '!' as topic2
FROM ad_group_ad`);
const columns = parser.columnsToSQL(ast.columns, ast.from);
expect(columns).to.be.eql([
'`campaign`.`id`',
'`ad_group`.`id`',
"'http://' + `ad_group_ad`.`ad`.`final_urls` + '?tm=123' AS `url`",
'`ad_group_ad`.`resource_name`',
'`ad_group_ad`.`policy_summary`.`policy_topic_entries` AS `policy_topic_entries`',
'`ad_group_ad`.`policy_summary`.`policy_topic_entries:topic` AS `topic`',
"`ad_group_ad`.`policy_summary`.`policy_topic_entries:topic` + '!' AS `topic2`"
])
});
})

describe('jsonb operator ast order', () => {
it('should parse jsonb operator ast order correct', () => {
const sql = `SELECT company.name
Expand Down

0 comments on commit a823aec

Please sign in to comment.