Skip to content

Commit

Permalink
settings are removed before trying to make an ast (we do not need set…
Browse files Browse the repository at this point in the history
…tings with the ast)
  • Loading branch information
bossinc committed Sep 28, 2023
1 parent e65ba06 commit dc20e24
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 3 deletions.
11 changes: 10 additions & 1 deletion src/data/ast.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { getFields } from './ast';
import { getFields, sqlToStatement } from './ast';
import { toSql } from 'pgsql-ast-parser'

describe('ast', () => {
describe('getFields', () => {
Expand All @@ -7,4 +8,12 @@ describe('ast', () => {
expect(stm.length).toBe(1);
});
});
describe('sqlToStatement', () => {
it('settings parse correctly', () => {
const sql = 'SELECT count(*) FROM mytable SETTINGS setting1=stuff setting2=stuff';
const stm = sqlToStatement(sql);
// this is formatted like this to match how pgsql generates its sql
expect(toSql.statement(stm)).toEqual('SELECT (count (*) ) FROM mytable');
});
});
});
17 changes: 15 additions & 2 deletions src/data/ast.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,17 +7,26 @@ export function sqlToStatement(sql: string): Statement {
replacementName: string;
}> = [];
//default is a key word in this grammar, but it can be used in CH
const re = /(\$__|\$|default)/gi;
const re = /(\$__|\$|default|settings)/gi;
let regExpArray: RegExpExecArray | null;
while ((regExpArray = re.exec(sql)) !== null) {
replaceFuncs.push({ startIndex: regExpArray.index, name: regExpArray[0], replacementName: '' });
let n = regExpArray[0];
if (n.toLowerCase() === "settings") {
n = sql.substring(regExpArray.index)
}
replaceFuncs.push({ startIndex: regExpArray.index, name: n, replacementName: '' });
}

//need to process in reverse so starting positions aren't effected by replacing other things
for (let i = replaceFuncs.length - 1; i >= 0; i--) {
const si = replaceFuncs[i].startIndex;
const replacementName = 'f' + (Math.random() + 1).toString(36).substring(7);
replaceFuncs[i].replacementName = replacementName;
// settings do not parse and we do not need information from them so we will remove them
if (replaceFuncs[i].name.toLowerCase().includes("settings")) {
sql = sql.substring(0, si)
continue;
}
sql = sql.substring(0, si) + replacementName + sql.substring(si + replaceFuncs[i].name.length);
}

Expand Down Expand Up @@ -98,3 +107,7 @@ export function getFields(sql: string): string[] {
}
});
}

export function statementToSql(stm: Statement): string {
return toSql.statement(stm);
}

0 comments on commit dc20e24

Please sign in to comment.