Skip to content
Skills Library
Data & analytics · Building & coding

dc-cubes

/dc-cubes

Author drizzle-cube cube definitions from an existing Drizzle schema — defineCube, measures, dimensions, joins, tenant securityContext filtering, calculated/statistical/window measures, EAV attribute dimensions. Use whenever the user wants to create or edit cubes, add a metric or dimension, model a semantic layer, or turn Drizzle tables into analytics in an app using drizzle-cube (not for contributing to drizzle-cube itself).

Licence
MIT
Last repository change
27.09.2026

Assessment and security

100/ 100Class: good
Format25 / 25
Frontmatter with name and description, valid name, description up to 1,024 characters, name matching the folder.
Discoverability25 / 25
Description explains when to use the skill, has a reasonable length and uses third person.
Content35 / 35
At least 150 words and at most 500 lines, headings, step lists, examples or code.
Hygiene15 / 15
No placeholders such as TODO, no Windows paths, with a licence.
Riskno signals detected in the scan
Files in this package
5
Scripts
0
HTML comments
0
URLs in SKILL.md
0
Deprecation

No signals detected. Repository changed on 27.09.2026, without references to retired models or APIs.

Licence

MIT, open: use and modify while retaining author attribution.

What it does and when to use it

Author drizzle-cube cube definitions from an existing Drizzle schema — defineCube, measures, dimensions, joins, tenant securityContext filtering, calculated/statistical/window measures, EAV attribute dimensions. Use whenever the user wants to create or edit cubes, add a metric or dimension, model a semantic layer, or turn Drizzle tables into analytics in an app using drizzle-cube (not for contributing to drizzle-cube itself).

Original author description

Author drizzle-cube cube definitions from an existing Drizzle schema — defineCube, measures, dimensions, joins, tenant securityContext filtering, calculated/statistical/window measures, EAV attribute dimensions. Use whenever the user wants to create or edit cubes, add a metric or dimension, model a semantic layer, or turn Drizzle tables into analytics in an app using drizzle-cube (not for contributing to drizzle-cube itself).

How it works

  1. Canonical example
  2. Rules that matter
  3. Workflow
  4. Read next
Original SKILL.md headings · 144 lines, 1,120 words
SKILL.md preview
---
name: dc-cubes
description: Author drizzle-cube cube definitions from an existing Drizzle schema — defineCube, measures, dimensions, joins, tenant securityContext filtering, calculated/statistical/window measures, EAV attribute dimensions. Use whenever the user wants to create or edit cubes, add a metric or dimension, model a semantic layer, or turn Drizzle tables into analytics in an app using drizzle-cube (not for contributing to drizzle-cube itself).
---

# Authoring drizzle-cube cubes

A cube wraps one Drizzle table (or view/subquery) as a queryable model: **dimensions** to group and filter by, **measures** to aggregate, **joins** to other cubes, and a tenant filter. Queries reference members as `CubeName.memberKey` (e.g. `Orders.revenue`).

Everything below matches `drizzle-cube` 0.9.6 and later (`import … from 'drizzle-cube/server'`).

## Canonical example

Two cubes, joined in both directions, each scoped to the caller's organisation:

```ts
import { eq } from 'drizzle-orm'
import { defineCube } from 'drizzle-cube/server'
import type { Cube, QueryContext } from 'drizzle-cube/server'
import { customers, orders } from './schema'

// securityContext values are typed `unknown`: narrow them once, and fail closed.
function orgId(ctx: QueryContext): number {
  const id = ctx.securityContext.organisationId
  if (typeof id !== 'number') throw new Error('securityContext.organisationId missing')
  return id
}

// Forward declarations so each cube's joins can point at the other.
let customersCube: Cube
let ordersCube: Cube

customersCube = defineCube('Customers', {
  title: 'Customers',
  description: 'One row per customer account',
  sql: (ctx) => ({
    from: customers,
    where: eq(customers.organisationId, orgId(ctx))
  }),
  joins: {
    Orders: {
      targetCube: () => ordersCube,
      relationship: 'hasMany',
      on: [{ source: customers.id, target: orders.customerId }]
    }
  },
  dimensions: {
    id: { name: 'id', type: 'number', sql: customers.id, primaryKey: true, shown: false },
    name: { name: 'name', title: 'Customer', type: 'string', sql: customers.name },
    plan: { name: 'plan', type: 'string', sql: customers.plan, synonyms: ['tier'] },
    region: { name: 'region', type: 'string', sql: customers.region },
    isActive: { name: 'isActive', type: 'boolean', sql: customers.isActive },
    createdAt: { name: 'createdAt', title: 'Signup date', type: 'time', sql: customers.createdAt }
  },
  measures: {
    count: { name: 'count', title: 'Customers', type: 'count', sql: customers.id },
    activeCount: {
      name: 'activeCount',
      title: 'Active customers',
      type: 'count',
      sql: customers.id,
      filters: [() => eq(customers.isActive, true)]
    }
  }
})

ordersCube = defineCube('Orders', {
  title: 'Orders',
  exampleQuestions: ['What was revenue last month?', 'Average order value by plan'],
  sql: (ctx) => ({
    from: orders,
    where: eq(orders.organisationId, orgId(ctx))
  }),
  joins: {
    Customers: {
      targetCube: () => customersCube,
      relationship: 'belongsTo',
      on: [{ source: orders.customerId, target: customers.id }]
    }
  },
  dimensions: {
    id: { name: 'id', type: 'number', sql: orders.id, primaryKey: true },
    status: { name: 'status', type: 'string', sql: orders.status },
    createdAt: { name: 'createdAt', title: 'Order date', type: 'time', sql: orders.createdAt }
  },
  measures: {
    count: {
      name: 'count',
      title: 'Orders',
      type: 'count',
      sql: orders.id,
      drillMembers: ['Orders.id', 'Orders.status', 'Customers.name']
    },
    revenue: {
      name: 'revenue',
      type: 'sum',
      sql: orders.total,
      synonyms: ['sales', 'income']
    },
    averageOrderValue: {
      name: 'averageOrderValue',
      title: 'Average order value',
      type: 'calculated',
      calculatedSql: '{revenue} / NULLIF({count}, 0)'
    }
  }
})

export { customersCube, ordersCube }
export const allCubes = [customersCube, ordersCube]
```

Register `allCubes` with the semantic layer — see the **dc-server-setup** skill.

## Rules that matter

1. **The cube `sql` returns `{ from, where, joins? }`, not a SQL expression, and `where` carries the tenant filter on every cube.** Each cube's `where` is applied only to that cube's own table. A joined cube without a filter pulls in every tenant's rows.
2. **Narrow `securityContext` values instead of casting blindly.** They are typed `unknown`, so `eq(col, ctx.securityContext.organisationId)` doesn't compile. `as number` compiles too, but a missing value then goes straight into the SQL unchecked. A guard like `orgId()` throws when the value is missing, so queries fail closed.
3. **Keep each member's `name` identical to its record key.** Metadata and queries use the key (`Orders.revenue` comes from `measures.revenue`), so a `name` that differs from its key only confuses readers.
4. **Give every cube a `primaryKey` dimension that is a plain column.** The fan-out de-duplication uses it to avoid double-counting across `hasMany` joins. It skips primary keys whose `sql` is a function.
5. **Declare joins from both sides: `belongsTo` on the foreign-key side, `hasMany` back on the parent.** The planner can walk a join backwards to find a path. But it only picks the query's base (FROM) cube from cubes whose *own* joins reach every other cube. Without `Customers → Orders hasMany`, a query for `Customers.name` + `Orders.count` has to start from Orders with an inner join, so customers with no orders disappear from the result and `Customers.count` is undercounted.
6. **Use thunks (`() => ordersCube`) with `let` forward declarations for mutual joins.** A direct reference to a cube that isn't assigned yet is `undefined` at definition time. A thunk is only resolved at query time. A string name (`'Orders'`) also works and is resolved against the registered cubes; it suits cubes that live in separate files.
7. **Only the join's `targetCube` matters. The join's record key is just a label.** Name the key after the target cube anyway. Members are always addressed by the target cube's name (`Customers.name`), never by the join key.
8. **Stick to measure types that do what they say.** `countDistinctApprox` and `runningTotal` exist in the type union, but they silently compile to `COUNT(...)`, and `rollingWindow` is ignored. Use `countDistinct`, or a window measure (`movingSum`, `lag`, …), instead. Non-calculated measures need `sql`, even `count`.

## Workflow

1. **Read the schema.** Find the tenant column (`organisationId`, `tenantId`, …) on every table you'll model. If a table has none, scope it through a join to a table that does (in the cube's `sql.joins` + `where`), or leave it out.
2. **Pick the grain.** One cube per table, where one row is one thing (one order, one event). Its primary key becomes the `primaryKey` dimension.
3. **Dimensions.** Add the columns people group or filter by: strings, booleans, numeric IDs, and `time` for timestamps. Derived values are `sql` expressions. Hide technical IDs with `shown: false`; they stay queryable.
4. **Measures.** Start with `count`, then add `sum`/`avg`/`countDistinct` on business columns. Use `filters` for conditional variants ("paid revenue"), and `calculated` for ratios.
5. **Joins.** For each foreign key, add `belongsTo` on the child and `hasMany` on the parent. Use `belongsToMany` + `through` for junction tables that have no measures of their own.
6. **Add AI/UX hints.** Add `title`, `description`, `synonyms` and `exampleQuestions`. The AI agent and the field picker read them.
7. **Typecheck** (`tsc --noEmit`), register the cubes, then run a query per join path to confirm the row counts look right.

## Read next

Open only the reference your task needs.

| File | Read when |
|---|---|
| `references/measures.md` | Choosing a measure type; filtered, calculated, cross-cube, statistical, percentile or window (period-over-period, moving average, rank) measures; engine support |
| `references/dimensions.md` | SQL-expression dimensions, JSON fields, casts, time granularities, `shown`, hierarchies, cube-level options (`meta.eventStream` for funnels/flows/retention, subquery sources) |
| `references/joins.md` | Relationship semantics and default join types, star schemas / fan-out, many-to-many via `through`, multi-column or non-equality joins, `preferredFor`, string references |
| `references/eav-attributes.md` | Per-tenant custom fields stored as entity-attribute-value rows (`buildAttributeDimensions`) |

Sibling skills: **dc-server-setup** (registering cubes, the compiler, adapters, per-tenant cube sets), **dc-queries** (writing queries against these cubes), **dc-charts** (value formatting and display).
Files in this package (5)
  • SKILL.md 9 KB
  • references/dimensions.md 8 KB
  • references/eav-attributes.md 5 KB
  • references/joins.md 9 KB
  • references/measures.md 10 KB

Versions

The database has no other skills named dc-cubes.

Database snapshot: 13.11.2026 · package version 5be7ec8babf3 (SHA-256 digest of the entire package)

Downloads in the last 30 days: 0 · ranking

Report a problem with this skill: harmful content, incorrect descriptions or an author’s removal request.

Similar skills

  • 100dc-queries
    Use when writing or fixing drizzle-cube / Cube.js-style semantic queries (measures, dimensions, filters, timeDimensions, date ranges, period comparison, funnels, flows, retention, raw rows), when answering data questions against a drizzle-cube server with the drizzle_cube_* MCP…
  • 100dc-server-setup
    Set up the drizzle-cube server side of an app — install, SemanticLayerCompiler, engineType, Express/Fastify/Hono/Next.js adapters, extractSecurityContext for multi-tenant auth, the built-in MCP endpoint for Claude/AI clients, caching, Postgres RLS, per-tenant cube sets. Use…
  • 100cube
    Cube is an open-source semantic layer that sits between a data warehouse and analytics applications and serves governed metrics over REST, GraphQL and SQL APIs. Use when a user asks to define cubes, measures and dimensions, add pre-aggregations, build a metrics API or embedded…
  • 93omni-model-builder
    Create and edit Omni Analytics semantic model definitions — views, topics, dimensions, measures, relationships, query views, composite topics, and aggregate tables (materialized_query) — using YAML through the Omni CLI. Use this skill whenever someone wants to add a field,…
  • 100add-query-mode
    Use when adding a new analysis/query mode to drizzle-cube (e.g., cohort, path analysis). Covers backend types, query builder, executor/compiler integration, frontend adapter, store slice, hooks, UI components, tests, and icon.
  • 100migrate-from-cube
    Migrate a Cube.js semantic layer to airlayer .view.yml files. Use when the user has existing Cube.js schema files (.js or .yml) they want to convert to airlayer format.

Feedback and reports

Your message goes to Bartosz Sokoliński. An email address is needed only for a reply. See the privacy policy.