one
TypeScript only
rel.one()Problem
Section titled “Problem”Extract a single tuple from a relation when you expect exactly one result.
Example: I want to get the user with a specific ID, expecting exactly one match.
Description
Section titled “Description”The one operator extracts a single tuple from a relation. It validates that the relation contains exactly one tuple and throws an error otherwise.
This is useful when:
- You’ve filtered to a unique result (e.g., by primary key)
- You expect exactly one match and want to fail fast if that assumption is wrong
Requirements
Section titled “Requirements”The relation must contain exactly one tuple. An error is thrown if the relation:
- Is empty (no tuples)
- Contains more than one tuple
Examples
Section titled “Examples”Extract by unique key
Section titled “Extract by unique key”const suppliers = Bmg([ { sid: "S1", name: "Smith", status: 20, city: "London" }, { sid: "S2", name: "Jones", status: 10, city: "Paris" },])
const smith = suppliers.restrict({ sid: "S1" }).one()// => { sid: "S1", name: "Smith", status: 20, city: "London" }Error on empty relation
Section titled “Error on empty relation”const result = suppliers.restrict({ sid: "S99" }).one()// Throws Error: Expected exactly one tuple, got 0Error on multiple tuples
Section titled “Error on multiple tuples”const result = suppliers.restrict({ city: "Paris" }).one()// Throws Error: Expected exactly one tuple, got 2 (if multiple Paris suppliers)Best practices
Section titled “Best practices”Use one() when you have a strong expectation of exactly one result:
// Good: fetching by unique IDconst user = users.restrict({ id: userId }).one()
// Good: after summarizing to a single resultconst total = orders.summarize([], { total: { op: 'sum', attr: 'amount' } }).one()
// Risky: when multiple matches are possible// Use .toArray() and handle the array insteadconst parisSuppliers = suppliers.restrict({ city: "Paris" }).toArray()Comparison with toArray
Section titled “Comparison with toArray”| Method | Returns | Use when |
|---|---|---|
one() | Single tuple | You expect exactly one result and want to fail otherwise |
toArray() | Array of tuples | You want all results or need to handle 0/many cases |