dc-cubes
/dc-cubes
Pisze definicje kostek drizzle-cube ze schematu Drizzle: defineCube, miary, wymiary, złączenia, filtrowanie najemców przez securityContext oraz miary obliczane, statystyczne i okienkowe.
- Autor
- cliftonc ↗
- Repozytorium
- drizzle-cube-plugin ↗
- Licencja
- MIT
- Ostatnia zmiana repozytorium
- 27.09.2026
Ocena i bezpieczeństwo
- Pliki w paczce
- 5
- Skrypty
- 0
- Komentarze HTML
- 0
- Adresy URL w SKILL.md
- 0
Brak sygnałów. Repozytorium zmienione 27.09.2026, bez odwołań do wycofanych modeli i API.
MIT, otwarta: można używać i zmieniać, z zachowaniem informacji o autorze.
Co robi i kiedy
Pisze definicje kostek drizzle-cube ze schematu Drizzle: defineCube, miary, wymiary, złączenia, filtrowanie najemców przez securityContext oraz miary obliczane, statystyczne i okienkowe.
Oryginalny opis (EN)
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).
Jak działa
- Canonical example
- Rules that matter
- Workflow
- Read next
Podgląd SKILL.md
---
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).
Pliki w paczce (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
Wersje
W bazie nie ma innych skilli o nazwie dc-cubes.
Migawka bazy z 13.11.2026 · wersja paczki 5be7ec8babf3 (skrót SHA-256 całej paczki)
Pobrania w ostatnich 30 dniach: 0 · ranking
Zgłoś problem z tym skillem: szkodliwa treść, błędny opis albo prośba autora o usunięcie.
Podobne skille
- 100dc-queries
Pisze i naprawia zapytania semantyczne w stylu Cube.js dla drizzle-cube: miary, wymiary, filtry, okresy, porównania, lejki, retencja, a także odpowiada na pytania narzędziami MCP drizzle_cube_*. - 100dc-server-setup
Konfiguruje stronę serwerową drizzle-cube: SemanticLayerCompiler, adaptery Express, Fastify, Hono i Next.js, extractSecurityContext dla wielu najemców, endpoint MCP, cache i RLS w Postgres. - 100cube
Pomaga w Cube, otwartej warstwie semantycznej między hurtownią danych a aplikacjami analitycznymi: kostki, miary i wymiary, pre-agregacje, API metryk, osadzona analityka i bezpieczeństwo na poziomie wierszy. - 93omni-model-builder
Tworzy i edytuje semantyczny model Omni Analytics w YAML przez Omni CLI: widoki, tematy, wymiary, miary, relacje, tabele agregujące i pola obliczane. - 100add-query-mode
Dodaje nowy tryb analizy lub zapytań do drizzle-cube, np. kohortowy czy analizę ścieżek: typy backendu, query builder, kompilator, adapter frontendu, store, hooki, komponenty UI, testy i ikonę. - 100migrate-from-cube
Migruje warstwę semantyczną Cube.js do plików .view.yml airlayer z istniejących schematów Cube.js (.js lub .yml).