Skip to content
Active Record
Esc
↑↓navigate↵open⌘Jpreview
On this page

Scopes

Name a reusable part of a query, or narrow every query on a Model with a default scope.

At a glance

To Write
declare a scope static published = this.scope((q) => q.whereNot({ … }))
declare one that takes arguments static publishedSince = this.scope((q, since: Date) => q.where({ … }))
call it Post.published(), or on any Relation: Post.where(…).published()
narrow every query static { this.defaultScope((q) => q.where({ isAvailable: true })) }
leave the default scope out Product.unscoped()

The Models

The examples use these Models, whose attributes come from their tables through the schema active-record schema generates:

import { gte } from "@forestfuture/active-record";
import { ApplicationRecord } from "./application-record";

export class Post extends ApplicationRecord {
  static published = this.scope((q) => q.whereNot({ publishedAt: null }));
  static publishedSince = this.scope((q, since: Date) => q.where({ publishedAt: gte(since) }));
}
import { ApplicationRecord } from "./application-record";

export class Product extends ApplicationRecord {
  static {
    this.defaultScope((q) => q.where({ isAvailable: true }));
  }
}
// Generated by `active-record schema` from migrations/ — don't edit.
// schema: e9579b7b05ee

import { defineSchema, type TableAttributes } from "@forestfuture/active-record";
import { d1 } from "@forestfuture/active-record/d1";

/** posts — last changed by 0001_create_tables.sql */
export const posts = {
  id: { type: "string", null: false, generateId: true },
  title: { type: "string", null: false },
  publishedAt: "datetime",
} as const;

/** products — last changed by 0001_create_tables.sql */
export const products = {
  id: { type: "string", null: false, generateId: true },
  name: { type: "string", null: false },
  isAvailable: { type: "boolean", null: false },
} as const;

/** The database's adapter and binding, its tables (with their primary keys), and the Models built on them. */
export const schema = defineSchema({
  adapter: d1({ binding: "DB" }),
  tables: {
    posts: { attributes: posts, primaryKey: "id" },
    products: { attributes: products, primaryKey: "id" },
  },
  models: { Post: "posts", Product: "products" },
});

declare module "../models/post" {
  interface Post extends TableAttributes<typeof posts, (typeof Post)["attributes"]> {}
}

declare module "../models/product" {
  interface Product extends TableAttributes<typeof products, (typeof Product)["attributes"]> {}
}
CREATE TABLE posts (
  id TEXT PRIMARY KEY NOT NULL,
  title TEXT NOT NULL,
  published_at DATETIME
);
CREATE TABLE products (
  id TEXT PRIMARY KEY NOT NULL,
  name TEXT NOT NULL,
  is_available BOOLEAN NOT NULL
);
CREATE TABLE posts (
  id UUID PRIMARY KEY,
  title TEXT NOT NULL,
  published_at TIMESTAMPTZ
);
CREATE TABLE products (
  id UUID PRIMARY KEY,
  name TEXT NOT NULL,
  is_available BOOLEAN NOT NULL
);

Defining scopes

Declare a scope as a static that receives the Relation, plus any arguments, and returns a narrower one:

import { gte } from "@forestfuture/active-record";
import { ApplicationRecord } from "./application-record";

export class Post extends ApplicationRecord {
  static published = this.scope((q) => q.whereNot({ publishedAt: null }));
  static publishedSince = this.scope((q, since: Date) => q.where({ publishedAt: gte(since) }));
}

Calling scopes

Call a scope as a static, or on any Relation of the Model:

import { class PostPost } from "./models/post";

const const published: Post[]published = await class PostPost.Post.published: <typeof Post>(this: typeof Post) => Relation<Post, ScopesOf<typeof Post>> & ScopeMethods<Post, ScopesOf<typeof Post>>published().Relation<Post, ScopesOf<typeof Post>>.toArray(): Promise<Post[]>toArray();
const const thisYear: Post[]thisYear = await class PostPost.Post.published: <typeof Post>(this: typeof Post) => Relation<Post, ScopesOf<typeof Post>> & ScopeMethods<Post, ScopesOf<typeof Post>>published().publishedSince: (since: Date) => Relation<Post, ScopesOf<typeof Post>> & ScopeMethods<Post, ScopesOf<typeof Post>>publishedSince(new 
var Date: DateConstructor
new (value: number | string | Date) => Date (+4 overloads)
Date
("2026-01-01")).Relation<Post, ScopesOf<typeof Post>>.toArray(): Promise<Post[]>toArray();
const const hellos: numberhellos = await class PostPost.where<typeof Post>(this: typeof Post, conditions: SafeSql | Conditions<Post>): Relation<Post, ScopesOf<typeof Post>> & ScopeMethods<Post, ScopesOf<typeof Post>>where({ title?: string | readonly string[] | Comparison<string> | undefinedtitle: "Hello" }).published: () => Relation<Post, ScopesOf<typeof Post>> & ScopeMethods<Post, ScopesOf<typeof Post>>published().Relation<Post, ScopesOf<typeof Post>>.count(attribute?: "id" | "title" | "publishedAt" | undefined): Promise<number>
The number of matching records, or of non-null values of `attribute`.
count
(); // on any Relation
  • Its arguments, and anything it computes such as new Date(), are evaluated when you call it.
  • Scopes are inherited, including those on your app’s base class (Shared behavior). A subclass can replace one with static override published = this.scope(…).
  • A scope can’t reuse a Relation method’s name (where, count) or a Model static’s (validates, scope, all).
  • Inside a scope, q has every Relation method but not the Model’s other scopes. Share logic between scopes with a plain function.

An enum gives its Model a scope for each name, and a not… scope: Ticket.open() and Ticket.notOpen(). Conditions take its names, one or a list: Ticket.where({ status: ["open", "in_progress"] }).

Narrowing every query

Declare a default scope in the class’s static {} block, as Product does, to narrow every query on the Model:

import { class ProductProduct } from "./models/product";

const const listed: Product[]listed = await class ProductProduct.order<typeof Product>(this: typeof Product, spec: SafeSql | OrderSpec<Product>): Relation<Product, ScopesOf<typeof Product>>
Sorts by each key in turn (`{ createdAt: "desc" }`, or `{ role: { direction: "asc", nulls: "last" } }`), or by an `sql` fragment expression. Repeated calls append.
order
({
name?: OrderDirection | {
    direction: OrderDirection;
    nulls?: NullsPlacement;
} | undefined
name
: "asc" }).Relation<Product, ScopesOf<typeof Product>>.toArray(): Promise<Product[]>toArray(); // available products only
const const draft: Productdraft = class ProductProduct.
build<typeof Product>(this: typeof Product, attributes?: Partial<AttributeProperties<OverriddenSpecs<{
    readonly id: {
        readonly type: "string";
        readonly null: false;
        readonly generateId: true;
    };
    readonly name: {
        readonly type: "string";
        readonly null: false;
    };
    readonly isAvailable: {
        readonly type: "boolean";
        readonly null: false;
    };
}, Readonly<Record<string, false | AttributeOverride>> | undefined>>> | undefined, init?: ((record: Product) => void) | undefined): Product
A new, unsaved record of this Relation's Model, handed to `init` first if it's given. Nothing awaits `init`, so one that returns a promise throws `TypeError`. Built through a hasMany, it joins the association, and saving the owner saves it too (autosave).
build
({ name?: string | undefinedname: "Pen" }); // isAvailable: true, from the default scope
  • New records take its conditions’ values.
  • It applies to everything that queries the Model: find, count, updateAll, deleteAll, its scopes, and associations that read it, preloads included.
  • reload, uniqueness validation, and a record’s own save and destroy ignore it, since they work by primary key.
  • insert, insertAll, upsert, and upsertAll write its conditions’ values over the values you give. build and create use the values you give.
  • Several default scopes all apply. A subclass adds its own to its parent’s.
  • An order in a default scope is the Relation’s order. reorder replaces it.
  • rewhere replaces its condition on an attribute, and unscope drops its parts.

Leaving the default scope out

Start from unscoped() to leave the default scope out:

import { class ProductProduct } from "./models/product";

const const everything: Product[]everything = await class ProductProduct.Model.unscoped<typeof Product>(this: typeof Product): Relation<Product, ScopesOf<typeof Product>>
All of this Model's records without its default scopes (#25), on the current database. Only a static: a Relation keeps what it has.
unscoped
().Relation<Product, ScopesOf<typeof Product>>.toArray(): Promise<Product[]>toArray(); // available or not

unscoped() is a Model static only. With a database you hold, call it inside withDatabase.

Last updated on