Rayfin

Fabric SQL sources

Read and write Fabric SQL connector entities from Rayfin apps, including query chains, by-key reads, projected result types, mutations by dialect, defaults, and troubleshooting.

Use a Category A connector when an existing Fabric SQL source should feel like typed Rayfin entities. Category A covers fabric-sqlanalytics, fabric-warehouse, and fabric-sqldatabase; see Connectors for the full connector-type catalog and the steps that create the connector entry.

Each generated entity is reached at client.connectors.<name>.<Entity>. The methods on that entity come from two gates:

  • The connector's operations: list in rayfin.yml decides which CRUD verbs exist.
  • The connector type decides the write dialect, including whether mutations return the row or a status object.

The examples on this page import the client from src/services/rayfinClient.ts, wired as shown in Wiring connectors into your app. inventory is a Warehouse connector and orders is a SQL Database connector.

Choose the expected shape

  • Lakehouse SQL analytics endpoint (fabric-sqlanalytics) — reads only. Write methods are not exposed.
  • Fabric SQL Database (fabric-sqldatabase) — full CRUD when operations: allows it; writes return the persisted row.
  • Fabric Warehouse (fabric-warehouse) — full CRUD when operations: allows it; writes return DbOperationResult { result: string }.

Read rows with the query chain

Reads work the same way on Lakehouse, Warehouse, and SQL Database connectors. Start from an entity, choose a selection, add filters or ordering, and call execute() — or executePaginated() for a cursor envelope.

src/features/orders/loadOrders.ts
import { rayfinClient } from '../../services/rayfinClient';

export function loadLargeOrders() {
  return rayfinClient.connectors.inventory.Order
    .select(['orderId', 'customerEmail', 'total'])
    .where({ total: { gt: 100 } })
    .orderBy({ total: 'desc' })
    .execute();
}

export function loadOrderPage(cursor?: string) {
  const page = rayfinClient.connectors.inventory.Order
    .select(['orderId', 'customerEmail', 'total'])
    .where({ customerEmail: { contains: '@contoso.com' } })
    .orderBy({ orderId: 'asc' })
    .first(25);

  return (cursor ? page.after(cursor) : page).executePaginated();
}

executePaginated() resolves to { items, hasNextPage, endCursor?, totalCount? }; pass endCursor to after() on the next call. select, where, orderBy, first, and after are read operations, available when the connector includes read in operations:. A chain that reaches execute() without select() throws SELECTION_REQUIRED: the default selection from connectorConfig.entities never applies to the chain.

Read one row by key

findByKey identifies a row with a key object. For a composite primary key, the object must include every key part; omitting one is a compile error. The optional second argument is a scalar-only selection. Relationships cannot be selected through findByKey; use the query chain for related data.

src/features/orders/findOrder.ts
import { rayfinClient } from '../../services/rayfinClient';

export function findOrder(orderId: string) {
  return rayfinClient.connectors.inventory.Order.findByKey(
    { orderId },
    ['orderId', 'customerEmail', 'total'],
  );
}

export async function findLineItemQuantity(orderId: string, productId: string) {
  const lineItem = await rayfinClient.connectors.inventory.OrderItem.findByKey(
    { orderId, productId },
    ['orderId', 'productId', 'quantity'],
  );
  return lineItem?.quantity;
}

findByKey resolves to the selected fields or null. A keyless entity exposes no findByKey method.

Read result types follow the selection

Changed in 2.0

Result types match the fields the request actually asks for, so code that treated a partial response as a complete entity now fails at build time instead of reading unrequested properties as undefined.

ReadResult type
select([...]) chains, findMany(fields, filter?), findFirst(fields, filter?) with a literal field listExactly the selected fields with their declared types, including dotted relationship paths
findByKey(key, fields) with a literal field listThe selected scalar fields
findMany(filter?), findFirst(filter?), findByKey(key)Every scalar field, each optional, and no relationships
A field list built at runtime, or with conditional entriesThe possible fields, each optional
  • Selected Date fields are typed Date | string, and booleans boolean | 'true' | 'false', because wire values are not coerced. Convert them before using date methods or boolean truthiness.
  • select() returns a new builder. Always continue from the builder it returns; a repeated select() replaces the projection without changing an earlier builder.
  • To read fields you rely on, name them in the selection, or guard the optional fields of a default read.
src/features/orders/orderPlacedAt.ts
import { rayfinClient } from '../../services/rayfinClient';

export async function orderPlacedAt(orderId: string) {
  const order = await rayfinClient.connectors.inventory.Order.findByKey(
    { orderId },
    ['orderId', 'placedUtc'],
  );
  return order ? new Date(order.placedUtc) : undefined;
}

select accepts scalar columns and dotted paths through generated @one and @many navigation fields. The builder expands each dotted path into the nested GraphQL selection and unwraps to-many items connections so related rows are inline in the response.

src/features/products/loadProducts.ts
import { rayfinClient } from '../../services/rayfinClient';

export async function loadStockedProducts() {
  const products = await rayfinClient.connectors.inventory.Product
    .select(['name', 'category.name', 'orderItems.quantity'])
    .where({ stock: { gt: 0 } })
    .execute();

  return products.map((product) => ({
    name: product.name,
    category: product.category.name,
    unitsOrdered: product.orderItems.reduce((sum, item) => sum + item.quantity, 0),
  }));
}

export function loadProductCustomers() {
  return rayfinClient.connectors.inventory.Product
    .select(['name', 'orderItems.order.customerEmail'])
    .execute();
}

Name a related column as a dotted path such as category.name. Naming the bare relationship, such as category, is a compile error because a navigation field is not a selectable leaf. Connector paths stay dotted at any depth; they do not use the [] marker of client.data collection selections.

Relationship selections need the entity classes registered in connectorConfig.entities; string arrays throw ENTITIES_REQUIRED_FOR_RELATIONSHIP_SELECT. See Choose an entities registration form.

Self-referencing foreign keys still generate an entity relationship for DAB, but the client cannot query across a self-relationship. Do not select a dotted path over a self-reference.

Write rows by dialect

Write methods exist only when the connector's operations: includes the verb and the entity's @role() grants it. Autocomplete is expected to omit a method that is outside the connector operation list.

Connector typeSource behaviorcreate / update / delete returnWhat to do
fabric-sqlanalytics (Lakehouse)Read-only at the hostMethod does not existTreat missing write methods as expected compile-time protection.
fabric-sqldatabase (SQL Database)Supports read-after-writeThe persisted row's registered scalar columnsUse the returned values, including server-generated columns the caller never sent. Requires the entities map.
fabric-warehouse (Warehouse)DWSQL has no OUTPUT clauseDbOperationResult { result: string }Treat "success" as completion; failed writes throw GraphQL errors. Re-query if you need persisted values.
src/features/orders/orderWrites.ts
import { rayfinClient } from '../../services/rayfinClient';

export async function placeOrder(customerEmail: string, total: number) {
  const created = await rayfinClient.connectors.orders.Order.create({ customerEmail, total });
  return created.orderId;
}

export async function repriceOrder(orderId: string, total: number) {
  const result = await rayfinClient.connectors.inventory.Order.update({ orderId }, { total });
  return result.result === 'success';
}

export async function removeLineItem(orderId: string, productId: string) {
  await rayfinClient.connectors.inventory.OrderItem.delete({ orderId, productId });
}

Changed in 2.0

A SQL Database write returns the registered scalar columns, each optional in its type, with no relationships — placeOrder above returns number | undefined. Guard the values you read.

update and delete take the same full key object as findByKey. A keyless entity, where Source({ primaryKey }) is omitted or primaryKey: [], exposes no findByKey, update, or delete at all. It is read-only by key regardless of connector type.

Handle server-generated columns

A generated entity marks server-filled columns as AutoGenerated<T>. The metadata that triggers this type wrapper is:

  • IDENTITY columns.
  • Any column with a DEFAULT expression.
  • Computed columns declared with AS (...).
  • Server-managed rowversion or temporal-period columns.

Those columns are optional in create and update inputs and read back as plain T in query and mutation results. Most cannot be written: passing an IDENTITY, computed, rowversion, or temporal value is rejected by the database. A plain DEFAULT column is the exception: omit it to get the default, or pass a value to override it.

rayfin/connectors/orders/Order.ts
import { entity, date, decimal, int, text } from '@microsoft/rayfin-core';
import { Source } from '@microsoft/rayfin-connectors';
import type { AutoGenerated } from '@microsoft/rayfin-connectors';

@entity()
export class Order extends Source({ schema: 'dbo', table: 'Order', primaryKey: ['orderId'] }) {
  @int({ column: 'OrderID' })
  orderId!: AutoGenerated<number>;

  @text({ max: 256 })
  customerEmail!: string;

  @decimal({ precision: 18, scale: 2 })
  total!: number;

  @date({ column: 'CreatedUtc' })
  createdUtc!: AutoGenerated<Date>;
}

Configure default selections with entities

connectorConfig.entities gives the runtime either the scalar field names for each entity or the generated entity classes. It makes no-selection reads work and tells fabric-sqldatabase writes which columns to read back after a mutation. The decorated class form also tells relationship selections their cardinality.

rayfin/connectors/inventory/schema.ts
import type { GraphQLBackedConnector } from '@microsoft/rayfin-connector-fabric-graphql';
import type { ConnectorConfig } from '@microsoft/rayfin-connectors';

import type { Order } from './Order.js';
import type { OrderItem } from './OrderItem.js';

export type { Order } from './Order.js';
export type { OrderItem } from './OrderItem.js';

export const connectorConfig = {
  connector: 'fabric-warehouse',
  operations: ['read', 'create', 'update', 'delete'],
  entities: {
    Order: ['orderId', 'customerEmail', 'total', 'placedUtc'],
    OrderItem: ['orderId', 'productId', 'quantity', 'unitPrice'],
  },
} as const satisfies ConnectorConfig;

export type InventorySchema = GraphQLBackedConnector<
  { Order: typeof Order; OrderItem: typeof OrderItem },
  typeof connectorConfig
>;

Without entities, every no-selection findMany or findFirst throws SELECTION_REQUIRED. Passing an explicit selection remains the most precise way to control a read projection and its result type.

Use entity property names, not database column names. If the entity declares @uuid({ column: 'ProductID' }) productId!: string, the string-array entry is productId.

Prefer the string-array form unless app code selects relationship dotted paths. The class form puts decorated entity classes in the browser bundle, so the bundler must compile TC39 decorators — see Let the bundler compile entity decorators.

Aggregate connector rows

Aggregations use the same client pattern as Rayfin data entities. Use groupBy(fields).aggregate(spec).execute() for grouped values, or call aggregate(spec) on the entity client for a grand total. See Aggregations for the full API and response shape.

src/features/orders/orderTotals.ts
import { rayfinClient } from '../../services/rayfinClient';

export function totalsByCustomer() {
  return rayfinClient.connectors.inventory.Order
    .groupBy(['customerEmail'])
    .aggregate({
      revenue: { sum: 'total' },
      average: { avg: 'total' },
      orders: { count: 'total' },
    })
    .execute();
}

export function grandTotal() {
  return rayfinClient.connectors.inventory.Order
    .aggregate({
      revenue: { sum: 'total' },
      smallest: { min: 'total' },
      largest: { max: 'total' },
    })
    .execute();
}

Each key of the aggregate() map is an alias you choose, holding exactly one operation and the field it runs over. All five aggregate operations, sum, avg, min, max, and count, accept numeric fields only on connector entities.

Troubleshoot connector entity calls

SymptomLikely causeFix
A query chain throws SELECTION_REQUIREDThe chain has no select(); the entities default never applies to chainsAdd .select([...]), or use findMany(filter) when you need neither ordering nor a row limit.
findMany or findFirst throws SELECTION_REQUIREDconnectorConfig.entities is missing and the call passed no selectionAdd the entity's scalar property names or class to entities, or pass a selection.
A relationship read throws ENTITIES_REQUIRED_FOR_RELATIONSHIP_SELECTThe connector registered entities as string arrays, so relationship cardinality is unavailableSelect foreign key scalars and fetch separately, or register entity classes and enable decorator compilation.
After upgrading to 2.0, a property is missing or possibly undefined on a read resultResult types now follow the selection, and default reads expose optional scalarsAdd the field to the selection, or guard the optional value.
A date or boolean comparison misbehavesSelected Date fields are Date | string and booleans boolean | 'true' | 'false'Convert the value explicitly before using it.
A CRUD method is missing from autocompleteExpected: the typed marker narrows methods to the connector's operations: and removes by-key methods from keyless entitiesCheck rayfin.yml, connectorConfig.operations, and Source({ primaryKey }); widen only if the source and policy should allow it.
PromptQuery and update a Fabric SQL connector
In my Rayfin 2.0 project, use the existing Category A connector named inventory. Inspect rayfin/connectors/inventory/schema.ts and the generated entity files to confirm the connector type, operations, primary keys, scalar fields, and relationship fields. Then add a client-side query that reads Order rows through client.connectors.inventory.Order with an explicit select, a where filter, and an orderBy, and use only the selected fields from the result (result types follow the selection; dates come back as Date | string). If the connector exposes update, update one Order by passing the full key object and the scalar fields to change. If the connector is a Warehouse, treat the mutation result as DbOperationResult and re-query the row with findByKey and an explicit field list if persisted values are needed; if it is a SQL Database, use the returned row and guard its optional fields. Run the type-check when you are done.
Something wrong on this page?Report an issueEdit this page

On this page