Guides
Code reusability
Schema Generation

Implementing Schema Generation

This functionality only works with data models written in JavaScript, not YAML. For more information, check out the Data Modeling Syntax page.

Cube supports two ways to define data model files: with YAML or JavaScript syntax. If you opt for JavaScript syntax, you can use the full power of this programming language to configure your data model. In this guide we generate several measure definitions based on an array of strings.

One example, based on a real world scenario, is when you have a single events table containing an event_type and user_id column. Based on this table you want to create a separate user count measure for each event.

It can be done as simple as

const events = ["app_engagement", "login", "purchase"];
 
cube(`events`, {
  sql_table: `events`,
 
  measures: Object.assign(
    {
      count: {
        type: `count`,
      },
    },
    events
      .map((e) => ({
        [`${e}_user_count`]: {
          type: `count_distinct`,
          sql: `user_id`,
          filters: [
            {
              sql: `${CUBE}.event_type = '${e}'`,
            },
          ],
        },
      }))
      .reduce((a, b) => Object.assign(a, b))
  ),
});

In this case we use standard JavaScript functions Object.assign (opens in a new tab), Array.map (opens in a new tab) and Array.reduce (opens in a new tab) to add user count measure definitions based on events array. This approach allows you to maintain list of events in very concise manner without boilerplate code. This configuration can be reused using export / import feature.

Please refer to the asyncModule() documentation to learn how to use databases and other data sources for data model generation.