Reference · Database

db.tenants

signature
db.tenants() -> list | error(str)

What it does

The names of the tenants that have a database, when the program's database is one per tenant: db.open("data/{tenant}.db") lists the SQLite files there are, a ?schema=t_{tenant} target the PostgreSQL schemas, mysql://host/app_{tenant} the MySQL databases. A tenant's database is made, and migrated, the first time code runs for it with with_tenant(name, ...), as when signing the tenant up.

Examples

db.open("data/{tenant}.db")print(db.tenants())with_tenant("acme", () => db.exec("create table settings (plan text)"))with_tenant("beta", () => db.exec("create table settings (plan text)"))print(db.tenants())print(db.tenants() | map((t) => with_tenant(t, () => db.exec("insert into settings values (?)", "free"))))
output
[]["acme", "beta"][{ changes: 1, last_id: 1 }, { changes: 1, last_id: 1 }]

Edge cases

db.open("data/{tenant}.db")print(db.tenants())print(db.exec("create table t (a)"))with_tenant("zed", () => db.query("select 1"))with_tenant("acme", () => db.query("select 1"))print(db.tenants(), with_tenant("acme", () => db.tenants()))
output
[]err("db: the database is one per tenant ({tenant} in its target), and this code runs for none: see tenant_from and with_tenant")["acme", "zed"] ["acme", "zed"]

Errors

A program whose database is not one per tenant, or one where a function names each tenant's database, gets a runtime error.

this one fails
db.open("app.db")print(db.tenants())
output
line 2: `db.tenants` needs a database per tenant: db.open("data/{tenant}.db")

Chaining

A job for every tenant:

db.open("data/{tenant}.db")write_file("migrations/001_s.sql", "create table settings (plan text)")db.migrate()with_tenant("acme", () => db.exec("insert into settings values ('pro')"))with_tenant("beta", () => db.exec("insert into settings values ('free')"))print(db.tenants() | map((t) => [t, with_tenant(t, () => db.one("select plan from settings").plan)]))
output
[["acme", "pro"], ["beta", "free"]]

See also

db.tenant_exists, with_tenant, tenant, tenant_from, db.open, db.migrate

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

Thread 0 posts

On db.tenants(): 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