{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "data-grid-server-query-drizzle",
  "title": "Data Grid Server Query Drizzle",
  "author": "gridcn",
  "description": "Runs the grid's sort, filter tree, quick search, row range, row count, set values, and flat aggregates with Drizzle on PostgreSQL and SQLite: columnsFromDrizzleTable builds the column map from a schema, createDrizzleGridQuery returns fetchRows for useDataGridServerRows.",
  "dependencies": [
    "drizzle-orm@>=0.45.0 <1"
  ],
  "registryDependencies": [
    "@gridcn/data-grid-server-query"
  ],
  "files": [
    {
      "path": "registry/default/blocks/data-grid-server-query-drizzle/columns.ts",
      "content": "import { type Column, type Table, getTableColumns } from \"drizzle-orm\";\r\nimport { type ColumnMap, type ColumnSpec, defineColumnMap } from \"@/registry/default/components/data-grid-server-query/data-grid-server-query\";\r\nimport { isDev } from \"@/registry/default/components/data-grid-server-query/data-grid-server-query-sdk\";\r\n\r\nexport type ColumnsFromDrizzleTableOptions<Id extends string> = {\r\n  /** The columns the client may see, by the table's property names. Required: no helper maps a whole table. */\r\n  pick: readonly Id[];\r\n  /** Per-column changes to the generated spec. */\r\n  overrides?: { [K in Id]?: Partial<ColumnSpec> };\r\n  /** Columns that order rows when the table has no single-column primary key. */\r\n  tieBreaker?: readonly Id[];\r\n};\r\n\r\nconst SMALL = new Set([\"PgSmallInt\", \"PgSmallSerial\"]);\r\nconst INT53 = new Set([\"PgBigInt53\", \"PgBigSerial53\", \"SQLiteInteger\"]);\r\nconst FLOAT = new Set([\"PgReal\", \"PgDoublePrecision\", \"SQLiteReal\"]);\r\n\r\nfunction specFor(id: string, column: Column): ColumnSpec {\r\n  const columnType = column.columnType;\r\n  const base = { required: column.notNull, primaryKey: column.primary, field: id };\r\n  const sqlite = columnType.startsWith(\"SQLite\");\r\n  switch (column.dataType) {\r\n    case \"number\":\r\n      if (columnType.endsWith(\"NumericNumber\")) return { ...base, type: \"number\", numeric: \"decimal\" };\r\n      if (FLOAT.has(columnType)) return { ...base, type: \"number\", numeric: \"float\" };\r\n      return { ...base, type: \"number\", numeric: SMALL.has(columnType) ? \"int2\" : INT53.has(columnType) ? \"int8\" : \"int4\" };\r\n    case \"bigint\":\r\n      if (columnType.endsWith(\"NumericBigInt\")) return { ...base, type: \"number\", numeric: \"decimal\" };\r\n      return { ...base, type: \"number\", numeric: \"int8\" };\r\n    case \"boolean\":\r\n      return { ...base, type: \"checkbox\" };\r\n    case \"date\":\r\n      if (columnType === \"PgTimestamp\") return { ...base, type: \"date\", time: true, storage: \"native\" };\r\n      if (sqlite) return { ...base, type: \"date\", time: true, storage: (column as unknown as { mode?: string }).mode === \"timestamp_ms\" ? \"epoch-ms\" : \"epoch-s\" };\r\n      return { ...base, type: \"date\" };\r\n    case \"string\": {\r\n      if (columnType === \"PgNumeric\" || columnType === \"SQLiteNumeric\") {\r\n        const scale = (column as unknown as { scale?: number }).scale;\r\n        return { ...base, type: \"number\", numeric: \"decimal\", ...(scale === undefined || scale === null ? {} : { scale }) };\r\n      }\r\n      if (columnType === \"PgDateString\") return { ...base, type: \"date\" };\r\n      if (columnType === \"PgTimestampString\") return { ...base, type: \"date\", time: true, storage: \"native\" };\r\n      if (columnType === \"PgEnumColumn\" && column.enumValues) return { ...base, type: \"select\", native: \"enum\", choices: [...column.enumValues] };\r\n      if (columnType === \"PgUUID\") return { ...base, type: \"text\", native: \"uuid\" };\r\n      return { ...base, type: \"text\" };\r\n    }\r\n    default:\r\n      if (isDev()) console.warn(`gridcn query layer: column \"${id}\" has the type ${columnType}, which the column map reads as text. Override it if that is wrong.`);\r\n      return { ...base, type: \"text\" };\r\n  }\r\n}\r\n\r\n/**\r\n * Builds the column map of picked Drizzle columns: kinds, nullability, enums, uuids, decimals, and the primary key come\r\n * from the schema. Adjust one column with `overrides`.\r\n *\r\n * @example\r\n * const columns = columnsFromDrizzleTable(users, { pick: [\"id\", \"name\", \"tenantId\"], overrides: { name: { searchable: true } } });\r\n */\r\nexport function columnsFromDrizzleTable<TTable extends Table, Id extends keyof TTable[\"_\"][\"columns\"] & string>(table: TTable, options: ColumnsFromDrizzleTableOptions<Id>): ColumnMap<Id> {\r\n  const all = getTableColumns(table) as Record<string, Column>;\r\n  const specs: Record<string, ColumnSpec> = {};\r\n  const primaries = options.pick.filter((id) => all[id]?.primary);\r\n  const overrides = options.overrides as Record<string, Partial<ColumnSpec>> | undefined;\r\n  for (const id of options.pick) {\r\n    const column = Object.hasOwn(all, id) ? all[id] : undefined;\r\n    if (!column) throw new Error(`columnsFromDrizzleTable: the table has no column \"${id}\"`);\r\n    const generated = specFor(id, column);\r\n    if (primaries.length > 1) generated.primaryKey = false;\r\n    specs[id] = { ...generated, ...(overrides && Object.hasOwn(overrides, id) ? overrides[id] : {}) };\r\n  }\r\n  const tieBreaker = options.tieBreaker ?? (primaries.length > 1 ? primaries : undefined);\r\n  return defineColumnMap(specs, tieBreaker ? { tieBreaker } : {}) as unknown as ColumnMap<Id>;\r\n}\r\n",
      "type": "registry:component",
      "target": "components/data-grid-server-query-drizzle/columns.ts"
    },
    {
      "path": "registry/default/blocks/data-grid-server-query-drizzle/create-drizzle-grid-query.ts",
      "content": "import { type Column, SQL, type Table, getTableColumns, sql } from \"drizzle-orm\";\r\nimport type { AdapterCapabilities, ColumnMap, GridQuery, QueryLimits, RowCountMode, RowScope } from \"@/registry/default/components/data-grid-server-query/data-grid-server-query\";\r\nimport {\r\n  type CustomHandler,\r\n  type PlanColumn,\r\n  type SqlAlgebra,\r\n  assertCustomOperatorHandlers,\r\n  createGridQuery,\r\n  createSqlRenderer,\r\n  mapOf,\r\n} from \"@/registry/default/components/data-grid-server-query/data-grid-server-query-sdk\";\r\n\r\ntype Rows = Record<string, unknown>[];\r\ntype Builder = PromiseLike<Rows> & {\r\n  from(table: Table): Builder;\r\n  where(condition: SQL): Builder;\r\n  orderBy(...order: SQL[]): Builder;\r\n  groupBy(...group: SQL[]): Builder;\r\n  limit(count: number): Builder;\r\n  offset(count: number): Builder;\r\n};\r\n\r\n/** A Drizzle database of any driver. */\r\nexport type DrizzleDatabase = { select: (...args: never[]) => unknown };\r\n\r\nexport type DrizzleGridQueryOptions<TContext = never> = {\r\n  db: DrizzleDatabase;\r\n  table: Table;\r\n  columns: ColumnMap;\r\n  /** Equalities on mapped columns that every query ANDs in. Needs `context` on every call. */\r\n  rowScope?: RowScope<TContext>;\r\n  /** When a rows request also counts the result. Default `\"firstBlock\"`. */\r\n  rowCount?: RowCountMode;\r\n  limits?: QueryLimits;\r\n  /** IANA zone or fixed offset of day filters on `time` columns. Default `\"UTC\"`. */\r\n  timeZone?: string;\r\n  /** Handlers for the custom operators the column map declares; each returns a Drizzle `sql` fragment and must bind `value` through it. */\r\n  customOperators?: Record<string, (ctx: { column: PlanColumn; value: unknown }) => SQL>;\r\n};\r\n\r\n/** Reads and counts rows with Drizzle, from the column map and a request body. */\r\nexport function createDrizzleGridQuery<TRow = Record<string, unknown>, TContext = never>(options: DrizzleGridQueryOptions<TContext>): GridQuery<TRow, TContext, SQL, SQL> {\r\n  const { db, table, columns } = options;\r\n  const tableColumns = getTableColumns(table) as Record<string, Column>;\r\n  const first = Object.values(tableColumns)[0];\r\n  const dialect = first?.columnType.startsWith(\"SQLite\") ? \"sqlite\" : \"pg\";\r\n  const physical = new Map<string, Column>();\r\n  for (const column of mapOf(columns).byId.values()) {\r\n    const found = Object.hasOwn(tableColumns, column.field) ? tableColumns[column.field] : undefined;\r\n    if (!found) throw new Error(`createDrizzleGridQuery: the table has no column \"${column.field}\" for \"${column.id}\"`);\r\n    physical.set(column.id, found);\r\n  }\r\n  assertCustomOperatorHandlers(columns, options.customOperators);\r\n  const algebra: SqlAlgebra<SQL> = {\r\n    dialect,\r\n    raw: (text) => sql.raw(text),\r\n    param: (value) => sql`${value}`,\r\n    column: (column) => sql`${physical.get(column.id)!}`,\r\n    cat: (...parts) => sql.join(parts, sql.raw(\"\")),\r\n    native: (value) => {\r\n      if (!(value instanceof SQL)) throw new Error(\"customOperators: a handler must return a Drizzle sql fragment\");\r\n      return value;\r\n    },\r\n  };\r\n  const renderer = createSqlRenderer(algebra, new Map(Object.entries(options.customOperators ?? {})) as ReadonlyMap<string, CustomHandler>);\r\n  const selectFrom = (fields: Record<string, unknown>) => (db as unknown as { select(fields: Record<string, unknown>): { from(table: Table): Builder } }).select(fields).from(table);\r\n  const capabilities: AdapterCapabilities = {\r\n    caseInsensitiveText: dialect === \"pg\" ? \"collation\" : \"ascii\",\r\n    likeEscape: true,\r\n    literalAsterisk: true,\r\n    nullsLast: \"native\",\r\n    aggregates: true,\r\n    groupBy: true,\r\n    localDayGrouping: dialect === \"pg\",\r\n  };\r\n\r\n  return createGridQuery<TRow, TContext, SQL, SQL>({\r\n    columns,\r\n    rowScope: options.rowScope,\r\n    rowCount: options.rowCount,\r\n    limits: options.limits,\r\n    timeZone: options.timeZone,\r\n    executor: {\r\n      capabilities,\r\n      where: (plan) => renderer.predicate(plan.where),\r\n      orderBy: (plan) => renderer.orderBy(plan.orderBy),\r\n      selectRows: (plan, page) => {\r\n        const fields = Object.fromEntries(plan.projection.map((column) => [column.id, physical.get(column.id)!]));\r\n        return Promise.resolve(selectFrom(fields).where(renderer.predicate(plan.where)).orderBy(renderer.orderBy(plan.orderBy)).limit(page.limit).offset(page.offset));\r\n      },\r\n      countRows: async (plan) => {\r\n        const rows = await selectFrom({ n: sql`count(*)` }).where(renderer.predicate(plan.where));\r\n        return rows[0]?.[\"n\"];\r\n      },\r\n      selectValues: (plan, { limit }) => {\r\n        const { key, value } = renderer.valueKey(plan.column, options.timeZone ?? \"UTC\");\r\n        return Promise.resolve(\r\n          selectFrom({ value, count: sql`count(*)` })\r\n            .where(renderer.valuesFilter(plan, options.timeZone ?? \"UTC\"))\r\n            .groupBy(key)\r\n            .orderBy(sql`count(*) DESC`, sql`${value} ASC`)\r\n            .limit(limit),\r\n        ) as Promise<{ value: unknown; count: unknown }[]>;\r\n      },\r\n      selectGroups: async (plan, page) => {\r\n        const key = renderer.groupKey(plan.level);\r\n        const fields: Record<string, unknown> = { k: key, n: sql`count(*)`, c: plan.nextLevel ? renderer.keyCount(renderer.groupKey(plan.nextLevel)) : sql`count(*)` };\r\n        plan.aggregates.forEach(({ column, reducer }, index) => (fields[`a${index}`] = renderer.aggregate(column, reducer)));\r\n        const rows = await selectFrom(fields)\r\n          .where(renderer.predicate(plan.where))\r\n          .groupBy(key)\r\n          .orderBy(sql`${key} ${sql.raw(plan.direction === \"asc\" ? \"ASC\" : \"DESC\")} NULLS LAST`)\r\n          .limit(page.limit)\r\n          .offset(page.offset);\r\n        return rows.map((row) => ({ key: row[\"k\"], count: row[\"n\"], childCount: row[\"c\"], aggregates: Object.fromEntries(plan.aggregates.map(({ column }, index) => [column.id, row[`a${index}`]])) }));\r\n      },\r\n      countGroups: async (plan) => (await selectFrom({ n: renderer.keyCount(renderer.groupKey(plan.level)) }).where(renderer.predicate(plan.where)))[0]?.[\"n\"],\r\n      aggregate: async (plan) => {\r\n        const fields = Object.fromEntries(plan.columns.map(({ column, reducer }, index) => [`c${index}`, renderer.aggregate(column, reducer)]));\r\n        const rows = await selectFrom(fields).where(renderer.predicate(plan.where));\r\n        const row = rows[0] ?? {};\r\n        return Object.fromEntries(plan.columns.map(({ column }, index) => [column.id, row[`c${index}`]]));\r\n      },\r\n    },\r\n  });\r\n}\r\n",
      "type": "registry:component",
      "target": "components/data-grid-server-query-drizzle/create-drizzle-grid-query.ts"
    },
    {
      "path": "registry/default/blocks/data-grid-server-query-drizzle/data-grid-server-query-drizzle.ts",
      "content": "export { createDrizzleGridQuery, type DrizzleGridQueryOptions, type DrizzleDatabase } from \"./create-drizzle-grid-query\";\r\nexport { columnsFromDrizzleTable, type ColumnsFromDrizzleTableOptions } from \"./columns\";\r\n",
      "type": "registry:component",
      "target": "components/data-grid-server-query-drizzle/data-grid-server-query-drizzle.ts"
    }
  ],
  "categories": [
    "data"
  ],
  "type": "registry:block"
}
