Skip to content

Commit

Permalink
formatter: fixes grant query. closes #460
Browse files Browse the repository at this point in the history
  • Loading branch information
mtxr committed Jun 4, 2020
1 parent 9543776 commit 7475ec2
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 7 deletions.
19 changes: 12 additions & 7 deletions packages/formatter/src/core/Formatter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ const trimSpacesEnd = str => str.replace(/[ \t]+$/u, '');
export default class Formatter {
private tokens: Token[] = [];
private previousReservedWord: Token = { type: null, value: null };
private previousNonWhiteSpace: Token = { type: null, value: null };
private indentation: Indentation;
private inlineBlock: InlineBlock;
private params: Params;
Expand Down Expand Up @@ -79,8 +80,8 @@ export default class Formatter {
formattedQuery = this.formatWithSpaces(token, formattedQuery);
}

if (this.previousToken().type === TokenTypes.RESERVED_TOP_LEVEL) {
this.indentation.increaseTopLevel();
if (token.type !== TokenTypes.WHITESPACE) {
this.previousNonWhiteSpace = token;
}
});
return formattedQuery;
Expand Down Expand Up @@ -143,11 +144,15 @@ export default class Formatter {
}

formatTopLevelReservedWord(token: Token, query: string) {
this.indentation.decreaseTopLevel();

query = this.addNewline(query);

return query + this.equalizeWhitespace(this.formatReservedWord(token.value)) + ' ';
const shouldChangeTopLevel = (this.previousNonWhiteSpace.value !== ',' && `${this.previousNonWhiteSpace.value}`.toUpperCase() !== 'GRANT');
if (shouldChangeTopLevel) {
this.indentation.decreaseTopLevel();
query = this.addNewline(query);
}
query = query + this.equalizeWhitespace(this.formatReservedWord(token.value)) + ' ';
if (shouldChangeTopLevel)
this.indentation.increaseTopLevel();
return query;
}

formatNewlineReservedWord(token: Token, query: string) {
Expand Down
26 changes: 26 additions & 0 deletions packages/formatter/test/StandardSqlFormatter.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -616,4 +616,30 @@ where id = $1`);
.toEqual(i);
}
});

it(`format grant stataments with keyword identation`, () => {
let input = `GRANT ALTER, CREATE, DELETE, EXECUTE, INSERT, SELECT, REFERENCES, TRIGGER, UPDATE ON *.* TO 'user' @'%';`;

expect(format(input)).toEqual(dedent(`
GRANT ALTER,
CREATE,
DELETE,
EXECUTE,
INSERT,
SELECT,
REFERENCES,
TRIGGER,
UPDATE ON *.* TO 'user' @'%';
`))

input = `GRANT INSERT, SELECT, REFERENCES, TRIGGER, UPDATE ON * TO 'user' @'%';`;

expect(format(input)).toEqual(dedent(`
GRANT INSERT,
SELECT,
REFERENCES,
TRIGGER,
UPDATE ON * TO 'user' @'%';
`))
});
});

0 comments on commit 7475ec2

Please sign in to comment.