Skip to content

Commit

Permalink
Merge PR #281: Fix BigQuery STRUCT formatting
Browse files Browse the repository at this point in the history
  • Loading branch information
nene authored Jul 5, 2022
2 parents e132c30 + 7e67cb2 commit 2313b9f
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 3 deletions.
16 changes: 13 additions & 3 deletions src/languages/bigquery.formatter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -892,9 +892,9 @@ function combineParameterizedTypes(tokens: Token[]) {
const endIndex = findClosingAngleBracketIndex(tokens, i + 1);
const typeDefTokens = tokens.slice(i, endIndex + 1);
processed.push({
...token,
value: typeDefTokens.map(t => t.value).join(''),
text: typeDefTokens.map(t => t.text).join(''),
type: TokenType.IDENT,
value: typeDefTokens.map(formatTypeDefToken('value')).join(''),
text: typeDefTokens.map(formatTypeDefToken('text')).join(''),
});
i = endIndex;
} else {
Expand All @@ -904,6 +904,16 @@ function combineParameterizedTypes(tokens: Token[]) {
return processed;
}

const formatTypeDefToken =
(key: 'text' | 'value') =>
(token: Token): string => {
if (token.type === TokenType.IDENT || token.value === ',') {
return token[key] + ' ';
} else {
return token[key];
}
};

function findClosingAngleBracketIndex(tokens: Token[], startIndex: number): number {
let level = 0;
for (let i = startIndex; i < tokens.length; i++) {
Expand Down
29 changes: 29 additions & 0 deletions test/bigquery.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,35 @@ describe('BigQueryFormatter', () => {
`);
});

// Issue #279
it('supports parametric STRUCT with named fields', () => {
expect(format('SELECT STRUCT<y INT64, z STRING>(1,"foo"), STRUCT<arr ARRAY<INT64>>([1,2,3]);'))
.toBe(dedent`
SELECT
STRUCT<y INT64, z STRING>(1, "foo"),
STRUCT<arr ARRAY<INT64>>([1, 2, 3]);
`);
});

it('supports uppercasing of STRUCT', () => {
expect(format('select struct<Nr int64, myName string>(1,"foo");', { keywordCase: 'upper' }))
.toBe(dedent`
SELECT
STRUCT<Nr INT64, myName STRING>(1, "foo");
`);
});

// XXX: This is hard to achieve with our current type-parameter processing hack.
// At least we're preserving the case of identifier names here,
// and lowercasing is luckily less used than uppercasing.
it('does not support lowercasing of STRUCT', () => {
expect(format('SELECT STRUCT<Nr INT64, myName STRING>(1,"foo");', { keywordCase: 'lower' }))
.toBe(dedent`
select
STRUCT<Nr INT64, myName STRING>(1, "foo");
`);
});

it('supports parameterised types', () => {
const result = format(
`
Expand Down

0 comments on commit 2313b9f

Please sign in to comment.