Reference · Tenants

with_tenant

signature
with_tenant(str, fn) -> any

What it does

Runs the function for a tenant, with its database, its live updates, and its rooms of channels and its media streams, and gives what the function gives. For code outside a request: a script, a scheduled job that loops over the tenants. Its database is made and migrated if there is none, so to sign a tenant up use new_tenant, which refuses a name that is taken. The name must be a valid tenant's name: lowercase letters, digits, - and _, at most 63, starting with a letter or a digit. See Many tenants.

Examples

in a program
schedule("@daily", () => {    for t in db.tenants() { with_tenant(t, () => db.exec("delete from tokens where expires < ?", now())) }})
print(with_tenant("acme", () => tenant()))print(with_tenant("acme", () => 1 + 1))
output
acme2

Edge cases

print(with_tenant("acme", () => err("no such plan")) ?? "defaulted")print(with_tenant("9lives", () => with_tenant("a-b_c", () => tenant())), tenant())print(with_tenant("x" | repeat(63), () => len(tenant())))
output
defaulteda-b_c null63

Errors

A name that cannot be a tenant's, a name that is not a string, and a second argument that is not a function are runtime errors, not error values. A runtime error inside the function is the call's.

this one fails
with_tenant("Acme Inc", () => 1)
output
line 1: `with_tenant`: "Acme Inc" cannot be a tenant's name (lowercase letters, digits, - and _)
this one fails
with_tenant("x" | repeat(64), () => 1)
output
line 1: `with_tenant`: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" cannot be a tenant's name (lowercase letters, digits, - and _)
this one fails
with_tenant("acme", 42)
output
line 1: `with_tenant` expects a function second, got int

Chaining

The name is the first argument, so a pipeline hands it in; db.tenants() lists the names to loop over:

print("acme" | with_tenant(() => tenant()))print(["acme", "beta"] | map((t) => with_tenant(t, () => upper(tenant()))))
output
acme["ACME", "BETA"]

See also

tenant, tenant_from, db.tenants, db.open, schedule

Thread
5Useful? Like it, or add to its thread below.

Thread 0 posts

On with_tenant(): questions, tips, corrections, and code that uses it.

No posts yet. The first one opens the thread.

    Edit this page on GitHub · every example's output was made by running it (tools/refcheck.mjs) · questions on Discord or r/quillo