Skip to content
NewMulti-tenancy and row-level security (RLS) in TypeScript6 min read

Views

defineView declares a view as a query over an entity: an aggregate, written as pool.aggregate takes it, or a find. Its rows are typed by that query, and UQL reads it by its query on every engine, MongoDB included, so the source’s filters and policies hold every read of it.

A view’s columns come from its query, so it is declared with defineView alone, over a decorated class or a defineEntity one alike: a decorator would declare each column again by hand.

import { defineView, Entity, f, Field, ManyToOne } from 'uql-orm';
@Entity()
export class Customer {
@Field(f.number().autoIncrement()) id?: number;
@Field(f.string()) name!: string;
}
@Entity()
export class Order {
@Field(f.number().autoIncrement()) id?: number;
@Field(f.number()) customerId!: number;
@Field(f.number()) total!: number;
@Field(f.enum(['open', 'paid'])) status!: 'open' | 'paid';
@Field(f.date().nullable().softDelete()) deletedAt?: Date | null;
@ManyToOne(() => Customer, { references: (order) => order.customerId })
customer?: Customer;
}
export const CustomerTotals = defineView({
name: 'CustomerTotals',
from: () => Order,
aggregate: {
$group: { customerId: true },
$select: { orders: { $count: '*' }, spent: { $sum: { total: true } } },
$where: { status: 'paid' },
},
}).relations((rel) => ({
customer: () =>
rel.manyToOne(Customer, { references: (row) => row.customerId }),
}));
export const OpenOrder = defineView({
name: 'OpenOrder',
from: () => Order,
find: {
$select: { id: true, customerId: true, total: true },
$where: { status: 'open' },
},
});

aggregate takes what pool.aggregate takes, and find what findMany takes but the clauses a flat row cannot hold: $populate, $count and $lock. So a typo in either fails to compile as it would in a query. Each takes $sort only with $limit, a top N such as a leaderboard’s: a view is a set of rows, and otherwise a read orders and pages it.

The query reaches related rows as any query does: a $group through a to-one ({ customerName: { customer: { name: true } } }), a $where on a relation, or a relation aggregate a find selects. Related rows beside a view’s own come from its relations, populated when it is read.

A view reads like any entity: findMany, findOne, count, findManyAndCount, aggregate, a stream, $where and $sort on its columns, and its relations populated. Another entity may join it by a relation, and a view may read another view (from: () => CustomerTotals).

const big = await pool.findMany(CustomerTotals, {
$where: { spent: { $gt: 1000 } },
$sort: { spent: 'desc' },
$populate: { customer: { $select: { name: true } } },
});

Each read renders the view’s query in place: a derived table on SQL, the view’s stages ahead of the read’s own on MongoDB. So the source’s soft delete, its other filters and its policies hold inside the view, under the caller’s context, on every engine.

Each column is typed by the query. A group or a selected field is the source’s column. A $count is a number; $sum, $min and $max take the type of the column they read, and $avg is a number, each | null since it is NULL over no rows.

A find view is keyed by its source’s key where it selects it. An aggregate view is keyed by its $group columns where none can be NULL, since NULL groups are not unique. A keyed view is read by id (findOneById(CustomerTotals, 7)) and joined by a to-one; any other has no key, as a read-only entity without one.

A column read off a key holds that key: filtering by it compares keys, and on MongoDB it reads back as the string an ObjectId is, as the source column does.

A view is read-only. A write to one is a compile error, and refused at run time on every engine; over an API its wire takes reads alone. Its sections are relations, filters and policies, each chained once as on defineEntity, and indexes on a materialized one.

A plain view has no rows of its own, so what needs them is refused by name:

  • $lock, and estimatedCount: count it instead.
  • $text where the engine’s search reads an index of the table (MySQL, MariaDB, SQLite, MongoDB). The Postgres family searches the view’s columns themselves.

A vector sort needs no index: on MongoDB the distance is computed over the view’s rows.

materialized: true keeps a view as a table of its own, read from its rows rather than by its query: an expensive aggregate read often, at the cost of rows as fresh as its last refresh. Its table is a real one, so a BI tool, a SQL client or another app reads it by its name; a plain view exists only in UQL’s reads.

export const CustomerTotalsKept = defineView({
name: 'CustomerTotalsKept',
from: () => Order,
aggregate: {
$group: { customerId: true },
$select: { spent: { $sum: { total: true } } },
},
materialized: true,
}).indexes((row, index) => [index([row.spent])]);
await pool.refreshView(CustomerTotalsKept);
  • Migrations create its table and fill it, so it never reads empty after a deploy, and treat it as any table: indexed, diffed and checked for drift.
  • refreshView replaces its rows with its query’s in one atomic write, so a reader sees the old rows or the new, never an empty table. On MongoDB it is replaced at once with $out, which keeps its indexes.
  • When to refresh is yours: after the writes it summarizes, on a schedule, or inside the transaction that changed them, which it joins (but on MongoDB, where $out runs outside one).
  • A $sum column is as wide as a total needs, a BIGINT for whole numbers, and an $avg a double.
  • Only a materialized view is refreshed: anything else is a compile error. refreshView runs on the server alone, never over an API.

A refresh computes every row under no caller, past every policy, so the rows are the same whoever refreshes. So a materialized view over rows a policy or a tenant holds must declare policies of its own, which hold each read of its rows, or it is refused when first read:

import { $context, defineView, Entity, f, Field } from 'uql-orm';
@Entity()
export class Invoice {
@Field(f.number().autoIncrement()) id?: number;
@Field(f.number().tenant()) tenantId!: number;
@Field(f.number()) total!: number;
}
export const TenantTotals = defineView({
name: 'TenantTotals',
from: () => Invoice,
aggregate: {
$group: { tenantId: true },
$select: { billed: { $sum: { total: true } } },
},
materialized: true,
}).policies([{ allow: { tenantId: $context.tenantId } }]);

On a policies: 'native' pool the database holds its table too, so refreshView runs as a role that reads past row-level security, a superuser or one with BYPASSRLS, and is refused by name otherwise.

tableOf renders a view as the read does, its source’s filters and policies included:

import { refs, sql, tableOf } from 'uql-orm';
const totals = refs(CustomerTotals);
const rows = await pool.all(
sql`SELECT ${totals.spent} FROM ${tableOf(totals)} ORDER BY ${totals.spent} DESC`,
);

For SQL a find or an aggregate cannot express (a UNION, a window function), or a view another team owns, write the CREATE VIEW in a migration and map it as a read-only entity, its columns declared by hand. UQL reads it by name like a table, so the database’s own view runs, live for every tool, but no filter or policy of its sources holds it, and it runs on SQL engines alone.

A plain view has no table: sync, generated migrations and drift checks leave it out. A materialized view’s table is created and filled by them. No foreign key is created to or from either.