Skip to content

Commit

Permalink
feat(schema-compiler): Allow to pass functions to USER_CONTEXT
Browse files Browse the repository at this point in the history
Fixes #88
  • Loading branch information
paveltiunov committed Apr 24, 2019
1 parent 9ccf5e9 commit b489090
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 6 deletions.
26 changes: 21 additions & 5 deletions packages/cubejs-schema-compiler/adapter/BaseQuery.js
Original file line number Diff line number Diff line change
Expand Up @@ -1299,16 +1299,32 @@ class BaseQuery {
contextSymbolsProxy(symbols) {
return new Proxy(symbols, {
get: (target, name) => {
const paramValue = target[name];
return {
filter: (column) => (paramValue ? `${column} = ${this.paramAllocator.allocateParam(paramValue)}` : '1 = 1'),
const propValue = target[name];
const methods = (paramValue) => ({
filter: (column) => {
if (paramValue) {
const value = Array.isArray(paramValue) ?
paramValue.map(this.paramAllocator.allocateParam.bind(this.paramAllocator)) :
this.paramAllocator.allocateParam(paramValue);
if (typeof column === "function") {
return column(value);
} else {
return `${column} = ${value}`;
}
} else {
return '1 = 1';
}
},
requiredFilter: (column) => {
if (!paramValue) {
throw new UserError(`Filter for ${column} is required`);
}
return `${column} = ${this.paramAllocator.allocateParam(paramValue)}`;
return methods.filter(column);
}
};
});
return methods(target)[name] ||
typeof propValue === 'object' && this.contextSymbolsProxy(propValue) ||
methods(propValue);
}
});
}
Expand Down
27 changes: 26 additions & 1 deletion packages/cubejs-schema-compiler/test/GraphBuilderTest.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,8 @@ describe('JoinGraph', () => {
cube(\`visitors\`, {
sql: \`
select * from visitors WHERE \${USER_CONTEXT.source.filter('source')}
select * from visitors WHERE \${USER_CONTEXT.source.filter('source')} AND
\${USER_CONTEXT.sourceArray.filter(sourceArray => \`source in (\${sourceArray.join(',')})\`)}
\`,
sqlAlias: 'visitors_table',
Expand Down Expand Up @@ -1175,6 +1176,30 @@ describe('JoinGraph', () => {
});
});

it('user context array', () => compiler.compile().then(() => {
const query = new PostgresQuery({ joinGraph, cubeEvaluator, compiler }, {
measures: [
'visitor_checkins.revenue_per_checkin'
],
timeDimensions: [],
timezone: 'America/Los_Angeles',
contextSymbols: {
userContext: {
sourceArray: ['some', 'google']
}
}
});

console.log(query.buildSqlAndParams());

return dbRunner.testQuery(query.buildSqlAndParams()).then(res => {
console.log(JSON.stringify(res));
res.should.be.deepEqual(
[{ "visitor_checkins.revenue_per_checkin": "50" }]
);
});
}));

it('reference cube sql', () =>
runQueryTest({
measures: [
Expand Down

0 comments on commit b489090

Please sign in to comment.