Skip to content

fix params in CTE #79

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 13 commits into from
Oct 2, 2024
8 changes: 8 additions & 0 deletions src/parser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -164,12 +164,14 @@ export function parse(
statementEnd: boolean;
parens: 0;
state: State;
params: Array<string>;
} = {
isCte: false,
asSeen: false,
statementEnd: false,
parens: 0,
state: topLevelState,
params: [],
};

const ignoreOutsideBlankTokens = ['whitespace', 'comment-inline', 'comment-block', 'semicolon'];
Expand Down Expand Up @@ -251,11 +253,17 @@ export function parse(
if (cteState.isCte) {
statementParser.getStatement().start = cteState.state.start;
statementParser.getStatement().isCte = true;
statementParser.getStatement().parameters.push(...cteState.params);
cteState.params = [];
cteState.isCte = false;
cteState.asSeen = false;
cteState.statementEnd = false;
}
}

if (cteState.isCte && token.type === 'parameter') {
cteState.params.push(token.value);
}
} else {
statementParser.addToken(token, nextToken);
topLevelStatement.tokens.push(token);
Expand Down
21 changes: 21 additions & 0 deletions test/index.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,27 @@ describe('identify', () => {
]);
});

it('params should be recognized in a CTE', () => {
const query = `
WITH foo AS (
SELECT * FROM bar where user_id = $1::bigint
)
SELECT * FROM foo
`;

expect(identify(query.trim(), { dialect: 'psql' })).to.eql([
{
start: 0,
end: 97,
text: query.trim(),
type: 'SELECT',
executionType: 'LISTING',
parameters: ['$1'],
tables: [],
},
]);
});

it('should identify tables in simple for basic cases', () => {
expect(
identify('SELECT * FROM foo JOIN bar ON foo.id = bar.id', { identifyTables: true }),
Expand Down