cube.js 上下文变量

上下文变量提供了比较强大的cube.js 自定义处理,目前cube.js 提供了filter,user context
sql utils,compile context,unsafe value

filter params

基于FILTER_PARAMS 允许基于filter 在sql 生成的时候

  • 参考格式
 
FILTER_PARAMS.<CUBE_NAME>.<FILTER_NAME>.filter(expression)
  • 说明
    expression 可以是字符串以及函数
    比如
 
cube(`OrderFacts`, {
  sql: `SELECT * FROM orders WHERE ${FILTER_PARAMS.OrderFacts.date.filter('date')}`,
  measures: {
    count: {
      type: `count`
    }
  },
  dimensions: {
    date: {
      sql: `date`,
      type: `time`
    }
  }
});
 

查询

{
  measures: ['OrderFacts.count'],
  timeDimensions: [{
    dimension: 'OrderFacts.date',
    granularity: 'day',
    dateRange: ['2018-01-01', '2018-12-31']
  }]
}

对于['2018-01-01', '2018-12-31']区间的查询sql如下

SELECT * FROM orders WHERE date >= '2018-01-01 00:00:00' and date <= '2018-12-31 23:59:59'

函数格式

cube(`Events`, {
  sql: `
  SELECT * FROM schema.\`events*\`
  WHERE ${FILTER_PARAMS.Events.date.filter((from, to) =>
    `_TABLE_SUFFIX >= FORMAT_TIMESTAMP('%Y%m%d', TIMESTAMP(${from})) AND _TABLE_SUFFIX <= FORMAT_TIMESTAMP('%Y%m%d', TIMESTAMP(${to}))`
  )}
  `,
  dimensions: {
    date: {
      sql: `date`,
      type: `time`
    }
  }
});
 
 

user context

  • 参考格式
cube(`Orders`, {
  sql: `SELECT * FROM orders WHERE ${USER_CONTEXT.email.filter('email')}`,
  dimensions: {
    date: {
      sql: `date`,
      type: `time`
    }
  }
});

对于必须的可以使用requiredFilter

cube(`Orders`, {
  sql: `SELECT * FROM orders WHERE ${USER_CONTEXT.email.requiredFilter('email')}`,
  dimensions: {
    date: {
      sql: `date`,
      type: `time`
    }
  }
});

sql utils

主要进行时区的转换处理

cube(`visitors`, {
  // ...
  dimensions: {
    createdAtConverted: { // do not use in timeDimensions query property
      type: 'time',
      sql: SQL_UTILS.convertTz(`created_at`)
    },
    createdAt: { // use in timeDimensions query property
      type: 'time',
      sql: `created_at`
    },
  }
})

compile context

可以实现类似RequestContext 的处理

const { authInfo: { deploymentId } } = COMPILE_CONTEXT;
const schemaName = `user_${deploymentId}`;
cube(`Users`, {
  sql: `select * from ${schemaName}.users`,
  // ...
});

参考资料

https://cube.dev/docs/cube#context-variables-filter-params

posted on   荣锋亮  阅读(207)  评论(0编辑  收藏  举报

编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)
历史上的今天:
2019-01-27 sofa graphql 2 rest api webhook 试用
2019-01-27 sofa graphql 2 rest api 试用
2019-01-27 sofa graphql 2 rest api框架

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示