@protobase/cli 0.117.6 → 0.118.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli/package.js +1 -1
- package/dist/doctor/lookup-issues.js +23 -0
- package/dist/doctor/lookup-models.js +35 -0
- package/dist/doctor/read-shapes.js +15 -2
- package/dist/doctor/run-without-database.js +4 -2
- package/dist/doctor/run.js +8 -4
- package/package.json +8 -8
- package/skills/protobase/SKILL.md +1 -1
- package/skills/protobase/references/features/data-model.md +1 -0
- package/skills/protobase/references/reference/api.md +3 -2
- package/skills/protobase/references/reference/cli.md +2 -2
- package/skills/protobase/references/reference/client.md +1 -1
- package/skills/protobase/references/reference/data-config.md +65 -0
- package/skills/protobase/references/reference/ui-config.md +2 -0
package/dist/cli/package.js
CHANGED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { tableKey } from "../db/model.js";
|
|
2
|
+
import { hasUniqueIndexOn } from "../db/keys.js";
|
|
3
|
+
//#region src/doctor/lookup-issues.ts
|
|
4
|
+
const quoteIdent = (name) => `"${name.replaceAll("\"", "\"\"")}"`;
|
|
5
|
+
/**
|
|
6
|
+
* A lookup field that reads the one record of another resource pointing at each record needs a unique index on that
|
|
7
|
+
* relation: without one a record may have several, and every read of the field fails.
|
|
8
|
+
*/
|
|
9
|
+
const lookupIssues = (model, models, tables) => Object.values(model.lookups ?? {}).flatMap((field) => {
|
|
10
|
+
const { from, via } = field.lookup;
|
|
11
|
+
const linked = from === void 0 ? void 0 : models.find((each) => each.name === from);
|
|
12
|
+
const column = linked && Object.hasOwn(linked.fields, via) ? linked.fields[via].column : void 0;
|
|
13
|
+
const table = linked && tables.find((each) => each.schema === (linked.table.schema ?? "public") && each.name === linked.table.name);
|
|
14
|
+
if (!column || !table || table.kind === "view" || hasUniqueIndexOn(table, [column])) return [];
|
|
15
|
+
return [{
|
|
16
|
+
severity: "error",
|
|
17
|
+
resource: model.name,
|
|
18
|
+
message: `${field.name}: looks up the one ${from} record whose "${via}" points at each record, but no unique index on ${tableKey(table)} (${column}) makes it one, so a read fails once a record has two`,
|
|
19
|
+
suggestion: `create unique index on ${quoteIdent(table.schema)}.${quoteIdent(table.name)} (${quoteIdent(column)});`
|
|
20
|
+
}];
|
|
21
|
+
});
|
|
22
|
+
//#endregion
|
|
23
|
+
export { lookupIssues };
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import { withLookupRead } from "@protobase/query";
|
|
2
|
+
import { lookupLink } from "@protobase/schema/internal";
|
|
3
|
+
//#region src/doctor/lookup-models.ts
|
|
4
|
+
/**
|
|
5
|
+
* The models as the scan guard judges a read of them: each with its lookup fields among its fields, read in no
|
|
6
|
+
* caller's scope, since doctor judges what any caller may ask. A lookup whose linked record cannot be found is left
|
|
7
|
+
* out; the server's startup check names it.
|
|
8
|
+
*/
|
|
9
|
+
const lookupReadModels = (models) => {
|
|
10
|
+
const byName = new Map(models.map((model) => [model.name, model]));
|
|
11
|
+
return models.map((model) => {
|
|
12
|
+
const { lookups, ...rest } = model;
|
|
13
|
+
if (!lookups) return model;
|
|
14
|
+
const read = Object.values(lookups).flatMap((field) => {
|
|
15
|
+
const link = lookupLink(model, field, (name) => byName.get(name));
|
|
16
|
+
return link ? [[field.name, withLookupRead(field, {
|
|
17
|
+
model: link.linked,
|
|
18
|
+
scope: {},
|
|
19
|
+
conditions: [],
|
|
20
|
+
value: link.value,
|
|
21
|
+
match: link.match,
|
|
22
|
+
link: link.link
|
|
23
|
+
})]] : [];
|
|
24
|
+
});
|
|
25
|
+
return {
|
|
26
|
+
...rest,
|
|
27
|
+
fields: {
|
|
28
|
+
...model.fields,
|
|
29
|
+
...Object.fromEntries(read)
|
|
30
|
+
}
|
|
31
|
+
};
|
|
32
|
+
});
|
|
33
|
+
};
|
|
34
|
+
//#endregion
|
|
35
|
+
export { lookupReadModels };
|
|
@@ -1,18 +1,31 @@
|
|
|
1
1
|
import { viewShapes } from "./view-shapes.js";
|
|
2
2
|
import { pageShapes } from "./page-shapes.js";
|
|
3
3
|
import { fieldShapes, lookupShapes } from "./field-shapes.js";
|
|
4
|
+
import { lookupQueries } from "@protobase/query";
|
|
4
5
|
//#region src/doctor/read-shapes.ts
|
|
6
|
+
const linkedShapes = (shape, byName) => {
|
|
7
|
+
const model = byName[shape.resource];
|
|
8
|
+
if (!model) return [];
|
|
9
|
+
return lookupQueries(model, shape.query).map(({ field, read, query }) => ({
|
|
10
|
+
resource: read.model.name,
|
|
11
|
+
request: shape.request,
|
|
12
|
+
from: `${shape.from}, through the lookup field "${field}"`,
|
|
13
|
+
query
|
|
14
|
+
}));
|
|
15
|
+
};
|
|
5
16
|
/**
|
|
6
17
|
* Every read the API takes of the resources and the app makes of them, which the scan guard judges when it runs: what
|
|
7
|
-
* the fields allow, the relations' lookups, each view's pages and each composed page's blocks
|
|
18
|
+
* the fields allow, the relations' lookups, each view's pages and each composed page's blocks, and the linked records
|
|
19
|
+
* each of them reads through a lookup field. `models` have their lookup fields among their fields (`lookupReadModels`).
|
|
8
20
|
*/
|
|
9
21
|
const readShapes = ({ models, views, pages }) => {
|
|
10
22
|
const byName = Object.fromEntries(models.map((model) => [model.name, model]));
|
|
11
|
-
|
|
23
|
+
const shapes = [
|
|
12
24
|
...models.flatMap((model) => [...fieldShapes(model), ...lookupShapes(model, byName)]),
|
|
13
25
|
...views.flatMap((view) => viewShapes(view, byName)),
|
|
14
26
|
...pages.flatMap((page) => pageShapes(page, byName, views))
|
|
15
27
|
];
|
|
28
|
+
return [...shapes, ...shapes.flatMap((shape) => linkedShapes(shape, byName))];
|
|
16
29
|
};
|
|
17
30
|
//#endregion
|
|
18
31
|
export { readShapes };
|
|
@@ -3,6 +3,7 @@ import { userTablesOn } from "../config/user-tables-config.js";
|
|
|
3
3
|
import { readMigrationSql } from "./migration-sql.js";
|
|
4
4
|
import { captureFileIssues } from "./capture-files.js";
|
|
5
5
|
import { formatIssue, loadDoctorProject, unplannedNotes } from "./project.js";
|
|
6
|
+
import { lookupReadModels } from "./lookup-models.js";
|
|
6
7
|
import { readShapes } from "./read-shapes.js";
|
|
7
8
|
import { relationIssues } from "./relation-issues.js";
|
|
8
9
|
import { sortIssues } from "./sort-issues.js";
|
|
@@ -19,14 +20,15 @@ const runDoctorWithoutDatabase = async (options, out) => {
|
|
|
19
20
|
const project = await loadDoctorProject(options.configDir, options.projectDir);
|
|
20
21
|
const { config, source, builtIn } = project;
|
|
21
22
|
const models = [...builtIn.models, ...config.models];
|
|
23
|
+
const read = lookupReadModels(models);
|
|
22
24
|
const shapes = readShapes({
|
|
23
|
-
models,
|
|
25
|
+
models: read,
|
|
24
26
|
views: [...builtIn.views, ...config.views],
|
|
25
27
|
pages: config.pages
|
|
26
28
|
});
|
|
27
29
|
const served = configExports(await projectResources(source)).resources.map((resource) => resource.toModel());
|
|
28
30
|
const capture = captureFileIssues(served, source.events, await readMigrationSql(options.projectDir) ?? "");
|
|
29
|
-
const issues = [...models.flatMap((model) => [...relationIssues(model, models), ...sortIssues(
|
|
31
|
+
const issues = [...models.flatMap((model, i) => [...relationIssues(model, models), ...sortIssues(read[i], shapes)]), ...capture.issues];
|
|
30
32
|
for (const issue of issues) out(formatIssue(issue));
|
|
31
33
|
for (const note of unplannedNotes(project, models)) out(note);
|
|
32
34
|
const errors = issues.filter((i) => i.severity === "error").length;
|
package/dist/doctor/run.js
CHANGED
|
@@ -4,6 +4,7 @@ import { connect } from "../db/connect.js";
|
|
|
4
4
|
import { introspect } from "../db/introspect.js";
|
|
5
5
|
import { builtInIndexIssues } from "./built-in-models.js";
|
|
6
6
|
import { formatIssue, loadDoctorProject, unplannedNotes } from "./project.js";
|
|
7
|
+
import { lookupReadModels } from "./lookup-models.js";
|
|
7
8
|
import { readShapes } from "./read-shapes.js";
|
|
8
9
|
import { relationIssues } from "./relation-issues.js";
|
|
9
10
|
import { sortIssues } from "./sort-issues.js";
|
|
@@ -11,6 +12,7 @@ import { checkServerStartup } from "./startup.js";
|
|
|
11
12
|
import { readOnlyDb } from "../db/read-only-db.js";
|
|
12
13
|
import { checkResource } from "./check.js";
|
|
13
14
|
import { fileIndexIssues, indexIssues } from "./index-issues.js";
|
|
15
|
+
import { lookupIssues } from "./lookup-issues.js";
|
|
14
16
|
import { userTableModels } from "./user-table-models.js";
|
|
15
17
|
import pg from "pg";
|
|
16
18
|
import { tableIndexes } from "@protobase/query";
|
|
@@ -30,19 +32,21 @@ const runDoctor = async (options, out) => {
|
|
|
30
32
|
...config.models,
|
|
31
33
|
...userTables.models
|
|
32
34
|
];
|
|
35
|
+
const read = lookupReadModels(models);
|
|
33
36
|
const shapes = readShapes({
|
|
34
|
-
models,
|
|
37
|
+
models: read,
|
|
35
38
|
views: [...builtIn.views, ...config.views],
|
|
36
39
|
pages: config.pages
|
|
37
40
|
});
|
|
38
|
-
const indexes = await Promise.all(models.map(async (model) => {
|
|
41
|
+
const indexes = await Promise.all(models.map(async (model, i) => {
|
|
39
42
|
const table = await tableIndexes(db, model);
|
|
40
|
-
return [...indexIssues(
|
|
43
|
+
return [...indexIssues(read[i], table, shapes), ...fileIndexIssues(model, table)];
|
|
41
44
|
})).then((found) => found.map((issues, i) => i < builtIn.models.length ? builtInIndexIssues(issues) : issues)).finally(() => db.destroy());
|
|
42
45
|
const issues = [...userTables.issues, ...models.flatMap((model, i) => [
|
|
43
46
|
...checkResource(model, tables),
|
|
44
47
|
...relationIssues(model, models),
|
|
45
|
-
...
|
|
48
|
+
...lookupIssues(model, models, tables),
|
|
49
|
+
...sortIssues(read[i], shapes),
|
|
46
50
|
...indexes[i]
|
|
47
51
|
])];
|
|
48
52
|
for (const issue of issues) out(formatIssue(issue));
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@protobase/cli",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.118.0",
|
|
4
4
|
"description": "The protobase command: scaffold, doctor, dev, build and serve a Protobase project.",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"repository": {
|
|
@@ -43,13 +43,13 @@
|
|
|
43
43
|
"dependencies": {
|
|
44
44
|
"@better-auth/core": "^1.7.12",
|
|
45
45
|
"@hono/node-server": "^2.1.3",
|
|
46
|
-
"@protobase/config": "0.
|
|
47
|
-
"@protobase/layout": "0.
|
|
48
|
-
"@protobase/query": "0.
|
|
49
|
-
"@protobase/schema": "0.
|
|
50
|
-
"@protobase/server": "0.
|
|
51
|
-
"@protobase/ui": "0.
|
|
52
|
-
"@protobase/workflows": "0.
|
|
46
|
+
"@protobase/config": "0.118.0",
|
|
47
|
+
"@protobase/layout": "0.118.0",
|
|
48
|
+
"@protobase/query": "0.118.0",
|
|
49
|
+
"@protobase/schema": "0.118.0",
|
|
50
|
+
"@protobase/server": "0.118.0",
|
|
51
|
+
"@protobase/ui": "0.118.0",
|
|
52
|
+
"@protobase/workflows": "0.118.0",
|
|
53
53
|
"@react-email/render": "^2.1.0",
|
|
54
54
|
"@scalar/hono-api-reference": "^0.12.10",
|
|
55
55
|
"@sentry/vite-plugin": "^11.10.0",
|
|
@@ -71,7 +71,7 @@ Reference:
|
|
|
71
71
|
- When setting the assistant, maps or plugins in the config → read [Admin app options](references/reference/config/admin-app.md)
|
|
72
72
|
- When setting `jobs`, `events`, `history`, `webhooks` or `notifications` in the config → read [Jobs and events options](references/reference/config/jobs-and-events.md)
|
|
73
73
|
- When setting `files` in the config → read [Files options](references/reference/config/files.md)
|
|
74
|
-
- When defining resources, fields, keys, relations, rollups, formulas and validation → read [Data config](references/reference/data-config.md)
|
|
74
|
+
- When defining resources, fields, keys, relations, rollups, formulas, lookups and validation → read [Data config](references/reference/data-config.md)
|
|
75
75
|
- When defining views, columns, filters, charts, related records and actions → read [UI config](references/reference/ui-config.md)
|
|
76
76
|
- When asking how the packages fit together → read [Architecture](references/reference/architecture.md)
|
|
77
77
|
- When calling or changing the REST API, its filters, writes and errors → read [REST API](references/reference/api.md)
|
|
@@ -17,6 +17,7 @@ Describe the tables of an existing Postgres database as resources, with their fi
|
|
|
17
17
|
- [Opening an existing record](../reference/data-config.md#opening-an-existing-record): A create that repeats a record's unique values, such as a direct message with the same people, opens that record instead of failing, for whoever may read it; anyone else gets the usual conflict, which does not say the record exists.
|
|
18
18
|
- [Record validation](../reference/data-config.md#resource): A rule over the whole record runs on every create and update and reports each problem on the field it concerns.
|
|
19
19
|
- [Rollups and formulas](../reference/data-config.md#rollups-and-formulas) (beta): Fields that hold counts, sums, averages, minimums or maximums of related records, or values calculated from the record's own numbers, kept current by the database.
|
|
20
|
+
- [Lookups](../reference/data-config.md#lookups) (beta): A field can show a field of a linked record, such as an order's customer name, read with the record in the same query and only as far as the caller may read the linked record.
|
|
20
21
|
- [Time rollups](../reference/data-config.md#time-rollups) (in development): A large events table gets an hourly or daily rollup table that the app's migrations create, so charts over months of millions of rows can read a few thousand rows instead.
|
|
21
22
|
- [Sensitive fields](../reference/data-config.md#sensitive-fields): Values such as bank account numbers are left out of every response and shown masked. A permitted user reveals one value at a time, and each reveal is audited.
|
|
22
23
|
- [Recent strong sign-in](../reference/data-config.md#recent-strong-sign-in): A sensitive field can ask for a passkey or a second step in the last minutes before it is revealed, or an emailed code for an account with neither. The record page asks the person to confirm it's them, then shows it.
|
|
@@ -51,6 +51,7 @@ Under `/api/v1`:
|
|
|
51
51
|
| `GET /{resource}:aggregate?group_by=&sum=&average=&maximum=&filter=` | `{ group_by, groups: [{ value, count, sum }] }`: the records the whole filter finds, per value of `group_by`, each with its count and, with `sum`, `average` or `maximum` (one of them), that of a numeric field, `null` when no record of the group has one. Values come largest first, the first `limit` (100 by default, at most 1,000), with `label` as in `:facets`. A date or timestamp `group_by` is bucketed like `:series` instead (`granularity` `minute`, `5_minutes`, `15_minutes` or `hour` to `year`, `range` or `from` and `to`, `time_zone`), empty buckets included, and each `value` is the bucket's start; the response adds `granularity` and `time_zone`. With `split_by` (a filterable field of values), a date `group_by` also splits each bucket: the response adds `split_by` and `splits` (the `split_limit` largest values over the range, 8 by default and at most 100, ranked by the sum, else by count; `split_label` names a relation's values), and each group lists its `splits` with their count and sum, average or maximum. Unlike `:facets`, the filter's terms on `group_by` apply too, so the groups add up to what the filter finds. A values `group_by` takes [`limit_per=<field>:<n>`](#first-rows-per-value): the first `n` groups per value of `field`, each with that value as `per`, by `per`, with `limit` capping all groups together; a date `group_by` refuses it |
|
|
52
52
|
| `GET /{resource}:series?field=&range=&granularity=&time_zone=&filter=` | `range` is `1h`, `24h`, `7d`, `30d`, `90d`, `1y`, `all`, or `from` and `to` (ISO); `granularity` `minute`, `5_minutes`, `15_minutes`, `hour`, `day` (the default), `week` or `month`. Buckets of minutes start on the clock's multiples of them |
|
|
53
53
|
| `GET /{resource}:histogram?field=&buckets=&filter=` | equal-width buckets of a numeric field |
|
|
54
|
+
| `POST /{resource}:batchAggregates` | `{ facets: [...], histograms: [...], series: [...] }`, each a list of reads with the parameters of `:facets`, `:histogram` and `:series` (at most 100 of each), answered with lists of what those methods answer, in the same order. Reads that filter the same rows, a facet's own terms left out, share their scans of the table: one for the bounds of every histogram, and one per four facets, histograms of several buckets and series. Each keeps its method's access, scan guard and labels, and a read that fails fails the request. A list page sends its filters' counts and its chart this way |
|
|
54
55
|
| `GET /{resource}:map?latitude=&longitude=&zoom=&filter=&order_by=&fields=&labels=&photos=&photos_order_by=` | the records in a map's view, the bounding box being in `filter` (`lat >= 51.9 AND lat <= 52.1 AND lng >= 4.2 AND lng <= 4.5`), as `{ items, buckets, total_size }`; see [Maps](#maps) |
|
|
55
56
|
| `GET /{resource}:seek?position=&order_by=&filter=&page_size=&fields=&labels=&photos=&photos_order_by=` | the page at a row position (scrollbar jumps), with `next_page_token` and `prev_page_token`; same items as a list |
|
|
56
57
|
| `GET /api/meta` | resource, view and page models (fields carry `default`: `{ value }` or `{ db: true }`) and the caller's `permissions`; the `ETag` hashes both, so it differs per user; `If-None-Match` gives `304` |
|
|
@@ -109,7 +110,7 @@ The photos are read as the caller lists that resource, in one query for the whol
|
|
|
109
110
|
Access is resolved once per request and resource ([`resolveAccess`](https://docs.protobase.net/api/schema/functions/resolveaccess/), see [Login with Better Auth](auth.md) for roles and capabilities), and everything downstream uses the result:
|
|
110
111
|
|
|
111
112
|
- **Operations**: a denied operation is `403`; a resource the caller can do nothing with does not exist for them (`404` everywhere, absent from `/meta` and the OpenAPI document).
|
|
112
|
-
- **Readable fields**: the caller works with a restricted model that has only the fields they may read. `filter`, `order_by`, `fields`, `search(...)`, `:facets`, `:aggregate`, `:histogram`, `:series`, `:map`, `:seek` and `:search` bodies are checked against it, so a hidden field is refused exactly like an unknown one (same status, same message and hint, nothing that says it exists). List, get, create, update and delete responses contain readable fields only, and queries select only those columns.
|
|
113
|
+
- **Readable fields**: the caller works with a restricted model that has only the fields they may read. `filter`, `order_by`, `fields`, `search(...)`, `:facets`, `:aggregate`, `:histogram`, `:series`, `:batchAggregates`, `:map`, `:seek` and `:search` bodies are checked against it, so a hidden field is refused exactly like an unknown one (same status, same message and hint, nothing that says it exists). List, get, create, update and delete responses contain readable fields only, and queries select only those columns.
|
|
113
114
|
- **Sensitive fields** are readable fields that no response carries and no request may name, except `:reveal`; they can be written. See [Sensitive fields and audit](#sensitive-fields-and-audit).
|
|
114
115
|
- **Writable fields**: only fields the caller may write and read are accepted, and [write-only](access.md#write-only-fields) ones; any other is `400`, worded as unknown (hidden) or read-only.
|
|
115
116
|
- **Row filters**: a rule that returns a filter (`.own`, `.team`) narrows every read (list, get, aggregates) and the rows a write may target; the database applies it, so it may use columns the caller cannot see. A row outside it is a `404`.
|
|
@@ -267,7 +268,7 @@ The API sends no CORS headers until it has something to allow: other websites in
|
|
|
267
268
|
|
|
268
269
|
- Every request runs in a transaction with `SET LOCAL statement_timeout` (`statementTimeoutMs`, default 1 s), so a slow query fails where it runs instead of holding a connection that other requests wait for. List, search, get, histogram, series, map and seek transactions are read-only. A query that runs longer is stopped: a `504` `statement-timeout` that names the request, its limit and the ways out, such as `GET /api/v1/orders ran a query longer than 1 s, so the database stopped it. Make the query faster, such as with an index or a narrower filter, or move the work into a function or job with longQueries: true, whose queries may run up to 30 s.` It goes to the app's error hook (`hooks/error.ts`, `createAdmin`'s `options.onUnhandledError`) and the [error tracker](#error-reporting) like a `500`. A read that needs longer has no way to opt out: give it an index, or move it into a [function](../guides/api-functions.md#long-queries) or [job](jobs.md) with `longQueries`.
|
|
269
270
|
- Under `protobase dev` and `serve`, a request waits at most 2 seconds for a free database connection. When every connection stays busy that long, it is a `503` `connections-busy` with `Retry-After: 1` that names the request, reported the same way, rather than a request that hangs behind slow ones. A request that finds room for a new connection waits up to 30 seconds for it to open, such as while a database that scaled to zero wakes.
|
|
270
|
-
- **Scan guard**: a list, `:search`, `:seek`, `:map` page, card photos, `:facets` and `:aggregate` read only columns an index serves, so they stay cheap however many rows match. The server reads each table's valid indexes from the catalog once, then checks every column the caller's filter, the role's row filter, the sort's first field, a facet's or an aggregate's grouped field, the field of [`limit_per`](#first-rows-per-value), a [`read` parent](access.md#records-that-belong-to-another)'s relation read and a [`related()`](#filtering-through-related-records) term's `field`, the columns of the parent's own row filter against the parent's table, and the subfilter's columns and `key` of a term against its resource's table:
|
|
271
|
+
- **Scan guard**: a list, `:search`, `:seek`, `:map` page, card photos, `:facets` (in `:batchAggregates` too) and `:aggregate` read only columns an index serves, so they stay cheap however many rows match. The server reads each table's valid indexes from the catalog once, then checks every column the caller's filter, the role's row filter, the sort's first field, a facet's or an aggregate's grouped field, the field of [`limit_per`](#first-rows-per-value), a [`read` parent](access.md#records-that-belong-to-another)'s relation read and a [`related()`](#filtering-through-related-records) term's `field`, the columns of the parent's own row filter against the parent's table, and the subfilter's columns and `key` of a term against its resource's table:
|
|
271
272
|
- Comparisons, `in`, null checks, sorts and facets need a btree index with the column as a key, every key before it pinned by the query: by `=` or `in` in the filter (outside `OR` and `NOT`), by the tenant or by soft delete. `(for_sale, status, published_at desc)` serves `for_sale = true AND status = "available"` sorted by `published_at desc`, but not `status` alone. `=` on text may use a pg_trgm index instead.
|
|
272
273
|
- `limit_per` reads each value's records in the sort's order, so it needs one btree index with its field as a key and the sort's first field under it, `(task_id, created_at)` for `limit_per=task_id:3&order_by=created_at desc`; without an `order_by`, an index on its field alone.
|
|
273
274
|
- Patterns (`name = "*port*"`), `regex()`, `similar()` and `search()` need a pg_trgm (GIN or GiST) index on each column they read, a `digitsEnd` search field one on its digits; JSON `field:value` needs a GIN index.
|
|
@@ -111,8 +111,8 @@ A config that exports no resource fails, as one that lost its resources by mista
|
|
|
111
111
|
|
|
112
112
|
Imports `config/index.ts` and the views of `config/*/ui.ts`, as the config module has them by convention, and checks every exported resource against the database, with the resources Protobase adds by what `protobase.config.ts` (read with `command: 'tool'`) and the resources enable: the [webhook](webhooks.md#subscriptions-in-the-admin-app) ones of `webhooks`, Failed jobs, [Activity](history.md) and [Comments](comments.md). The tables [`migration`](#migration) writes for those have every index their reads need, so after the project's migrations they pass; a read of theirs that lacks an index, as on a table an earlier version wrote, is an error and doctor exits 1 until you run `migration` and apply what it writes:
|
|
113
113
|
|
|
114
|
-
- error: missing table or column, field type that does not fit the column (a file field needs a text column), table without a usable key, configured key not backed by a unique index, `.openExisting()` fields that are not the columns of a unique index, relation to a resource the config does not declare
|
|
115
|
-
- error: a read the [scan guard](api.md#safety) refuses, because no index serves a column it filters, sorts, searches or counts by. Doctor reads each table's indexes from the catalog, as the server does, and judges with the scan guard's own rule every read the API takes and the app makes: a filter on each `.filterable()` field, a sort by each `.sortable()` one, `search()` over the search fields, a role's own records (`.owner()`)
|
|
114
|
+
- error: missing table or column, field type that does not fit the column (a file field needs a text column), table without a usable key, configured key not backed by a unique index, `.openExisting()` fields that are not the columns of a unique index, relation to a resource the config does not declare, a [lookup field](data-config.md#lookups) of the one record of another resource without a unique index on the relation it reads that record by
|
|
115
|
+
- error: a read the [scan guard](api.md#safety) refuses, because no index serves a column it filters, sorts, searches or counts by. Doctor reads each table's indexes from the catalog, as the server does, and judges with the scan guard's own rule every read the API takes and the app makes: a filter on each `.filterable()` field, a sort by each `.sortable()` one, `search()` over the search fields, a role's own records (`.owner()`), the names a relation shows and the linked records a lookup field reads, judged against the linked table; each view's list in its order and with the filter it opens with, its filter widgets and their counts, its chart, its map, board, calendar and timeline, its card photos, its order by hand, its related sections, galleries and charts, its named lists, its recent records and a saved search's new records; and each read of a [composed page's read plan](layouts.md#how-a-page-reads-its-data): its blocks' lists, counts and aggregates, a `Chart`'s grouped and split fields, a nested list's `limit_per`, and the outer read each `related()` term carries with its own filter and order. Each error is an index to add, with every request that needs it and where it comes from:
|
|
116
116
|
|
|
117
117
|
```
|
|
118
118
|
error agencies: no index serves the column "name", so the API refuses:
|
|
@@ -17,7 +17,7 @@ const { record, etag } = await api.get(orders, id)
|
|
|
17
17
|
await api.update(orders, id, { status: 'shipped' }, etag) // 412 rejects with PreconditionFailedError
|
|
18
18
|
```
|
|
19
19
|
|
|
20
|
-
Pass a resource builder to get its record type ([`InferRecord`](https://docs.protobase.net/api/schema/type-aliases/inferrecord/)), or a name for loose records. Filters are AIP-160 text or [`where`](https://docs.protobase.net/api/schema/variables/where/) results (printed with [`printFilter`](https://docs.protobase.net/api/schema/functions/printfilter/)), and a list whose query string passes 4,000 characters goes by `:search`. Errors are `ApiError` (`status`, `slug`, `errors`, `filterErrors` with spans, `blockedBy` for a delete other records point at), which `isApiError(error)` tells apart. Also: `search`, `create`, `remove`, `facets`, `series`, `histogram`, `map(resource, { latitude, longitude, zoom, filter?, orderBy?, fields? })` (the records in a map's view, or buckets of them, see [`:map`](api.md#maps)), `seek`, `reveal(resource, key, field)` (a [sensitive field](data-config.md#sensitive-fields)'s value), `generate(resource, key, action)` (runs an [AI action](ai.md#ai-actions) and resolves to the record as written), `meta(etag?, { signal? })`, `invoke(name, { body?, method?, path?, query?, cache? })` (one of the app's [API functions](../guides/api-functions.md#calling-a-function); its answer as parsed JSON, text, or a `Blob` for any other type), `history(resource, key, { pageSize?, pageToken? })` (a page of a record's [changes](history.md), newest first), `comments(resource, key, { pageSize?, pageToken? })`, `comment(resource, key, { body, mentions? })` and `mentionable(resource, key, query)` (a record's [comments](comments.md#the-endpoints), adding one, and the people it may mention), `form(name)`, `formChallenge(name)` and `submitForm(name, values, proof)` (a [public form](forms.md#routes)), `upload(resource, field, file, { onProgress?, signal? })` (a file for a [file field](files.md#uploading); its `value` goes in the next write, and `onProgress` uses XMLHttpRequest, since fetch reports no upload progress), `live({ onChanges, onResync, onRetry? })` (hears which records of the [live](live.md) resources change until the function it returns is called, connecting again by itself; every caller of one client shares one stream), `channel(resource, key)` (a record's [channel](channels.md#from-a-page), with its presence and broadcasts, every channel of the client on one socket), `bridges.open(name, target)` (a [TCP bridge](tcp-bridges.md#opening-a-bridge)'s socket, with when the server closes it).
|
|
20
|
+
Pass a resource builder to get its record type ([`InferRecord`](https://docs.protobase.net/api/schema/type-aliases/inferrecord/)), or a name for loose records. Filters are AIP-160 text or [`where`](https://docs.protobase.net/api/schema/variables/where/) results (printed with [`printFilter`](https://docs.protobase.net/api/schema/functions/printfilter/)), and a list whose query string passes 4,000 characters goes by `:search`. Errors are `ApiError` (`status`, `slug`, `errors`, `filterErrors` with spans, `blockedBy` for a delete other records point at), which `isApiError(error)` tells apart. Also: `search`, `create`, `remove`, `facets`, `series`, `histogram`, `batchAggregates(resource, { facets?, histograms?, series? })` (several of those reads in one [`:batchAggregates`](api.md#routes) request, answered as each would be), `map(resource, { latitude, longitude, zoom, filter?, orderBy?, fields? })` (the records in a map's view, or buckets of them, see [`:map`](api.md#maps)), `seek`, `reveal(resource, key, field)` (a [sensitive field](data-config.md#sensitive-fields)'s value), `generate(resource, key, action)` (runs an [AI action](ai.md#ai-actions) and resolves to the record as written), `meta(etag?, { signal? })`, `invoke(name, { body?, method?, path?, query?, cache? })` (one of the app's [API functions](../guides/api-functions.md#calling-a-function); its answer as parsed JSON, text, or a `Blob` for any other type), `history(resource, key, { pageSize?, pageToken? })` (a page of a record's [changes](history.md), newest first), `comments(resource, key, { pageSize?, pageToken? })`, `comment(resource, key, { body, mentions? })` and `mentionable(resource, key, query)` (a record's [comments](comments.md#the-endpoints), adding one, and the people it may mention), `form(name)`, `formChallenge(name)` and `submitForm(name, values, proof)` (a [public form](forms.md#routes)), `upload(resource, field, file, { onProgress?, signal? })` (a file for a [file field](files.md#uploading); its `value` goes in the next write, and `onProgress` uses XMLHttpRequest, since fetch reports no upload progress), `live({ onChanges, onResync, onRetry? })` (hears which records of the [live](live.md) resources change until the function it returns is called, connecting again by itself; every caller of one client shares one stream), `channel(resource, key)` (a record's [channel](channels.md#from-a-page), with its presence and broadcasts, every channel of the client on one socket), `bridges.open(name, target)` (a [TCP bridge](tcp-bridges.md#opening-a-bridge)'s socket, with when the server closes it).
|
|
21
21
|
|
|
22
22
|
With an absolute `baseUrl`, such as another app's `https://desk.example.com/api/v1`, the `url` of each [file](files.md) in a record the client answers is absolute too, on that API's origin, where the API answers a path on its own origin. `routedClient(own, sourceOf)` is one client over several APIs: each call about a resource goes to the client `sourceOf(resource)` gives, else to `own`, as the admin app does for [remote resources](remote-resources.md), and `sourceMeta(meta, source)` keeps the part of another API's `/meta` an app draws.
|
|
23
23
|
|
|
@@ -118,6 +118,7 @@ Every option returns a new [field](https://docs.protobase.net/api/schema/interfa
|
|
|
118
118
|
| `.ai({ prompt })` | A job fills the field from `prompt`, `{{field}}` replaced by the record's values, after a create and after an update of a field the prompt reads, as the user who wrote. Text or enum, optional. See [AI fields and actions](ai.md). |
|
|
119
119
|
| `.rollup({ from, via, fn, field })` | The database keeps the field from the records of another resource: their count, sum, average, least or greatest value. Read-only. See [Rollups and formulas](#rollups-and-formulas). |
|
|
120
120
|
| `.formula(expression)` | The database computes the field from the record's other number fields, as a generated column. Read-only. See [Rollups and formulas](#rollups-and-formulas). |
|
|
121
|
+
| `.lookup({ via, field, from? })` | Shows a field of the record this one is linked to, read with the record. Read-only. See [Lookups](#lookups). |
|
|
121
122
|
|
|
122
123
|
The ERP's products show most of them, together with soft delete and a tenant:
|
|
123
124
|
|
|
@@ -209,6 +210,70 @@ Empty values of `field` are left out, as in SQL. The migration adds the column,
|
|
|
209
210
|
|
|
210
211
|
Neither field can be written through the API, have a default, or be sensitive, an AI field, a file, or the key, tenant, owner or soft delete field, and a formula cannot read a sensitive field. The server does not start while a declared column, function or trigger is missing or out of date, with a message that names the fields; the migration fixes that. It stops with an error, without writing anything, when the column already exists as the project's own: a plain column where a formula is declared, a generated column it did not write, or a rollup column of another type.
|
|
211
212
|
|
|
213
|
+
## Lookups
|
|
214
|
+
|
|
215
|
+
:::caution[Beta]
|
|
216
|
+
Not yet:
|
|
217
|
+
|
|
218
|
+
- <gap>Sorting by a lookup field reads every record the list keeps before it returns a page, because no index orders one table by another table's column.</gap>
|
|
219
|
+
- <gap>A lookup field cannot show a relation or a file because reading the linked record's key or stored file for it is not implemented.</gap>
|
|
220
|
+
- <gap>A lookup through a relation of several columns, or to a resource with a key of several fields, is not supported yet.</gap>
|
|
221
|
+
- <gap>A list across organizations (`across: 'memberships'`) cannot show lookup fields of another organization's records because reading their linked records under that organization's access is not implemented.</gap> They are empty there.
|
|
222
|
+
- <gap>An open page of a [live](live.md) resource cannot refresh when only a linked record changes because capturing those changes for the lookup fields that read them is not implemented.</gap>
|
|
223
|
+
:::
|
|
224
|
+
|
|
225
|
+
A **lookup field** shows a field of the record its record is linked to, such as an order's customer name. It has no column of its own: the API reads it with the record, in the same query, from the linked table, so it always shows the linked record's current value.
|
|
226
|
+
|
|
227
|
+
```ts title="docs-examples/reference/lookups.ts"
|
|
228
|
+
import { f, resource } from '@protobase/schema'
|
|
229
|
+
|
|
230
|
+
// Orders show their customer's name and tier through their own relation to the customer, and each customer the name
|
|
231
|
+
// of their one account manager, whose record points at the customer.
|
|
232
|
+
|
|
233
|
+
/** shop.customers: one row per customer. */
|
|
234
|
+
export const customers = resource('customers')
|
|
235
|
+
.table('shop.customers')
|
|
236
|
+
.fields({
|
|
237
|
+
id: f.integer().readOnly().filterable().sortable().dbDefault(),
|
|
238
|
+
name: f.text().filterable().sortable(),
|
|
239
|
+
tier: f.enum(['gold', 'silver', 'bronze']).filterable(),
|
|
240
|
+
// From the one manager record whose customer_id is this customer; empty without one.
|
|
241
|
+
manager_name: f.text().lookup({ from: 'account_managers', via: 'customer_id', field: 'name' }),
|
|
242
|
+
})
|
|
243
|
+
.primaryKey((r) => r.id)
|
|
244
|
+
|
|
245
|
+
/** shop.account_managers: at most one per customer, by a unique index on customer_id. */
|
|
246
|
+
export const accountManagers = resource('account_managers')
|
|
247
|
+
.table('shop.account_managers')
|
|
248
|
+
.fields({
|
|
249
|
+
id: f.integer().readOnly().filterable().dbDefault(),
|
|
250
|
+
customer_id: f.relation('customers').filterable(),
|
|
251
|
+
name: f.text(),
|
|
252
|
+
})
|
|
253
|
+
.primaryKey((r) => r.id)
|
|
254
|
+
|
|
255
|
+
/** shop.orders: one row per order. */
|
|
256
|
+
export const orders = resource('orders')
|
|
257
|
+
.table('shop.orders')
|
|
258
|
+
.fields({
|
|
259
|
+
id: f.integer().readOnly().filterable().sortable().dbDefault(),
|
|
260
|
+
customer_id: f.relation('customers').filterable(),
|
|
261
|
+
// The customer's name and tier, as the caller may read them; filtered and sorted as the customer's fields are.
|
|
262
|
+
customer_name: f.text().lookup({ via: 'customer_id', field: 'name' }).filterable().sortable(),
|
|
263
|
+
customer_tier: f.enum(['gold', 'silver', 'bronze']).lookup({ via: 'customer_id', field: 'tier' }).filterable(),
|
|
264
|
+
})
|
|
265
|
+
.primaryKey((r) => r.id)
|
|
266
|
+
```
|
|
267
|
+
|
|
268
|
+
`.lookup({ via, field })` reads `field` of the record that the record's relation `via` points at. `.lookup({ from, via, field })` reads it of the one record of resource `from` whose relation `via` points at the record, such as a customer's account manager. That needs a unique index on `via`, which [`protobase doctor`](cli.md#doctor) asks for, since a second such record makes every read of the field fail.
|
|
269
|
+
|
|
270
|
+
- It is declared with the linked field's type, and for an enum its values. The server does not start while they differ, or while a resource or field it names is missing or the linked field is sensitive.
|
|
271
|
+
- It is read-only and optional: empty when there is no linked record, or none the caller may read.
|
|
272
|
+
- It shows in lists, record pages, `/meta` and the API as any read-only field does, and the response of a write has it too.
|
|
273
|
+
- `.filterable()` and `.sortable()` take it when the linked field takes them. A filter on it keeps the records whose link is among the keys of the linked records that match, so it needs an index on the linked field in the linked table and one on `via` in this one; the [scan guard](api.md#safety) and doctor ask for both, as for any other read. A sort by it needs them too. <gap>Sorting by a lookup field reads every record the list keeps before it returns a page, because no index orders one table by another table's column.</gap>
|
|
274
|
+
- It reads the linked records as the caller would: in their tenant, without soft-deleted ones, inside their row filter and the parents they read. A caller who may not read the linked resource, whose read rule there needs the record, or who may not read the linked field or the relation it goes through, does not have the lookup field at all: responses, `/meta`, filters and sorts leave it out, as they leave out any field the caller may not read. Its own `.access({ read })` narrows that further.
|
|
275
|
+
- It is not stored with the record, so the record's ETag, events, history and the filters of access rules do not see it, and it cannot be a key, tenant, owner, author, soft delete, position, parent, link or search field, or have a column, a default, a rollup, a formula or an AI prompt.
|
|
276
|
+
|
|
212
277
|
## Time rollups
|
|
213
278
|
|
|
214
279
|
:::caution[In development]
|
|
@@ -409,6 +409,8 @@ A list without rows says why, in the table, the cards and the phone's List alike
|
|
|
409
409
|
|
|
410
410
|
Every widget takes `secondary: true` (e.g. `w.facets(r.agent, { secondary: true })`): it waits behind the bar's **More filters** menu until it is picked there, and shows in the bar whenever it is set, such as from the address. The panel layout and the phone's filter sheet show every filter.
|
|
411
411
|
|
|
412
|
+
The widgets' counts and ranges and the list's chart load together as one [`:batchAggregates`](api.md#routes) request, so a page with many filters reads a large table a few times rather than once per filter. Counts that could not be loaded say **Could not load the counts** in their menu, and a chart that could not be loaded says **Could not load the chart.**, never zero counts or empty bars.
|
|
413
|
+
|
|
412
414
|
### Charts (graphs): records per day or week, or per value, above a list
|
|
413
415
|
|
|
414
416
|
A list can show a graph of how many of its records fall on each day or week, such as a daily graph of new listings. `.chart((r) => ({ field, range, granularity }))` draws the list's records per day over a date or timestamp field as bars above the list, following its filters, headed by their total and how much the second half of the bars differs from the first. `range` is how far back it reaches: `7d`, `30d`, `90d`, `1y` or `all`. A **Day** and **Week** switch changes the bars, and **Week** shows the last 12 weeks whatever the range; `granularity: 'week'` opens it on weeks. <gap>`hour` and `month` are accepted and show days, as hourly and monthly bars are not built.</gap> A bar's tooltip names its day or whole week, today's bar or this week's is outlined with a dash, as it is still filling up, and the chart reads by keyboard and screen reader as a [trend](#trends-of-related-records)'s does. Its bars do not filter the list.
|