@databricks/appkit-ui 0.86.0 → 0.88.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/js/database/client.d.ts.map +1 -1
- package/dist/js/database/client.js +41 -9
- package/dist/js/database/client.js.map +1 -1
- package/dist/react/beta.d.ts +14 -1
- package/dist/react/beta.js +9 -1
- package/dist/react/hooks/analytics-request-store.js +1 -1
- package/dist/react/hooks/analytics-request-store.js.map +1 -1
- package/dist/react/hooks/database-request-store.d.ts +33 -0
- package/dist/react/hooks/database-request-store.d.ts.map +1 -0
- package/dist/react/hooks/database-request-store.js +145 -0
- package/dist/react/hooks/database-request-store.js.map +1 -0
- package/dist/react/hooks/request-store.js +26 -5
- package/dist/react/hooks/request-store.js.map +1 -1
- package/dist/react/hooks/use-database-create.d.ts +55 -0
- package/dist/react/hooks/use-database-create.d.ts.map +1 -0
- package/dist/react/hooks/use-database-create.js +45 -0
- package/dist/react/hooks/use-database-create.js.map +1 -0
- package/dist/react/hooks/use-database-delete.d.ts +50 -0
- package/dist/react/hooks/use-database-delete.d.ts.map +1 -0
- package/dist/react/hooks/use-database-delete.js +47 -0
- package/dist/react/hooks/use-database-delete.js.map +1 -0
- package/dist/react/hooks/use-database-list.d.ts +40 -0
- package/dist/react/hooks/use-database-list.d.ts.map +1 -0
- package/dist/react/hooks/use-database-list.js +29 -0
- package/dist/react/hooks/use-database-list.js.map +1 -0
- package/dist/react/hooks/use-database-read.d.ts +75 -0
- package/dist/react/hooks/use-database-read.d.ts.map +1 -0
- package/dist/react/hooks/use-database-read.js +136 -0
- package/dist/react/hooks/use-database-read.js.map +1 -0
- package/dist/react/hooks/use-database-record.d.ts +37 -0
- package/dist/react/hooks/use-database-record.d.ts.map +1 -0
- package/dist/react/hooks/use-database-record.js +53 -0
- package/dist/react/hooks/use-database-record.js.map +1 -0
- package/dist/react/hooks/use-database-update.d.ts +52 -0
- package/dist/react/hooks/use-database-update.d.ts.map +1 -0
- package/dist/react/hooks/use-database-update.js +42 -0
- package/dist/react/hooks/use-database-update.js.map +1 -0
- package/dist/react/hooks/use-database-write.d.ts +32 -0
- package/dist/react/hooks/use-database-write.d.ts.map +1 -0
- package/dist/react/hooks/use-database-write.js +94 -0
- package/dist/react/hooks/use-database-write.js.map +1 -0
- package/docs/development/type-generation.md +11 -0
- package/docs/plugins/database.md +233 -14
- package/package.json +1 -1
- package/sbom.cdx.json +1 -1
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import { DatabaseQueryEncodingError, encodeDatabaseRecordQuery } from "../../shared/src/database/query-codec.js";
|
|
2
|
+
import { isDatabaseRow } from "../../js/database/client.js";
|
|
3
|
+
import { useDatabaseRead } from "./use-database-read.js";
|
|
4
|
+
|
|
5
|
+
//#region src/react/hooks/use-database-record.ts
|
|
6
|
+
/**
|
|
7
|
+
* Subscribe to one row from `GET /api/database/<entity>/:id`. Only entities
|
|
8
|
+
* with a public primary key have this route; a missing row surfaces as a
|
|
9
|
+
* `NOT_FOUND` error, and a refetch that finds the row gone clears `data`.
|
|
10
|
+
*
|
|
11
|
+
* A `null` or `undefined` id holds the hook idle without a request, so a
|
|
12
|
+
* record that depends on another read needs no separate `enabled` flag. An
|
|
13
|
+
* empty, `"."`, or `".."` id reports `INVALID_REQUEST` without a request.
|
|
14
|
+
*
|
|
15
|
+
* @param entity - A table the generated registry exposes with a public key
|
|
16
|
+
* @param id - The row's public key, or `null`/`undefined` to wait
|
|
17
|
+
* @param params - `select` and `include`; pass `{}` to reach `options` alone
|
|
18
|
+
* @param options - `enabled`, `keepPreviousData`, and `shape`
|
|
19
|
+
* @returns The row, loading and error state, and `refetch`
|
|
20
|
+
*
|
|
21
|
+
* @example
|
|
22
|
+
* ```tsx
|
|
23
|
+
* const board = useDatabaseRecord("boards", selectedId, {
|
|
24
|
+
* include: { notes: { limit: 20 } },
|
|
25
|
+
* });
|
|
26
|
+
* board.data?.notes.length;
|
|
27
|
+
* ```
|
|
28
|
+
*/
|
|
29
|
+
function useDatabaseRecord(entity, id, params, options = {}) {
|
|
30
|
+
const enabled = (options.enabled ?? true) && id !== null && id !== void 0;
|
|
31
|
+
const recordParams = params ?? {};
|
|
32
|
+
let query = "";
|
|
33
|
+
if (enabled) try {
|
|
34
|
+
query = encodeDatabaseRecordQuery(recordParams);
|
|
35
|
+
} catch (error) {
|
|
36
|
+
query = error instanceof DatabaseQueryEncodingError ? error : null;
|
|
37
|
+
}
|
|
38
|
+
return useDatabaseRead({
|
|
39
|
+
entity,
|
|
40
|
+
operation: "detail",
|
|
41
|
+
id: id ?? void 0,
|
|
42
|
+
query,
|
|
43
|
+
include: recordParams.include,
|
|
44
|
+
enabled,
|
|
45
|
+
accept: isDatabaseRow,
|
|
46
|
+
keepPreviousData: options.keepPreviousData ?? false,
|
|
47
|
+
shape: options.shape
|
|
48
|
+
});
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
//#endregion
|
|
52
|
+
export { useDatabaseRecord };
|
|
53
|
+
//# sourceMappingURL=use-database-record.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"use-database-record.js","names":[],"sources":["../../../src/react/hooks/use-database-record.ts"],"sourcesContent":["import {\n DatabaseQueryEncodingError,\n encodeDatabaseRecordQuery,\n type ExactDatabaseParams,\n} from \"shared\";\n\nimport { isDatabaseRow } from \"@/js/database/client\";\nimport type {\n DatabaseId,\n DatabaseKeyedEntity,\n DatabaseRecordParams,\n DatabaseRecordRow,\n} from \"@/js/database/types\";\n\nimport {\n type DatabaseReadRequest,\n type UseDatabaseReadOptions,\n type UseDatabaseReadResult,\n useDatabaseRead,\n} from \"./use-database-read\";\n\n/** Options for {@link useDatabaseRecord}. */\nexport type UseDatabaseRecordOptions<Row> = UseDatabaseReadOptions<Row>;\n\n/** What {@link useDatabaseRecord} returns: one row and its state. */\nexport type UseDatabaseRecordResult<Row> = UseDatabaseReadResult<Row>;\n\n/**\n * Subscribe to one row from `GET /api/database/<entity>/:id`. Only entities\n * with a public primary key have this route; a missing row surfaces as a\n * `NOT_FOUND` error, and a refetch that finds the row gone clears `data`.\n *\n * A `null` or `undefined` id holds the hook idle without a request, so a\n * record that depends on another read needs no separate `enabled` flag. An\n * empty, `\".\"`, or `\"..\"` id reports `INVALID_REQUEST` without a request.\n *\n * @param entity - A table the generated registry exposes with a public key\n * @param id - The row's public key, or `null`/`undefined` to wait\n * @param params - `select` and `include`; pass `{}` to reach `options` alone\n * @param options - `enabled`, `keepPreviousData`, and `shape`\n * @returns The row, loading and error state, and `refetch`\n *\n * @example\n * ```tsx\n * const board = useDatabaseRecord(\"boards\", selectedId, {\n * include: { notes: { limit: 20 } },\n * });\n * board.data?.notes.length;\n * ```\n */\nexport function useDatabaseRecord<\n K extends DatabaseKeyedEntity,\n const P extends DatabaseRecordParams<K> = Record<never, never>,\n Row = DatabaseRecordRow<K, P>,\n>(\n entity: K,\n id: DatabaseId<K> | null | undefined,\n params?: P & ExactDatabaseParams<P, DatabaseRecordParams<K>>,\n options: UseDatabaseRecordOptions<Row> = {},\n): UseDatabaseRecordResult<Row> {\n const enabled = (options.enabled ?? true) && id !== null && id !== undefined;\n const recordParams = (params ?? {}) as { include?: unknown };\n // Encode only an enabled read: a held read's params may still be incomplete.\n let query: DatabaseReadRequest[\"query\"] = \"\";\n if (enabled) {\n try {\n query = encodeDatabaseRecordQuery(recordParams);\n } catch (error) {\n query = error instanceof DatabaseQueryEncodingError ? error : null;\n }\n }\n const read = useDatabaseRead({\n entity,\n operation: \"detail\",\n id: id ?? undefined,\n query,\n include: recordParams.include,\n enabled,\n accept: isDatabaseRow,\n keepPreviousData: options.keepPreviousData ?? false,\n shape: options.shape as UseDatabaseReadOptions<unknown>[\"shape\"],\n });\n // The server projected and encoded the row; the types describe that wire.\n return read as UseDatabaseRecordResult<Row>;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkDA,SAAgB,kBAKd,QACA,IACA,QACA,UAAyC,EAAE,EACb;CAC9B,MAAM,WAAW,QAAQ,WAAW,SAAS,OAAO,QAAQ,OAAO;CACnE,MAAM,eAAgB,UAAU,EAAE;CAElC,IAAI,QAAsC;AAC1C,KAAI,QACF,KAAI;AACF,UAAQ,0BAA0B,aAAa;UACxC,OAAO;AACd,UAAQ,iBAAiB,6BAA6B,QAAQ;;AAelE,QAZa,gBAAgB;EAC3B;EACA,WAAW;EACX,IAAI,MAAM;EACV;EACA,SAAS,aAAa;EACtB;EACA,QAAQ;EACR,kBAAkB,QAAQ,oBAAoB;EAC9C,OAAO,QAAQ;EAChB,CAAC"}
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import { ExactDatabaseParams } from "../../shared/src/database/api-types.js";
|
|
2
|
+
import "../../shared/src/index.js";
|
|
3
|
+
import { DatabaseId, DatabaseKeyedEntity, DatabaseRow, DatabaseUpdate } from "../../js/database/types.js";
|
|
4
|
+
import { DatabaseApiError } from "../../js/database/errors.js";
|
|
5
|
+
import { UseDatabaseWriteOptions, UseDatabaseWriteState } from "./use-database-write.js";
|
|
6
|
+
|
|
7
|
+
//#region src/react/hooks/use-database-update.d.ts
|
|
8
|
+
/** Options for {@link useDatabaseUpdate}. */
|
|
9
|
+
interface UseDatabaseUpdateOptions<K extends DatabaseKeyedEntity> extends UseDatabaseWriteOptions {
|
|
10
|
+
/**
|
|
11
|
+
* Called for every successful update, once the restarted reads reloaded,
|
|
12
|
+
* even if the component unmounted meanwhile.
|
|
13
|
+
*/
|
|
14
|
+
onSuccess?: (row: DatabaseRow<K>, id: DatabaseId<K>, values: DatabaseUpdate<K>) => void;
|
|
15
|
+
/** Called for every failed update, with the error `error` also reports. */
|
|
16
|
+
onError?: (error: DatabaseApiError, id: DatabaseId<K>, values: DatabaseUpdate<K>) => void;
|
|
17
|
+
}
|
|
18
|
+
/** What {@link useDatabaseUpdate} returns. */
|
|
19
|
+
interface UseDatabaseUpdateResult<K extends DatabaseKeyedEntity> extends UseDatabaseWriteState<DatabaseRow<K>> {
|
|
20
|
+
/**
|
|
21
|
+
* Send `PATCH /api/database/<entity>/:id` and resolve with the updated row,
|
|
22
|
+
* or with `null` when the write failed; the reason is in `error`, and a
|
|
23
|
+
* missing row is `NOT_FOUND`. It never rejects.
|
|
24
|
+
*/
|
|
25
|
+
update<const V extends DatabaseUpdate<K>>(id: DatabaseId<K>, values: V & ExactDatabaseParams<V, DatabaseUpdate<K>>): Promise<DatabaseRow<K> | null>;
|
|
26
|
+
/** Return to the idle state; a call in flight no longer reports here. */
|
|
27
|
+
reset(): void;
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* Update rows through `PATCH /api/database/<entity>/:id`. Only entities with a
|
|
31
|
+
* public primary key have this route, and keys, generated, and
|
|
32
|
+
* default-stamped columns are not updatable. Once an update succeeds, mounted
|
|
33
|
+
* database reads restart.
|
|
34
|
+
*
|
|
35
|
+
* @param entity - A table the generated registry exposes with a public key
|
|
36
|
+
* @param options - `invalidate` to narrow the read restart; `onSuccess` and
|
|
37
|
+
* `onError` to observe every call
|
|
38
|
+
* @returns `update`, the latest call's row, loading and error state, and `reset`
|
|
39
|
+
*
|
|
40
|
+
* @example
|
|
41
|
+
* ```tsx
|
|
42
|
+
* const notes = useDatabaseUpdate("notes");
|
|
43
|
+
*
|
|
44
|
+
* <button onClick={() => notes.update(note.id, { body: "Resolved" })}>
|
|
45
|
+
* Resolve
|
|
46
|
+
* </button>;
|
|
47
|
+
* ```
|
|
48
|
+
*/
|
|
49
|
+
declare function useDatabaseUpdate<K extends DatabaseKeyedEntity>(entity: K, options?: UseDatabaseUpdateOptions<K>): UseDatabaseUpdateResult<K>;
|
|
50
|
+
//#endregion
|
|
51
|
+
export { UseDatabaseUpdateOptions, UseDatabaseUpdateResult, useDatabaseUpdate };
|
|
52
|
+
//# sourceMappingURL=use-database-update.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"use-database-update.d.ts","names":[],"sources":["../../../src/react/hooks/use-database-update.ts"],"mappings":";;;;;;;;UAmBiB,wBAAA,WACL,mBAAA,UACF,uBAAA;;AAFV;;;EAOE,SAAA,IACE,GAAA,EAAK,WAAA,CAAY,CAAA,GACjB,EAAA,EAAI,UAAA,CAAW,CAAA,GACf,MAAA,EAAQ,cAAA,CAAe,CAAA;EAFN;EAKnB,OAAA,IACE,KAAA,EAAO,gBAAA,EACP,EAAA,EAAI,UAAA,CAAW,CAAA,GACf,MAAA,EAAQ,cAAA,CAAe,CAAA;AAAA;;UAKV,uBAAA,WACL,mBAAA,UACF,qBAAA,CAAsB,WAAA,CAAY,CAAA;EAbhC;;;;;EAmBV,MAAA,iBAAuB,cAAA,CAAe,CAAA,GACpC,EAAA,EAAI,UAAA,CAAW,CAAA,GACf,MAAA,EAAQ,CAAA,GAAI,mBAAA,CAAoB,CAAA,EAAG,cAAA,CAAe,CAAA,KACjD,OAAA,CAAQ,WAAA,CAAY,CAAA;EA9Bf;EAgCR,KAAA;AAAA;;;;;;;;;;;;;;;;;;;;;iBAuBc,iBAAA,WAA4B,mBAAA,CAAA,CAC1C,MAAA,EAAQ,CAAA,EACR,OAAA,GAAS,wBAAA,CAAyB,CAAA,IACjC,uBAAA,CAAwB,CAAA"}
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import { updateDatabaseRow } from "../../js/database/client.js";
|
|
2
|
+
import { useDatabaseWrite } from "./use-database-write.js";
|
|
3
|
+
import { useCallback } from "react";
|
|
4
|
+
|
|
5
|
+
//#region src/react/hooks/use-database-update.ts
|
|
6
|
+
/**
|
|
7
|
+
* Update rows through `PATCH /api/database/<entity>/:id`. Only entities with a
|
|
8
|
+
* public primary key have this route, and keys, generated, and
|
|
9
|
+
* default-stamped columns are not updatable. Once an update succeeds, mounted
|
|
10
|
+
* database reads restart.
|
|
11
|
+
*
|
|
12
|
+
* @param entity - A table the generated registry exposes with a public key
|
|
13
|
+
* @param options - `invalidate` to narrow the read restart; `onSuccess` and
|
|
14
|
+
* `onError` to observe every call
|
|
15
|
+
* @returns `update`, the latest call's row, loading and error state, and `reset`
|
|
16
|
+
*
|
|
17
|
+
* @example
|
|
18
|
+
* ```tsx
|
|
19
|
+
* const notes = useDatabaseUpdate("notes");
|
|
20
|
+
*
|
|
21
|
+
* <button onClick={() => notes.update(note.id, { body: "Resolved" })}>
|
|
22
|
+
* Resolve
|
|
23
|
+
* </button>;
|
|
24
|
+
* ```
|
|
25
|
+
*/
|
|
26
|
+
function useDatabaseUpdate(entity, options = {}) {
|
|
27
|
+
const send = useCallback((id, values) => updateDatabaseRow(entity, id, values), [entity]);
|
|
28
|
+
const { onSuccess, onError } = options;
|
|
29
|
+
const { mutate, ...write } = useDatabaseWrite(send, {
|
|
30
|
+
invalidate: options.invalidate,
|
|
31
|
+
onSuccess: onSuccess && ((row, [id, values]) => onSuccess(row, id, values)),
|
|
32
|
+
onError: onError && ((error, [id, values]) => onError(error, id, values))
|
|
33
|
+
});
|
|
34
|
+
return {
|
|
35
|
+
...write,
|
|
36
|
+
update: mutate
|
|
37
|
+
};
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
//#endregion
|
|
41
|
+
export { useDatabaseUpdate };
|
|
42
|
+
//# sourceMappingURL=use-database-update.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"use-database-update.js","names":[],"sources":["../../../src/react/hooks/use-database-update.ts"],"sourcesContent":["import { useCallback } from \"react\";\nimport type { ExactDatabaseParams } from \"shared\";\n\nimport { updateDatabaseRow } from \"@/js/database/client\";\nimport type { DatabaseApiError } from \"@/js/database/errors\";\nimport type {\n DatabaseId,\n DatabaseKeyedEntity,\n DatabaseRow,\n DatabaseUpdate,\n} from \"@/js/database/types\";\n\nimport {\n type UseDatabaseWriteOptions,\n type UseDatabaseWriteState,\n useDatabaseWrite,\n} from \"./use-database-write\";\n\n/** Options for {@link useDatabaseUpdate}. */\nexport interface UseDatabaseUpdateOptions<\n K extends DatabaseKeyedEntity,\n> extends UseDatabaseWriteOptions {\n /**\n * Called for every successful update, once the restarted reads reloaded,\n * even if the component unmounted meanwhile.\n */\n onSuccess?: (\n row: DatabaseRow<K>,\n id: DatabaseId<K>,\n values: DatabaseUpdate<K>,\n ) => void;\n /** Called for every failed update, with the error `error` also reports. */\n onError?: (\n error: DatabaseApiError,\n id: DatabaseId<K>,\n values: DatabaseUpdate<K>,\n ) => void;\n}\n\n/** What {@link useDatabaseUpdate} returns. */\nexport interface UseDatabaseUpdateResult<\n K extends DatabaseKeyedEntity,\n> extends UseDatabaseWriteState<DatabaseRow<K>> {\n /**\n * Send `PATCH /api/database/<entity>/:id` and resolve with the updated row,\n * or with `null` when the write failed; the reason is in `error`, and a\n * missing row is `NOT_FOUND`. It never rejects.\n */\n update<const V extends DatabaseUpdate<K>>(\n id: DatabaseId<K>,\n values: V & ExactDatabaseParams<V, DatabaseUpdate<K>>,\n ): Promise<DatabaseRow<K> | null>;\n /** Return to the idle state; a call in flight no longer reports here. */\n reset(): void;\n}\n\n/**\n * Update rows through `PATCH /api/database/<entity>/:id`. Only entities with a\n * public primary key have this route, and keys, generated, and\n * default-stamped columns are not updatable. Once an update succeeds, mounted\n * database reads restart.\n *\n * @param entity - A table the generated registry exposes with a public key\n * @param options - `invalidate` to narrow the read restart; `onSuccess` and\n * `onError` to observe every call\n * @returns `update`, the latest call's row, loading and error state, and `reset`\n *\n * @example\n * ```tsx\n * const notes = useDatabaseUpdate(\"notes\");\n *\n * <button onClick={() => notes.update(note.id, { body: \"Resolved\" })}>\n * Resolve\n * </button>;\n * ```\n */\nexport function useDatabaseUpdate<K extends DatabaseKeyedEntity>(\n entity: K,\n options: UseDatabaseUpdateOptions<K> = {},\n): UseDatabaseUpdateResult<K> {\n const send = useCallback(\n (id: DatabaseId<K>, values: DatabaseUpdate<K>) =>\n updateDatabaseRow(entity, id, values as object),\n [entity],\n );\n const { onSuccess, onError } = options;\n const { mutate, ...write } = useDatabaseWrite(send, {\n invalidate: options.invalidate,\n // The server projected the row it holds; the types describe that wire.\n onSuccess:\n onSuccess &&\n ((row, [id, values]) => onSuccess(row as DatabaseRow<K>, id, values)),\n onError: onError && ((error, [id, values]) => onError(error, id, values)),\n });\n return { ...write, update: mutate } as UseDatabaseUpdateResult<K>;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AA4EA,SAAgB,kBACd,QACA,UAAuC,EAAE,EACb;CAC5B,MAAM,OAAO,aACV,IAAmB,WAClB,kBAAkB,QAAQ,IAAI,OAAiB,EACjD,CAAC,OAAO,CACT;CACD,MAAM,EAAE,WAAW,YAAY;CAC/B,MAAM,EAAE,QAAQ,GAAG,UAAU,iBAAiB,MAAM;EAClD,YAAY,QAAQ;EAEpB,WACE,eACE,KAAK,CAAC,IAAI,YAAY,UAAU,KAAuB,IAAI,OAAO;EACtE,SAAS,aAAa,OAAO,CAAC,IAAI,YAAY,QAAQ,OAAO,IAAI,OAAO;EACzE,CAAC;AACF,QAAO;EAAE,GAAG;EAAO,QAAQ;EAAQ"}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import { DatabaseApiError } from "../../js/database/errors.js";
|
|
2
|
+
import { DatabaseInvalidation } from "./database-request-store.js";
|
|
3
|
+
|
|
4
|
+
//#region src/react/hooks/use-database-write.d.ts
|
|
5
|
+
/** Latest state of a database write hook. */
|
|
6
|
+
interface UseDatabaseWriteState<T> {
|
|
7
|
+
/** The latest call's result, or `null` before it answers. */
|
|
8
|
+
data: T | null;
|
|
9
|
+
/**
|
|
10
|
+
* Whether the latest call is in flight, including the reload of the reads
|
|
11
|
+
* it restarts.
|
|
12
|
+
*/
|
|
13
|
+
loading: boolean;
|
|
14
|
+
/**
|
|
15
|
+
* Why the latest call failed: `NOT_EXPOSED` when no route exists,
|
|
16
|
+
* `OUTCOME_UNKNOWN` when it may have committed without an answer.
|
|
17
|
+
*/
|
|
18
|
+
error: DatabaseApiError | null;
|
|
19
|
+
}
|
|
20
|
+
/** Options every database write hook takes. */
|
|
21
|
+
interface UseDatabaseWriteOptions {
|
|
22
|
+
/**
|
|
23
|
+
* Reads to restart once a write succeeds. Default `true`: every mounted
|
|
24
|
+
* database read, since a server hook may write other tables in the same
|
|
25
|
+
* transaction. A table list restarts only the reads that show those tables,
|
|
26
|
+
* directly or through an include; `false` restarts none.
|
|
27
|
+
*/
|
|
28
|
+
invalidate?: DatabaseInvalidation;
|
|
29
|
+
}
|
|
30
|
+
//#endregion
|
|
31
|
+
export { UseDatabaseWriteOptions, UseDatabaseWriteState };
|
|
32
|
+
//# sourceMappingURL=use-database-write.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"use-database-write.d.ts","names":[],"sources":["../../../src/react/hooks/use-database-write.ts"],"mappings":";;;;;UAaiB,qBAAA;EAAqB;EAEpC,IAAA,EAAM,CAAA;EAUiB;;;;EALvB,OAAA;EAKA;;;;EAAA,KAAA,EAAO,gBAAA;AAAA;;UAIQ,uBAAA;EAOkB;;;;;;EAAjC,UAAA,GAAa,oBAAA;AAAA"}
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
import { asDatabaseApiError, invalidateDatabaseReads } from "./database-request-store.js";
|
|
2
|
+
import { useCallback, useEffect, useRef, useState } from "react";
|
|
3
|
+
|
|
4
|
+
//#region src/react/hooks/use-database-write.ts
|
|
5
|
+
const IDLE = Object.freeze({
|
|
6
|
+
data: null,
|
|
7
|
+
loading: false,
|
|
8
|
+
error: null
|
|
9
|
+
});
|
|
10
|
+
/**
|
|
11
|
+
* Run a caller's callback without letting it break the write's promise: the
|
|
12
|
+
* call still resolves, and the exception still reaches the page's error
|
|
13
|
+
* handling (and any error tracker) as an uncaught error.
|
|
14
|
+
*/
|
|
15
|
+
function runCallback(callback) {
|
|
16
|
+
try {
|
|
17
|
+
callback();
|
|
18
|
+
} catch (error) {
|
|
19
|
+
if (typeof globalThis.reportError === "function") globalThis.reportError(error);
|
|
20
|
+
else setTimeout(() => {
|
|
21
|
+
throw error;
|
|
22
|
+
});
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* One write hook's state around `send`, which must be stable per entity.
|
|
27
|
+
*
|
|
28
|
+
* A call never rejects, like `useServingInvoke`: it resolves with the result,
|
|
29
|
+
* or with `null` once the failure is in `error`, so a handler needs no
|
|
30
|
+
* `try/catch`. Callers that want an exception use `databaseApi` directly.
|
|
31
|
+
*
|
|
32
|
+
* A write is never aborted: cancelling the request would not undo a committed
|
|
33
|
+
* transaction. A successful call restarts the reads `invalidate` names and
|
|
34
|
+
* resolves once they have reloaded, so a handler that clears its form sees the
|
|
35
|
+
* new rows already on screen. Only the latest call of a hook updates its
|
|
36
|
+
* state; callbacks run for every call, even after the hook unmounts, since the
|
|
37
|
+
* rows did change.
|
|
38
|
+
*/
|
|
39
|
+
function useDatabaseWrite(send, options) {
|
|
40
|
+
const [state, setState] = useState(IDLE);
|
|
41
|
+
const latest = useRef(null);
|
|
42
|
+
const optionsRef = useRef(options);
|
|
43
|
+
useEffect(() => {
|
|
44
|
+
optionsRef.current = options;
|
|
45
|
+
});
|
|
46
|
+
const mutate = useCallback(async (...args) => {
|
|
47
|
+
const call = Symbol("database write");
|
|
48
|
+
latest.current = call;
|
|
49
|
+
const settle = (next) => {
|
|
50
|
+
if (latest.current === call) setState(next);
|
|
51
|
+
};
|
|
52
|
+
settle({
|
|
53
|
+
data: null,
|
|
54
|
+
loading: true,
|
|
55
|
+
error: null
|
|
56
|
+
});
|
|
57
|
+
let data;
|
|
58
|
+
try {
|
|
59
|
+
data = await send(...args);
|
|
60
|
+
} catch (cause) {
|
|
61
|
+
const error = asDatabaseApiError(cause);
|
|
62
|
+
settle({
|
|
63
|
+
data: null,
|
|
64
|
+
loading: false,
|
|
65
|
+
error
|
|
66
|
+
});
|
|
67
|
+
const { onError } = optionsRef.current;
|
|
68
|
+
if (onError) runCallback(() => onError(error, args));
|
|
69
|
+
return null;
|
|
70
|
+
}
|
|
71
|
+
await invalidateDatabaseReads(optionsRef.current.invalidate ?? true);
|
|
72
|
+
settle({
|
|
73
|
+
data,
|
|
74
|
+
loading: false,
|
|
75
|
+
error: null
|
|
76
|
+
});
|
|
77
|
+
const { onSuccess } = optionsRef.current;
|
|
78
|
+
if (onSuccess) runCallback(() => onSuccess(data, args));
|
|
79
|
+
return data;
|
|
80
|
+
}, [send]);
|
|
81
|
+
const reset = useCallback(() => {
|
|
82
|
+
latest.current = null;
|
|
83
|
+
setState(IDLE);
|
|
84
|
+
}, []);
|
|
85
|
+
return {
|
|
86
|
+
...state,
|
|
87
|
+
mutate,
|
|
88
|
+
reset
|
|
89
|
+
};
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
//#endregion
|
|
93
|
+
export { useDatabaseWrite };
|
|
94
|
+
//# sourceMappingURL=use-database-write.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"use-database-write.js","names":[],"sources":["../../../src/react/hooks/use-database-write.ts"],"sourcesContent":["import { useCallback, useEffect, useRef, useState } from \"react\";\n\nimport type { DatabaseApiError } from \"@/js/database/errors\";\n\nimport {\n asDatabaseApiError,\n type DatabaseInvalidation,\n invalidateDatabaseReads,\n} from \"./database-request-store\";\n\nexport type { DatabaseInvalidation } from \"./database-request-store\";\n\n/** Latest state of a database write hook. */\nexport interface UseDatabaseWriteState<T> {\n /** The latest call's result, or `null` before it answers. */\n data: T | null;\n /**\n * Whether the latest call is in flight, including the reload of the reads\n * it restarts.\n */\n loading: boolean;\n /**\n * Why the latest call failed: `NOT_EXPOSED` when no route exists,\n * `OUTCOME_UNKNOWN` when it may have committed without an answer.\n */\n error: DatabaseApiError | null;\n}\n\n/** Options every database write hook takes. */\nexport interface UseDatabaseWriteOptions {\n /**\n * Reads to restart once a write succeeds. Default `true`: every mounted\n * database read, since a server hook may write other tables in the same\n * transaction. A table list restarts only the reads that show those tables,\n * directly or through an include; `false` restarts none.\n */\n invalidate?: DatabaseInvalidation;\n}\n\n/** The generic write lifecycle's callbacks, before each hook names its args. */\ninterface WriteCallbacks<Args extends unknown[], T> {\n invalidate?: DatabaseInvalidation;\n onSuccess?: (data: T, args: Args) => void;\n onError?: (error: DatabaseApiError, args: Args) => void;\n}\n\ninterface DatabaseWrite<\n Args extends unknown[],\n T,\n> extends UseDatabaseWriteState<T> {\n mutate(...args: Args): Promise<T | null>;\n reset(): void;\n}\n\nconst IDLE: UseDatabaseWriteState<never> = Object.freeze({\n data: null,\n loading: false,\n error: null,\n});\n\n/**\n * Run a caller's callback without letting it break the write's promise: the\n * call still resolves, and the exception still reaches the page's error\n * handling (and any error tracker) as an uncaught error.\n */\nfunction runCallback(callback: () => void): void {\n try {\n callback();\n } catch (error) {\n if (typeof globalThis.reportError === \"function\") {\n globalThis.reportError(error);\n } else {\n setTimeout(() => {\n throw error;\n });\n }\n }\n}\n\n/**\n * One write hook's state around `send`, which must be stable per entity.\n *\n * A call never rejects, like `useServingInvoke`: it resolves with the result,\n * or with `null` once the failure is in `error`, so a handler needs no\n * `try/catch`. Callers that want an exception use `databaseApi` directly.\n *\n * A write is never aborted: cancelling the request would not undo a committed\n * transaction. A successful call restarts the reads `invalidate` names and\n * resolves once they have reloaded, so a handler that clears its form sees the\n * new rows already on screen. Only the latest call of a hook updates its\n * state; callbacks run for every call, even after the hook unmounts, since the\n * rows did change.\n */\nexport function useDatabaseWrite<Args extends unknown[], T>(\n send: (...args: Args) => Promise<T>,\n options: WriteCallbacks<Args, T>,\n): DatabaseWrite<Args, T> {\n const [state, setState] = useState<UseDatabaseWriteState<T>>(IDLE);\n const latest = useRef<symbol | null>(null);\n\n // Read at call time, so inline callbacks and an inline `invalidate` list do\n // not change `mutate`'s identity on every render.\n const optionsRef = useRef(options);\n useEffect(() => {\n optionsRef.current = options;\n });\n\n const mutate = useCallback(\n async (...args: Args): Promise<T | null> => {\n const call = Symbol(\"database write\");\n latest.current = call;\n // React ignores a state update after unmount, so only staleness matters.\n const settle = (next: UseDatabaseWriteState<T>) => {\n if (latest.current === call) setState(next);\n };\n\n settle({ data: null, loading: true, error: null });\n let data: T;\n try {\n data = await send(...args);\n } catch (cause) {\n const error = asDatabaseApiError(cause);\n settle({ data: null, loading: false, error });\n const { onError } = optionsRef.current;\n if (onError) runCallback(() => onError(error, args));\n return null;\n }\n // Hold `loading` until the restarted reads answer, so the hook does not\n // report success beside rows that still show the old state.\n await invalidateDatabaseReads(optionsRef.current.invalidate ?? true);\n settle({ data, loading: false, error: null });\n const { onSuccess } = optionsRef.current;\n if (onSuccess) runCallback(() => onSuccess(data, args));\n return data;\n },\n [send],\n );\n\n // A call still in flight keeps running, but no longer reports here.\n const reset = useCallback(() => {\n latest.current = null;\n setState(IDLE);\n }, []);\n\n return { ...state, mutate, reset };\n}\n"],"mappings":";;;;AAsDA,MAAM,OAAqC,OAAO,OAAO;CACvD,MAAM;CACN,SAAS;CACT,OAAO;CACR,CAAC;;;;;;AAOF,SAAS,YAAY,UAA4B;AAC/C,KAAI;AACF,YAAU;UACH,OAAO;AACd,MAAI,OAAO,WAAW,gBAAgB,WACpC,YAAW,YAAY,MAAM;MAE7B,kBAAiB;AACf,SAAM;IACN;;;;;;;;;;;;;;;;;AAmBR,SAAgB,iBACd,MACA,SACwB;CACxB,MAAM,CAAC,OAAO,YAAY,SAAmC,KAAK;CAClE,MAAM,SAAS,OAAsB,KAAK;CAI1C,MAAM,aAAa,OAAO,QAAQ;AAClC,iBAAgB;AACd,aAAW,UAAU;GACrB;CAEF,MAAM,SAAS,YACb,OAAO,GAAG,SAAkC;EAC1C,MAAM,OAAO,OAAO,iBAAiB;AACrC,SAAO,UAAU;EAEjB,MAAM,UAAU,SAAmC;AACjD,OAAI,OAAO,YAAY,KAAM,UAAS,KAAK;;AAG7C,SAAO;GAAE,MAAM;GAAM,SAAS;GAAM,OAAO;GAAM,CAAC;EAClD,IAAI;AACJ,MAAI;AACF,UAAO,MAAM,KAAK,GAAG,KAAK;WACnB,OAAO;GACd,MAAM,QAAQ,mBAAmB,MAAM;AACvC,UAAO;IAAE,MAAM;IAAM,SAAS;IAAO;IAAO,CAAC;GAC7C,MAAM,EAAE,YAAY,WAAW;AAC/B,OAAI,QAAS,mBAAkB,QAAQ,OAAO,KAAK,CAAC;AACpD,UAAO;;AAIT,QAAM,wBAAwB,WAAW,QAAQ,cAAc,KAAK;AACpE,SAAO;GAAE;GAAM,SAAS;GAAO,OAAO;GAAM,CAAC;EAC7C,MAAM,EAAE,cAAc,WAAW;AACjC,MAAI,UAAW,mBAAkB,UAAU,MAAM,KAAK,CAAC;AACvD,SAAO;IAET,CAAC,KAAK,CACP;CAGD,MAAM,QAAQ,kBAAkB;AAC9B,SAAO,UAAU;AACjB,WAAS,KAAK;IACb,EAAE,CAAC;AAEN,QAAO;EAAE,GAAG;EAAO;EAAQ;EAAO"}
|
|
@@ -73,6 +73,17 @@ npx @databricks/appkit generate-types [rootDir] [outFile] [warehouseId]
|
|
|
73
73
|
|
|
74
74
|
```
|
|
75
75
|
|
|
76
|
+
### Authentication[](#authentication "Direct link to Authentication")
|
|
77
|
+
|
|
78
|
+
Type generation (query `DESCRIBE`, warehouse state/start, metric views, and serving endpoint schemas) uses the Databricks SDK's default auth chain (`DATABRICKS_HOST`, OAuth/PAT env vars, `~/.databrickscfg`) unless one of these optional, dev-only overrides is set. They apply to the CLI, its background refresh, and the Vite plugin, and are checked in this order:
|
|
79
|
+
|
|
80
|
+
| Variable | Effect |
|
|
81
|
+
| -------------------------------------- | ---------------------------------------------------------------------------------------------------------- |
|
|
82
|
+
| `APPKIT_DEV_PROFILE` | Use this `~/.databrickscfg` profile. |
|
|
83
|
+
| `APPKIT_DEV_HOST` + `APPKIT_DEV_TOKEN` | Use this host and bearer token (PAT auth). Both must be non-empty; if either is missing, they are ignored. |
|
|
84
|
+
|
|
85
|
+
These variables override **typegen auth only**. Runtime clients (service context, connectors, Lakebase, agents) always use default auth, i.e. the app's service principal once deployed. If an override is set and a request fails, typegen reports the error as usual; it does not retry with default auth.
|
|
86
|
+
|
|
76
87
|
### Warehouse readiness and the `--wait` flag[](#warehouse-readiness-and-the---wait-flag "Direct link to warehouse-readiness-and-the---wait-flag")
|
|
77
88
|
|
|
78
89
|
By default, `generate-types` is **non-blocking**: it never waits on — or fails because of — your SQL warehouse. It writes the best types it can immediately (reusing cached types where the query is unchanged, otherwise `result: unknown`) and then spawns a detached background worker that refreshes the real types once the warehouse is ready. This keeps `npm install` (postinstall) and `npm run dev` (predev) fast and resilient to a cold or briefly-unreachable warehouse. The dev Vite plugin behaves the same way: types appear instantly and refresh in place once the warehouse is live.
|
package/docs/plugins/database.md
CHANGED
|
@@ -174,7 +174,7 @@ The callback deadline does not cancel arbitrary JavaScript, HTTP requests, or ot
|
|
|
174
174
|
|
|
175
175
|
Run `appkit generate-types` or use the AppKit Vite plugin to write `shared/appkit-types/database.d.ts`, and include it in the client's TypeScript project. It binds the server registry and a shared global interface used by `@databricks/appkit-ui/js/beta`; server-only apps do not need the UI package or `skipLibCheck`. Until the file exists, every entity name is a type error.
|
|
176
176
|
|
|
177
|
-
The client finds routes in the endpoint map the server embeds in the page. When the `api` configuration does not expose an operation, a call to it fails with `NOT_EXPOSED` and sends no request.
|
|
177
|
+
The client finds routes in the endpoint map the server embeds in the page. When the `api` configuration does not expose an operation, a call to it fails with `NOT_EXPOSED` and sends no request. The page also carries the relations between exposed tables, as relation and table names only, so the [React hooks](#refresh-reads-after-a-write) can tell which reads a write affects. These are the names `include` already accepts.
|
|
178
178
|
|
|
179
179
|
### Calls[](#calls "Direct link to Calls")
|
|
180
180
|
|
|
@@ -243,19 +243,238 @@ The answered row is the public row the database holds after any `before*` hook r
|
|
|
243
243
|
|
|
244
244
|
A `DatabaseApiError` has a stable `code`, the HTTP `status`, a `message`, and `details`. Each detail is a `{ path, message }` pair that names a public request field. Branch on `code` rather than `message`.
|
|
245
245
|
|
|
246
|
-
| `code` | `status` | Meaning
|
|
247
|
-
| ------------------------ | ---------------------------------- |
|
|
248
|
-
| `NOT_EXPOSED` | `null` | No published route for the operation. Nothing was sent
|
|
249
|
-
| `INVALID_REQUEST` | 400 or `null` | Malformed or unsupported parameters
|
|
250
|
-
| `FORBIDDEN` | 403 | The database refused the operation
|
|
251
|
-
| `NOT_FOUND` | 404 | No row has this id
|
|
252
|
-
| `CONFLICT` | 409 | A constraint rejected the change
|
|
253
|
-
| `PAYLOAD_TOO_LARGE` | 413 | The response exceeded the size limit
|
|
254
|
-
| `UNSUPPORTED_MEDIA_TYPE` | 415 | The request body was not JSON
|
|
255
|
-
| `VALIDATION_FAILED` | 422 | A value failed validation
|
|
256
|
-
| `TRANSIENT` | 503 or `null` | Temporarily unavailable, or a read received no response
|
|
257
|
-
| `OUTCOME_UNKNOWN` | `null` or a successful HTTP status | A write received no usable response; it may have committed. Check before retrying
|
|
258
|
-
| `INTERNAL` | 500 or other | Any other failure
|
|
246
|
+
| `code` | `status` | Meaning |
|
|
247
|
+
| ------------------------ | ---------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
|
|
248
|
+
| `NOT_EXPOSED` | `null` | No published route for the operation. Nothing was sent |
|
|
249
|
+
| `INVALID_REQUEST` | 400 or `null` | Malformed or unsupported parameters. `null` when the client refused them before sending: params that cannot be encoded, or an id of `""`, `"."`, or `".."`, which would resolve to another route |
|
|
250
|
+
| `FORBIDDEN` | 403 | The database refused the operation |
|
|
251
|
+
| `NOT_FOUND` | 404 | No row has this id |
|
|
252
|
+
| `CONFLICT` | 409 | A constraint rejected the change |
|
|
253
|
+
| `PAYLOAD_TOO_LARGE` | 413 | The response exceeded the size limit |
|
|
254
|
+
| `UNSUPPORTED_MEDIA_TYPE` | 415 | The request body was not JSON |
|
|
255
|
+
| `VALIDATION_FAILED` | 422 | A value failed validation |
|
|
256
|
+
| `TRANSIENT` | 503 or `null` | Temporarily unavailable, or a read received no response |
|
|
257
|
+
| `OUTCOME_UNKNOWN` | `null` or a successful HTTP status | A write received no usable response; it may have committed. Check before retrying |
|
|
258
|
+
| `INTERNAL` | 500 or other | Any other failure |
|
|
259
|
+
|
|
260
|
+
## React hooks (beta)[](#react-hooks-beta "Direct link to React hooks (beta)")
|
|
261
|
+
|
|
262
|
+
`@databricks/appkit-ui/react/beta` provides React hooks over the [browser client](#browser-client-beta). They take the same entity, id, and [parameters](#parameters) as `databaseApi`, need the same [setup](#setup), and report a failure as the same [`DatabaseApiError`](#errors) in `error`.
|
|
263
|
+
|
|
264
|
+
### Read a list[](#read-a-list "Direct link to Read a list")
|
|
265
|
+
|
|
266
|
+
```tsx
|
|
267
|
+
import { useDatabaseList } from "@databricks/appkit-ui/react/beta";
|
|
268
|
+
|
|
269
|
+
function Notes({ boardId }: { boardId: number }) {
|
|
270
|
+
const notes = useDatabaseList("notes", {
|
|
271
|
+
where: { board_id: boardId },
|
|
272
|
+
order: { created_at: "desc" },
|
|
273
|
+
limit: 20,
|
|
274
|
+
});
|
|
275
|
+
|
|
276
|
+
if (notes.error) return <p>{notes.error.message}</p>;
|
|
277
|
+
return (
|
|
278
|
+
<ul>
|
|
279
|
+
{notes.data?.items.map((note) => (
|
|
280
|
+
<li key={note.id}>{note.body}</li>
|
|
281
|
+
))}
|
|
282
|
+
</ul>
|
|
283
|
+
);
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
```
|
|
287
|
+
|
|
288
|
+
`data` is the list envelope `{ items, limit, offset }`, or `null` until the first response arrives. To wait for a value the params depend on, pass `null` as the params; the hook stays idle and sends nothing:
|
|
289
|
+
|
|
290
|
+
```tsx
|
|
291
|
+
const notes = useDatabaseList(
|
|
292
|
+
"notes",
|
|
293
|
+
board ? { where: { board_id: board.id }, limit: 20 } : null,
|
|
294
|
+
);
|
|
295
|
+
|
|
296
|
+
```
|
|
297
|
+
|
|
298
|
+
`{ enabled: false }` in the third argument also holds the request.
|
|
299
|
+
|
|
300
|
+
### Paginate[](#paginate "Direct link to Paginate")
|
|
301
|
+
|
|
302
|
+
New params start a new request, and `data` is `null` until it answers. For a paginated list, pass `keepPreviousData: true` to keep showing the previous page while the next one loads. `loading` stays `true` until it arrives, and a failure for the new page shows no stale rows.
|
|
303
|
+
|
|
304
|
+
```tsx
|
|
305
|
+
const [offset, setOffset] = useState(0);
|
|
306
|
+
const notes = useDatabaseList(
|
|
307
|
+
"notes",
|
|
308
|
+
{ order: { id: "desc" }, limit: 20, offset },
|
|
309
|
+
{ keepPreviousData: true },
|
|
310
|
+
);
|
|
311
|
+
|
|
312
|
+
<button disabled={notes.loading} onClick={() => setOffset(offset + 20)}>
|
|
313
|
+
Next
|
|
314
|
+
</button>;
|
|
315
|
+
|
|
316
|
+
```
|
|
317
|
+
|
|
318
|
+
### Read one record[](#read-one-record "Direct link to Read one record")
|
|
319
|
+
|
|
320
|
+
```tsx
|
|
321
|
+
import { useDatabaseRecord } from "@databricks/appkit-ui/react/beta";
|
|
322
|
+
|
|
323
|
+
const board = useDatabaseRecord("boards", boardId, {
|
|
324
|
+
include: { notes: { limit: 20, include: { note_events: { limit: 5 } } } },
|
|
325
|
+
});
|
|
326
|
+
board.data?.notes[0]?.note_events;
|
|
327
|
+
|
|
328
|
+
```
|
|
329
|
+
|
|
330
|
+
Only tables with a public primary key have a detail route, so a keyless table or a table with a private key is a type error here. A `null` or `undefined` id holds the hook without a request. A missing row reports `NOT_FOUND`, and a refetch that finds the row deleted clears `data` rather than showing it beside the error. An id of `""`, `"."`, or `".."` reports `INVALID_REQUEST` without a request. To pass options without params, use `{}` for the params: `useDatabaseRecord("boards", boardId, {}, { keepPreviousData: true })`.
|
|
331
|
+
|
|
332
|
+
### Request lifecycle[](#request-lifecycle "Direct link to Request lifecycle")
|
|
333
|
+
|
|
334
|
+
* Hooks that request the same entity with parameters that encode to the same query share one request while any of them is mounted. An inline parameter object does not refetch on every render.
|
|
335
|
+
* `refetch()` aborts the in-flight request and sends it again. The last `data` stays visible while it loads and if it fails, except for `NOT_FOUND`.
|
|
336
|
+
* The request is aborted once the last hook using it unmounts. Nothing is cached after that. A React Strict Mode remount reuses the in-flight request.
|
|
337
|
+
* `error` keeps its identity across renders until it changes, so an effect that depends on it, such as a toast, runs once per failure.
|
|
338
|
+
* A successful write through a write hook restarts mounted reads. See [Refresh reads after a write](#refresh-reads-after-a-write).
|
|
339
|
+
|
|
340
|
+
### Serializer-shaped reads[](#serializer-shaped-reads "Direct link to Serializer-shaped reads")
|
|
341
|
+
|
|
342
|
+
A read serializer can change the rows a list or detail route returns. The `shape` option types the result, and can check it. The entity, id, and parameters are still checked against the generated registry either way.
|
|
343
|
+
|
|
344
|
+
To check each row at runtime, pass a function that takes one decoded row and returns it typed, such as a zod schema's `parse`. It runs once per response, on each list item or on the record, and its return value becomes the row. If it throws, the read fails with `INTERNAL`; the thrown error is in `error.cause`, not in the message, since it may quote row values.
|
|
345
|
+
|
|
346
|
+
```tsx
|
|
347
|
+
import { useDatabaseList } from "@databricks/appkit-ui/react/beta";
|
|
348
|
+
import { z } from "zod";
|
|
349
|
+
|
|
350
|
+
// server: serialize: (row) => ({ id: row.id, excerpt: String(row.body).slice(0, 80) })
|
|
351
|
+
const NoteCard = z.object({ id: z.number(), excerpt: z.string() });
|
|
352
|
+
|
|
353
|
+
const notes = useDatabaseList(
|
|
354
|
+
"notes",
|
|
355
|
+
{ limit: 20 },
|
|
356
|
+
{ shape: NoteCard.parse },
|
|
357
|
+
);
|
|
358
|
+
notes.data?.items[0]?.excerpt;
|
|
359
|
+
|
|
360
|
+
```
|
|
361
|
+
|
|
362
|
+
Zod 4's `parse` works unbound. For a library whose parse method needs its schema as `this`, pass an arrow: `shape: (row) => schema.parse(row)`.
|
|
363
|
+
|
|
364
|
+
To only declare the type, pass `serialized<T>()`. Nothing checks it at runtime, so keep `T` in step with the serializer.
|
|
365
|
+
|
|
366
|
+
```tsx
|
|
367
|
+
import { serialized, useDatabaseList } from "@databricks/appkit-ui/react/beta";
|
|
368
|
+
|
|
369
|
+
interface NoteCard {
|
|
370
|
+
id: number;
|
|
371
|
+
excerpt: string;
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
const notes = useDatabaseList(
|
|
375
|
+
"notes",
|
|
376
|
+
{ limit: 20 },
|
|
377
|
+
{ shape: serialized<NoteCard>() },
|
|
378
|
+
);
|
|
379
|
+
|
|
380
|
+
```
|
|
381
|
+
|
|
382
|
+
### Write rows[](#write-rows "Direct link to Write rows")
|
|
383
|
+
|
|
384
|
+
```tsx
|
|
385
|
+
import { useState } from "react";
|
|
386
|
+
import { useDatabaseCreate } from "@databricks/appkit-ui/react/beta";
|
|
387
|
+
|
|
388
|
+
function AddNote({ boardId }: { boardId: number }) {
|
|
389
|
+
const notes = useDatabaseCreate("notes");
|
|
390
|
+
const [body, setBody] = useState("");
|
|
391
|
+
|
|
392
|
+
async function submit(event: React.FormEvent) {
|
|
393
|
+
event.preventDefault();
|
|
394
|
+
const note = await notes.create({ board_id: boardId, author: "ada", body });
|
|
395
|
+
if (note) setBody("");
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
return (
|
|
399
|
+
<form onSubmit={submit}>
|
|
400
|
+
<input value={body} onChange={(event) => setBody(event.target.value)} />
|
|
401
|
+
<button disabled={notes.loading}>Add</button>
|
|
402
|
+
{notes.error && (
|
|
403
|
+
<p>{notes.error.details[0]?.message ?? notes.error.message}</p>
|
|
404
|
+
)}
|
|
405
|
+
</form>
|
|
406
|
+
);
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
```
|
|
410
|
+
|
|
411
|
+
| Hook | Call | Route | Resolves with |
|
|
412
|
+
| --------------------------- | -------------------- | ----------------------------------- | -------------------------- |
|
|
413
|
+
| `useDatabaseCreate(entity)` | `create(values)` | `POST /api/database/<entity>` | The created row, or `null` |
|
|
414
|
+
| `useDatabaseUpdate(entity)` | `update(id, values)` | `PATCH /api/database/<entity>/:id` | The updated row, or `null` |
|
|
415
|
+
| `useDatabaseDelete(entity)` | `remove(id)` | `DELETE /api/database/<entity>/:id` | `true`, or `false` |
|
|
416
|
+
|
|
417
|
+
Each hook also returns `loading`, `error`, and `reset()`. The create and update hooks return `data`, the row the latest call answered with. Like `useServingInvoke`, a call never rejects: a failure resolves `null` (or `false` for `remove`) and the `DatabaseApiError` is in `error`, so a handler needs no `try/catch`. To handle failures as exceptions, call `databaseApi` instead.
|
|
418
|
+
|
|
419
|
+
A successful call resolves once the reads it restarts have reloaded, and `loading` stays `true` until then. A handler that clears its form after `await create(...)` therefore sees the new row already in the lists. A read that fails to reload does not fail the write. If another write or a manual refetch supersedes a reload, the waiting call follows the current run of each read rather than resolving on the cancelled run. Reads with no subscribers stop holding the write open. After teardown, remounting the same URL creates a new entry, not part of that write's refresh.
|
|
420
|
+
|
|
421
|
+
Values follow the same [rules](#values) as `databaseApi.create` and `update`. Update and delete need a public primary key, like record reads.
|
|
422
|
+
|
|
423
|
+
### Observe every write[](#observe-every-write "Direct link to Observe every write")
|
|
424
|
+
|
|
425
|
+
`error` only shows the latest call, and only while a component renders it. To report every outcome, for example to a toast or an error tracker, pass `onSuccess` and `onError`:
|
|
426
|
+
|
|
427
|
+
```tsx
|
|
428
|
+
const notes = useDatabaseCreate("notes", {
|
|
429
|
+
onSuccess: (note) => toast(`Added note #${note.id}`),
|
|
430
|
+
onError: (error, values) => report(error, { board: values.board_id }),
|
|
431
|
+
});
|
|
432
|
+
|
|
433
|
+
```
|
|
434
|
+
|
|
435
|
+
| Hook | `onSuccess` | `onError` |
|
|
436
|
+
| ------------------- | ------------------- | --------------------- |
|
|
437
|
+
| `useDatabaseCreate` | `(row, values)` | `(error, values)` |
|
|
438
|
+
| `useDatabaseUpdate` | `(row, id, values)` | `(error, id, values)` |
|
|
439
|
+
| `useDatabaseDelete` | `(id)` | `(error, id)` |
|
|
440
|
+
|
|
441
|
+
The callbacks run for every call, including one a later call superseded and one that finishes after the component unmounted, once the hook's state has settled. `onSuccess` runs after the restarted reads reload. A callback that throws does not change what the call resolves with; its error is reported as uncaught. Inline callbacks do not change the identity of `create`, `update`, or `remove`.
|
|
442
|
+
|
|
443
|
+
### Refresh reads after a write[](#refresh-reads-after-a-write "Direct link to Refresh reads after a write")
|
|
444
|
+
|
|
445
|
+
When a write succeeds, every mounted database read restarts, so lists and includes that show the changed row refresh without a manual `refetch()`. Each read keeps its last `data` while it reloads. A failed write restarts nothing.
|
|
446
|
+
|
|
447
|
+
The default restarts every read because a [mutation hook](#mutation-hooks) on the server may write other tables in the same transaction, and the browser cannot see that. When a page mounts many reads, pass `invalidate` to restart only the reads that show the tables you name, or none:
|
|
448
|
+
|
|
449
|
+
```ts
|
|
450
|
+
// A board's title changes only boards rows.
|
|
451
|
+
useDatabaseUpdate("boards", { invalidate: ["boards"] });
|
|
452
|
+
|
|
453
|
+
// Restart nothing. Call refetch() on the reads that need it.
|
|
454
|
+
useDatabaseCreate("notes", { invalidate: false });
|
|
455
|
+
|
|
456
|
+
```
|
|
457
|
+
|
|
458
|
+
A read shows a table when it is rooted at it or when its `include` reaches it. The server publishes the relations between exposed tables, so `invalidate: ["notes"]` also restarts a `boards` read that includes `notes`, and a `boards` read that includes `notes` and then `note_events`. A read whose include the server did not describe is restarted by any table list.
|
|
459
|
+
|
|
460
|
+
A write the hooks did not make, such as a `databaseApi` call or one of your own routes that changes rows, does not restart reads by itself. Call `invalidateDatabaseReads` from `@databricks/appkit-ui/react/beta` afterwards. It takes the same scope as `invalidate`, defaults to every mounted read, and resolves once the restarted reads have reloaded:
|
|
461
|
+
|
|
462
|
+
```ts
|
|
463
|
+
import { invalidateDatabaseReads } from "@databricks/appkit-ui/react/beta";
|
|
464
|
+
|
|
465
|
+
await fetch(`/api/boards/${boardId}/archive`, { method: "POST" });
|
|
466
|
+
await invalidateDatabaseReads(["boards", "notes"]);
|
|
467
|
+
|
|
468
|
+
```
|
|
469
|
+
|
|
470
|
+
### Write lifecycle[](#write-lifecycle "Direct link to Write lifecycle")
|
|
471
|
+
|
|
472
|
+
* A write is never aborted, even when its component unmounts. Aborting the request would not undo a transaction the server already committed.
|
|
473
|
+
* A write that succeeds after its component unmounts still restarts reads and runs `onSuccess`, because the rows did change.
|
|
474
|
+
* Only the latest call updates `data`, `loading`, and `error`. An earlier call still resolves for the code that awaits it, with `null` if it failed.
|
|
475
|
+
* `invalidate`, `onSuccess`, and `onError` are read when a call settles, so the options of the latest render apply.
|
|
476
|
+
* `reset()` returns the hook to idle. A call in flight keeps running, but no longer updates the hook.
|
|
477
|
+
* Writes are not queued or deduplicated. Each call sends its own request, so disable the submit control while `loading`.
|
|
259
478
|
|
|
260
479
|
## API reference[](#api-reference "Direct link to API reference")
|
|
261
480
|
|