Enums
Give an attribute a fixed set of names, with a predicate, a setter, and scopes for each.
At a glance
| To | Write |
|---|---|
| store each name as itself | status: { enum: ["open", "in_progress", "closed"] } |
| store each name as a value | priority: { enum: { low: 0, normal: 1, high: 2 } } |
| check a record’s name | ticket.isOpen() |
| set it and save | ticket.saveAsClosed(), ticket.saveAsClosedOrThrow() |
| find records by name | Ticket.open(), Ticket.notClosed(), where({ status: … }) |
| read names with their stored values | Ticket.enumValues("priority") |
| keep two enums’ methods apart | prefix: true, suffix: true |
| report an unknown name as invalid | validate: true |
use the names a CHECK lists |
state: { enum: true } |
The Models
The examples use these Models. Their attributes come from their tables through the schema active-record schema generates, and each declares its enum in an override:
import { ApplicationRecord } from "./application-record";
export class Ticket extends ApplicationRecord {
static override attributes = {
status: { enum: ["open", "in_progress", "closed"] }, // stored as the names
priority: { enum: { low: 0, normal: 1, high: 2 } }, // stored as 0, 1, and 2
} as const;
}import { ApplicationRecord } from "./application-record";
export class Conversation extends ApplicationRecord {
static override attributes = {
status: { enum: ["active", "archived"], prefix: true }, // isStatusActive()
comments: { enum: ["active", "closed"], suffix: true }, // Conversation.activeComments()
} as const;
}import { ApplicationRecord } from "./application-record";
export class Survey extends ApplicationRecord {
static override attributes = {
answer: { enum: ["yes", "no"], validate: true }, // an inclusion error, not a TypeError
} as const;
}import { ApplicationRecord } from "./application-record";
export class Task extends ApplicationRecord {
static override attributes = { state: { enum: true } } as const; // the CHECK's names, with methods
}// Generated by `active-record schema` from migrations/ — don't edit.
// schema: 4c1c120c39f8
import { defineSchema, type ScopeStatic, type TableAttributes } from "@forestfuture/active-record";
import { d1 } from "@forestfuture/active-record/d1";
/** conversations — last changed by 0001_create_tables.sql */
export const conversations = {
id: { type: "string", null: false, generateId: true },
status: "string",
comments: "string",
} as const;
/** surveys — last changed by 0001_create_tables.sql */
export const surveys = {
id: { type: "string", null: false, generateId: true },
answer: "string",
} as const;
/** tasks — last changed by 0001_create_tables.sql */
export const tasks = {
id: { type: "string", null: false, generateId: true },
state: { type: "string", null: false, enum: ["open", "done"], scopes: false, instanceMethods: false },
} as const;
/** tickets — last changed by 0001_create_tables.sql */
export const tickets = {
id: { type: "string", null: false, generateId: true },
title: { type: "string", null: false },
status: "string",
priority: "integer",
} 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: {
conversations: { attributes: conversations, primaryKey: "id" },
surveys: { attributes: surveys, primaryKey: "id" },
tasks: { attributes: tasks, primaryKey: "id" },
tickets: { attributes: tickets, primaryKey: "id" },
},
models: { Conversation: "conversations", Survey: "surveys", Task: "tasks", Ticket: "tickets" },
enumScopes: {
Conversation: ["statusActive", "notStatusActive", "statusArchived", "notStatusArchived", "activeComments", "notActiveComments", "closedComments", "notClosedComments"],
Survey: ["yes", "notYes", "no", "notNo"],
Task: ["open", "notOpen", "done", "notDone"],
Ticket: ["open", "notOpen", "inProgress", "notInProgress", "closed", "notClosed", "low", "notLow", "normal", "notNormal", "high", "notHigh"],
},
});
declare module "../models/conversation" {
interface Conversation
extends TableAttributes<typeof conversations, (typeof Conversation)["attributes"]> {}
namespace Conversation {
export const statusActive: ScopeStatic<[]>;
export const notStatusActive: ScopeStatic<[]>;
export const statusArchived: ScopeStatic<[]>;
export const notStatusArchived: ScopeStatic<[]>;
export const activeComments: ScopeStatic<[]>;
export const notActiveComments: ScopeStatic<[]>;
export const closedComments: ScopeStatic<[]>;
export const notClosedComments: ScopeStatic<[]>;
}
}
declare module "../models/survey" {
interface Survey extends TableAttributes<typeof surveys, (typeof Survey)["attributes"]> {}
namespace Survey {
export const yes: ScopeStatic<[]>;
export const notYes: ScopeStatic<[]>;
export const no: ScopeStatic<[]>;
export const notNo: ScopeStatic<[]>;
}
}
declare module "../models/task" {
interface Task extends TableAttributes<typeof tasks, (typeof Task)["attributes"]> {}
namespace Task {
export const open: ScopeStatic<[]>;
export const notOpen: ScopeStatic<[]>;
export const done: ScopeStatic<[]>;
export const notDone: ScopeStatic<[]>;
}
}
declare module "../models/ticket" {
interface Ticket extends TableAttributes<typeof tickets, (typeof Ticket)["attributes"]> {}
namespace Ticket {
export const open: ScopeStatic<[]>;
export const notOpen: ScopeStatic<[]>;
export const inProgress: ScopeStatic<[]>;
export const notInProgress: ScopeStatic<[]>;
export const closed: ScopeStatic<[]>;
export const notClosed: ScopeStatic<[]>;
export const low: ScopeStatic<[]>;
export const notLow: ScopeStatic<[]>;
export const normal: ScopeStatic<[]>;
export const notNormal: ScopeStatic<[]>;
export const high: ScopeStatic<[]>;
export const notHigh: ScopeStatic<[]>;
}
}CREATE TABLE tickets (
id TEXT PRIMARY KEY NOT NULL,
title TEXT NOT NULL,
status TEXT,
priority INTEGER
);
CREATE TABLE conversations (
id TEXT PRIMARY KEY NOT NULL,
status TEXT,
comments TEXT
);
CREATE TABLE surveys (
id TEXT PRIMARY KEY NOT NULL,
answer TEXT
);
CREATE TABLE tasks (
id TEXT PRIMARY KEY NOT NULL,
state TEXT NOT NULL CHECK (state IN ('open', 'done'))
);CREATE TABLE tickets (
id UUID PRIMARY KEY,
title TEXT NOT NULL,
status TEXT,
priority INTEGER
);
CREATE TABLE conversations (
id UUID PRIMARY KEY,
status TEXT,
comments TEXT
);
CREATE TABLE surveys (
id UUID PRIMARY KEY,
answer TEXT
);
CREATE TABLE tasks (
id UUID PRIMARY KEY,
state TEXT NOT NULL CHECK (state IN ('open', 'done'))
);Declaring enums
Declare an enum with enum in an override, as Ticket does:
- The attribute’s type is the union of its names:
"open" | "in_progress" | "closed" | null. - A list of names stores each name as itself, as text.
- An object stores each name as the value you give it, an integer for an
INTEGERcolumn or text for aTEXTone.
Using an enum’s methods
Each name gets a predicate and a setter on records, and two scopes on the Model:
import { class TicketTicket } from "./models/ticket";
const const ticket: Ticket | nullticket = await class TicketTicket.const Ticket.high: <typeof Ticket>(this: typeof Ticket) => Relation<Ticket, ScopesOf<typeof Ticket>> & ScopeMethods<Ticket, ScopesOf<typeof Ticket>>high().notClosed: () => Relation<Ticket, ScopesOf<typeof Ticket>> & ScopeMethods<Ticket, ScopesOf<typeof Ticket>>notClosed().Relation<Ticket, ScopesOf<typeof Ticket>>.first(): Promise<Ticket | null>The first record by this Relation's order, or by primary key if it has none.first();
if (const ticket: Ticket | nullticket?.isOpen: () => booleanisOpen()) await const ticket: Ticketticket.saveAsClosed: () => Promise<boolean>saveAsClosed();
const const unfinished: numberunfinished = await class TicketTicket.where<typeof Ticket>(this: typeof Ticket, conditions: SafeSql | Conditions<Ticket>): Relation<Ticket, ScopesOf<typeof Ticket>> & ScopeMethods<Ticket, ScopesOf<typeof Ticket>>where({ status?: "open" | "in_progress" | "closed" | readonly ("open" | "in_progress" | "closed" | null)[] | Comparison<NonNullable<"open" | "in_progress" | "closed" | null>> | null | undefinedstatus: ["open", "in_progress"] }).Relation<Ticket, ScopesOf<typeof Ticket>>.count(attribute?: "status" | "priority" | "id" | "title" | undefined): Promise<number>The number of matching records, or of non-null values of `attribute`.count();| Method | Does |
|---|---|
ticket.isOpen() |
Whether status is "open" |
ticket.saveAsClosed(), ticket.saveAsClosedOrThrow() |
Sets status to "closed" and saves the record, with its other changes |
Ticket.open(), Ticket.notOpen() |
Scopes of the records whose status is, or isn’t, "open" |
- A name in snake_case reads in camelCase:
in_progressgivesisInProgress()andTicket.inProgress(). saveAsClosed()returnsfalsewhen the record is invalid, assavedoes, andsaveAsClosedOrThrow()throws.where,whereNot,pluck, and every write take and give names, one or a list.
Reading stored values
Read an enum’s names with their stored values with enumValues:
import { class TicketTicket } from "./models/ticket";
const const priorities: Readonly<{
readonly low: 0;
readonly normal: 1;
readonly high: 2;
}>
priorities = class TicketTicket.Model.enumValues<typeof Ticket, "priority">(this: typeof Ticket, attribute: "priority"): Readonly<{
readonly low: 0;
readonly normal: 1;
readonly high: 2;
}>
An enum's names, each with the value it's stored as, frozen (#340):
`Post.enumValues("status")` is `{ draft: "draft", published: "published" }`.enumValues("priority"); // { low: 0, normal: 1, high: 2 }Keeping names apart
Add a prefix or a suffix when two enums share a name, true for the attribute’s name or a word of your own, as Conversation does:
import { class ConversationConversation } from "./models/conversation";
const const conversation: Conversationconversation = await class ConversationConversation.const Conversation.activeComments: <typeof Conversation>(this: typeof Conversation) => Relation<Conversation, ScopesOf<typeof Conversation>> & ScopeMethods<Conversation, ScopesOf<typeof Conversation>>activeComments().Relation<Conversation, ScopesOf<typeof Conversation>>.firstOrThrow(): Promise<Conversation>Like `first`, but throws `RecordNotFound` instead of returning null.firstOrThrow();
const const live: booleanlive = const conversation: Conversationconversation.isStatusActive: () => booleanisStatusActive();- A method name that’s taken, by another enum, an attribute, a record method, or a static, throws
InvalidModelwhen the Model is first used, andactive-record schemareports it. - So does a name TypeScript can’t declare, such as
in-progressornew. Map a readable name to the stored value instead:enum: { inProgress: "in-progress" }. - To leave an enum’s methods out, declare it with
scopes: falseorinstanceMethods: false.
Reading and assigning other values
Assigning a value that isn’t one of an enum’s names, or one of its stored values, throws TypeError, and a condition with one matches nothing:
- A stored value that the enum doesn’t list reads as
null, so rows written by a newer deploy don’t break an older one. This holds even for an attribute declarednull: false. - To rename a name without touching stored rows, map the new name to the old value:
enum: { drafted: "draft" }. Otherwise, migrate the rows in the same deploy.
Validating names
Declare an enum with validate: true, as Survey does, to report an unknown value as a validation error instead of throwing:
import { class SurveySurvey } from "./models/survey";
const const survey: Surveysurvey = class SurveySurvey.build<typeof Survey>(this: typeof Survey, attributes?: Partial<AttributeProperties<OverriddenSpecs<{
readonly id: {
readonly type: "string";
readonly null: false;
readonly generateId: true;
};
readonly answer: "string";
}, {
readonly answer: {
readonly enum: readonly ["yes", "no"];
readonly validate: true;
};
}>>> | undefined, init?: ((record: Survey) => void) | undefined): Survey
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(var JSON: JSONAn intrinsic object that provides functions to convert JavaScript values to and from the JavaScript Object Notation (JSON) format.JSON.JSON.parse(text: string, reviver?: (this: any, key: string, value: any) => any): anyConverts a JavaScript Object Notation (JSON) string into an object.parse('{ "answer": "maybe" }'));
await const survey: Surveysurvey.Model.save(options?: SaveOptions): Promise<boolean>Inserts a new record or updates a persisted one; `false` if it's invalid, a callback aborted,
or a record it destroys refused (#37). `context` validates it in that context (`"signup"`), as
`isValid(context)` does.save(); // false
var console: Consoleconsole.Console.log(...data: any[]): voidThe **`console.log()`** static method outputs a message to the console.
[MDN Reference](https://developer.mozilla.org/docs/Web/API/console/log_static)log(const survey: Surveysurvey.Model.errors: ErrorsThe errors from the last validation run.errors.Errors.fullMessages(): string[]Every message with its attribute's human name first: "Email can't be blank".fullMessages()); // ["Answer is not included in the list"]A survey with no answer is invalid too, unless you declare validate: { allowNull: true }.
Reading enums from the database
active-record schema writes the names a database restricts a column to into the generated schema, with the enum’s methods off. A Postgres enum type does it, and so does a CHECK such as the tasks table’s. Turn the methods on with enum: true, as Task does:
import { class TaskTask } from "./models/task";
const const task: Tasktask = await class TaskTask.const Task.open: <typeof Task>(this: typeof Task) => Relation<Task, ScopesOf<typeof Task>> & ScopeMethods<Task, ScopesOf<typeof Task>>open().Relation<Task, ScopesOf<typeof Task>>.firstOrThrow(): Promise<Task>Like `first`, but throws `RecordNotFound` instead of returning null.firstOrThrow();
await const task: Tasktask.saveAsDone: () => Promise<boolean>saveAsDone(); // task.isDone() is now true- The attribute’s type is
"open" | "done", assigning any other value throwsTypeError, andenumValuesworks as for any enum. enum: truekeeps the database’s names, so a name a later migration adds gets its methods the next time you runactive-record schema.- A
scopes: falseorinstanceMethods: falsebeside it still leaves those out, andscopes: trueorinstanceMethods: truealone turns on one kind. Names that clash only matter once their methods are on, and you fix them as in Keeping names apart. - To keep the column a plain string, override it with
enum: false. A list of your own, such asenum: ["open", "done", "archived"], replaces the database’s, with its methods on.