@rebasepro/cli 0.31.0 → 0.33.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/{agent-setup-DqAcoDcn.js → agent-setup-Cg_zBWoW.js} +3 -3
- package/dist/{agent-setup-DqAcoDcn.js.map → agent-setup-Cg_zBWoW.js.map} +1 -1
- package/dist/api-TbmW33D7.js +275 -0
- package/dist/api-TbmW33D7.js.map +1 -0
- package/dist/{api-keys-eIUjMqWn.js → api-keys-fPQ55DCm.js} +151 -158
- package/dist/api-keys-fPQ55DCm.js.map +1 -0
- package/dist/{apps-DExO4PEl.js → apps-DBTRoOeP.js} +18 -13
- package/dist/apps-DBTRoOeP.js.map +1 -0
- package/dist/{args-CaCcrYE1.js → args-DHyrshtI.js} +3 -132
- package/dist/args-DHyrshtI.js.map +1 -0
- package/dist/{atlas-dev-database-DOCKk6ht.js → atlas-dev-database-D6h65f2x.js} +3 -3
- package/dist/{atlas-dev-database-DOCKk6ht.js.map → atlas-dev-database-D6h65f2x.js.map} +1 -1
- package/dist/{auth-ofQETpM5.js → auth-BpyYLEFY.js} +93 -12
- package/dist/auth-BpyYLEFY.js.map +1 -0
- package/dist/auth-session-B6aT0Dyj.js +371 -0
- package/dist/auth-session-B6aT0Dyj.js.map +1 -0
- package/dist/{backend-guard-C0mVkXBw.js → backend-guard-Cf8eMK_f.js} +2 -2
- package/dist/{backend-guard-C0mVkXBw.js.map → backend-guard-Cf8eMK_f.js.map} +1 -1
- package/dist/{branch-pointer-DMPyvZoK.js → branch-pointer-BJOF2Ubv.js} +1 -1
- package/dist/{build-CA5R07tw.js → build-E5hfEWKj.js} +23 -10
- package/dist/build-E5hfEWKj.js.map +1 -0
- package/dist/{bundle-DgILeA5b.js → bundle-CIiKGrte.js} +78 -12
- package/dist/bundle-CIiKGrte.js.map +1 -0
- package/dist/bundle.d.ts +31 -1
- package/dist/{cloud-CYMk92iG.js → cloud-DNJyUU0T.js} +1715 -1516
- package/dist/cloud-DNJyUU0T.js.map +1 -0
- package/dist/{cms-directories-BK3vcswg.js → cms-directories-BaV-Is9a.js} +2 -2
- package/dist/{cms-directories-BK3vcswg.js.map → cms-directories-BaV-Is9a.js.map} +1 -1
- package/dist/codemod/collections-to-tables/backend.d.ts +0 -2
- package/dist/codemod/collections-to-tables/customization.d.ts +7 -1
- package/dist/codemod/collections-to-tables/modules.d.ts +32 -0
- package/dist/codemod/collections-to-tables/plan-context.d.ts +7 -1
- package/dist/{command-D5lhW_-B.js → command-Bks5xkrQ.js} +89 -44
- package/dist/command-Bks5xkrQ.js.map +1 -0
- package/dist/commands/api-keys.d.ts +89 -52
- package/dist/commands/api.d.ts +114 -0
- package/dist/commands/auth-session.d.ts +94 -0
- package/dist/commands/auth.d.ts +1 -1
- package/dist/commands/cloud/alerts.d.ts +29 -0
- package/dist/commands/cloud/context.d.ts +8 -0
- package/dist/commands/cloud/debug.d.ts +16 -1
- package/dist/commands/cloud/deploy-hooks.d.ts +19 -0
- package/dist/commands/cloud/deploy.d.ts +25 -0
- package/dist/commands/cloud/env.d.ts +12 -1
- package/dist/commands/cloud/index.d.ts +5 -0
- package/dist/commands/cloud/maintenance.d.ts +26 -1
- package/dist/commands/cloud/not-served.d.ts +27 -0
- package/dist/commands/cloud/orgs.d.ts +5 -0
- package/dist/commands/cloud/resources.d.ts +82 -2
- package/dist/commands/cloud/runtime-logs.d.ts +57 -0
- package/dist/commands/cloud/service-key.d.ts +33 -1
- package/dist/commands/cloud/settings.d.ts +3 -0
- package/dist/commands/cron.d.ts +68 -0
- package/dist/commands/data.d.ts +197 -0
- package/dist/commands/functions.d.ts +38 -0
- package/dist/commands/logs.d.ts +22 -0
- package/dist/commands/rls.d.ts +31 -0
- package/dist/commands/schema-reconcile.d.ts +2 -1
- package/dist/commands/schema-show.d.ts +38 -0
- package/dist/commands/storage-objects.d.ts +88 -0
- package/dist/commands/storage.d.ts +18 -2
- package/dist/commands/users.d.ts +147 -0
- package/dist/{consent-BXLIrMl8.js → consent-UV6ObCME.js} +2 -2
- package/dist/{consent-BXLIrMl8.js.map → consent-UV6ObCME.js.map} +1 -1
- package/dist/{console-DjThnr3f.js → console-BVoYOLAO.js} +6 -6
- package/dist/{console-DjThnr3f.js.map → console-BVoYOLAO.js.map} +1 -1
- package/dist/{context--JwaHaZp.js → context-BOMEoKxn.js} +80 -9
- package/dist/{context--JwaHaZp.js.map → context-BOMEoKxn.js.map} +1 -1
- package/dist/cron-CpUsQ739.js +298 -0
- package/dist/cron-CpUsQ739.js.map +1 -0
- package/dist/cron-ZRXsla0v.js +259 -0
- package/dist/cron-ZRXsla0v.js.map +1 -0
- package/dist/{daemon-w30PsdwV.js → daemon-D5gdG7gx.js} +3 -3
- package/dist/{daemon-w30PsdwV.js.map → daemon-D5gdG7gx.js.map} +1 -1
- package/dist/{daemon-entry-zOC1revO.js → daemon-entry--ummUJnk.js} +2 -2
- package/dist/{daemon-entry-zOC1revO.js.map → daemon-entry--ummUJnk.js.map} +1 -1
- package/dist/data-BJ9AZFUC.js +947 -0
- package/dist/data-BJ9AZFUC.js.map +1 -0
- package/dist/{db-Bz2RFGJj.js → db-D_iF4E-v.js} +38 -34
- package/dist/{db-Bz2RFGJj.js.map → db-D_iF4E-v.js.map} +1 -1
- package/dist/debug-nNbbxAeo.js +1114 -0
- package/dist/debug-nNbbxAeo.js.map +1 -0
- package/dist/{derive-C3ezmY-p.js → derive-Mky_u59_.js} +3 -3
- package/dist/{derive-C3ezmY-p.js.map → derive-Mky_u59_.js.map} +1 -1
- package/dist/{dev-D8TxrE_I.js → dev-bj6dEeSQ.js} +13 -13
- package/dist/{dev-D8TxrE_I.js.map → dev-bj6dEeSQ.js.map} +1 -1
- package/dist/dev-db/pull.d.ts +13 -3
- package/dist/{dev-preflight-DjvcV6SK.js → dev-preflight-BMOf2N6r.js} +2 -2
- package/dist/{dev-preflight-DjvcV6SK.js.map → dev-preflight-BMOf2N6r.js.map} +1 -1
- package/dist/{dev-server-BLxCbQEP.js → dev-server-2XHSHM_q.js} +2 -2
- package/dist/{dev-server-BLxCbQEP.js.map → dev-server-2XHSHM_q.js.map} +1 -1
- package/dist/{doctor-Du-mSxoE.js → doctor-FaBObSlb.js} +29 -10
- package/dist/doctor-FaBObSlb.js.map +1 -0
- package/dist/doctor-environment.d.ts +9 -0
- package/dist/{eject-Bhzd6hgb.js → eject-DK_M9kor.js} +4 -4
- package/dist/{eject-Bhzd6hgb.js.map → eject-DK_M9kor.js.map} +1 -1
- package/dist/{fold-static-CKewnAPX.js → fold-static-2t3UUX4z.js} +10 -6
- package/dist/fold-static-2t3UUX4z.js.map +1 -0
- package/dist/fold-static.d.ts +7 -0
- package/dist/functions-B4JR6EZL.js +120 -0
- package/dist/functions-B4JR6EZL.js.map +1 -0
- package/dist/{generate-view-CTOluXvH.js → generate-view-BMaLQm8H.js} +5 -5
- package/dist/{generate-view-CTOluXvH.js.map → generate-view-BMaLQm8H.js.map} +1 -1
- package/dist/{generate_sdk-De-aLC1L.js → generate_sdk-ByD-gTsK.js} +7 -7
- package/dist/{generate_sdk-De-aLC1L.js.map → generate_sdk-ByD-gTsK.js.map} +1 -1
- package/dist/index.es.js +123 -47
- package/dist/index.es.js.map +1 -1
- package/dist/{init-Dtl-IcXf.js → init-DHCe5mJ5.js} +59 -11
- package/dist/init-DHCe5mJ5.js.map +1 -0
- package/dist/{invoked-command-CG_rIa_o.js → invoked-command-FBeIBS8o.js} +2 -2
- package/dist/{invoked-command-CG_rIa_o.js.map → invoked-command-FBeIBS8o.js.map} +1 -1
- package/dist/last-dev-database-CBVkEUEl.js +2 -0
- package/dist/legacy-layout-DI2VeQSV.js +36 -0
- package/dist/legacy-layout-DI2VeQSV.js.map +1 -0
- package/dist/logs-DpuMukJe.js +192 -0
- package/dist/logs-DpuMukJe.js.map +1 -0
- package/dist/{manifest-C3uLDrrJ.js → manifest-RjqxfCpb.js} +114 -5
- package/dist/manifest-RjqxfCpb.js.map +1 -0
- package/dist/{migrate-VrKoi3nB.js → migrate-CSY9ZDKy.js} +5 -4
- package/dist/{migrate-VrKoi3nB.js.map → migrate-CSY9ZDKy.js.map} +1 -1
- package/dist/{normalize-imports-DwxqEMYq.js → normalize-imports-P86NVfpo.js} +3 -3
- package/dist/{normalize-imports-DwxqEMYq.js.map → normalize-imports-P86NVfpo.js.map} +1 -1
- package/dist/{path-flags-7O5uPBcQ.js → path-flags-ekLdkbra.js} +3 -3
- package/dist/{path-flags-7O5uPBcQ.js.map → path-flags-ekLdkbra.js.map} +1 -1
- package/dist/{prepare-Ccxspoj-.js → prepare-BaJe0Zik.js} +4 -4
- package/dist/{prepare-Ccxspoj-.js.map → prepare-BaJe0Zik.js.map} +1 -1
- package/dist/{project-CLcF5i8c.js → project-DALmhb5R.js} +2 -2
- package/dist/{project-CLcF5i8c.js.map → project-DALmhb5R.js.map} +1 -1
- package/dist/project-command-Cl9EZzjr.js +662 -0
- package/dist/project-command-Cl9EZzjr.js.map +1 -0
- package/dist/{project-schema-CsSOG2gE.js → project-schema-Dm6Jk0Y_.js} +4 -2
- package/dist/{project-schema-CsSOG2gE.js.map → project-schema-Dm6Jk0Y_.js.map} +1 -1
- package/dist/{pull-BMuiUyjb.js → pull-CTIsST6T.js} +66 -5
- package/dist/pull-CTIsST6T.js.map +1 -0
- package/dist/resolve-C36px9tR.js +2 -0
- package/dist/{resources-Dpfs2y8P.js → resources-Db3USuPO.js} +5 -5
- package/dist/{resources-Dpfs2y8P.js.map → resources-Db3USuPO.js.map} +1 -1
- package/dist/rls-BxrQ0P50.js +133 -0
- package/dist/rls-BxrQ0P50.js.map +1 -0
- package/dist/{schema-Dv6nHkb0.js → schema-_FzZEoB8.js} +54 -40
- package/dist/schema-_FzZEoB8.js.map +1 -0
- package/dist/{schema-dir-Cd1kvYbf.js → schema-dir-ChcYfWjP.js} +2 -2
- package/dist/{schema-dir-Cd1kvYbf.js.map → schema-dir-ChcYfWjP.js.map} +1 -1
- package/dist/schema-reconcile-DV14XY4o.js +2 -0
- package/dist/schema-show-h72UJ9zH.js +127 -0
- package/dist/schema-show-h72UJ9zH.js.map +1 -0
- package/dist/{skills-CXjA9TWw.js → skills-DQ2bZGkj.js} +6 -5
- package/dist/{skills-CXjA9TWw.js.map → skills-DQ2bZGkj.js.map} +1 -1
- package/dist/star-nudge.d.ts +28 -0
- package/dist/{start-Bwbtt2W5.js → start-Cjx4W0bJ.js} +7 -7
- package/dist/{start-Bwbtt2W5.js.map → start-Cjx4W0bJ.js.map} +1 -1
- package/dist/{status-BTgTWzlQ.js → status-CDBk25VO.js} +9 -9
- package/dist/{status-BTgTWzlQ.js.map → status-CDBk25VO.js.map} +1 -1
- package/dist/{storage-iTqj5-Av.js → storage-Clc8dLG8.js} +79 -36
- package/dist/storage-Clc8dLG8.js.map +1 -0
- package/dist/storage-objects-CfRKlTDe.js +279 -0
- package/dist/storage-objects-CfRKlTDe.js.map +1 -0
- package/dist/{telemetry-BP_1Cl9r.js → telemetry-DZU2-NCm.js} +5 -4
- package/dist/{telemetry-BP_1Cl9r.js.map → telemetry-DZU2-NCm.js.map} +1 -1
- package/dist/{telemetry-M3HjlyhZ.js → telemetry-EVtASbKb.js} +2 -2
- package/dist/{telemetry-M3HjlyhZ.js.map → telemetry-EVtASbKb.js.map} +1 -1
- package/dist/unknown-command-DnZ2uhGs.js +139 -0
- package/dist/unknown-command-DnZ2uhGs.js.map +1 -0
- package/dist/{upgrade-oZzJ13jM.js → upgrade-ZASvgxWM.js} +41 -9
- package/dist/{upgrade-oZzJ13jM.js.map → upgrade-ZASvgxWM.js.map} +1 -1
- package/dist/users-5PkqBY6R.js +561 -0
- package/dist/users-5PkqBY6R.js.map +1 -0
- package/dist/utils/legacy-layout.d.ts +22 -0
- package/dist/utils/project-command.d.ts +38 -0
- package/dist/utils/project-target.d.ts +193 -0
- package/dist/{verify-BkUVGLqo.js → verify-BdeqNb-V.js} +138 -12
- package/dist/verify-BdeqNb-V.js.map +1 -0
- package/dist/{version-Buyyo1ut.js → version-ONIeo7jl.js} +7 -2
- package/dist/{version-Buyyo1ut.js.map → version-ONIeo7jl.js.map} +1 -1
- package/package.json +10 -10
- package/templates/overlays/baas/backend/package.json +3 -1
- package/templates/template/backend/package.json +3 -1
- package/dist/api-keys-eIUjMqWn.js.map +0 -1
- package/dist/apps-DExO4PEl.js.map +0 -1
- package/dist/args-CaCcrYE1.js.map +0 -1
- package/dist/auth-ofQETpM5.js.map +0 -1
- package/dist/build-CA5R07tw.js.map +0 -1
- package/dist/bundle-DgILeA5b.js.map +0 -1
- package/dist/cloud-CYMk92iG.js.map +0 -1
- package/dist/command-D5lhW_-B.js.map +0 -1
- package/dist/doctor-Du-mSxoE.js.map +0 -1
- package/dist/fold-static-CKewnAPX.js.map +0 -1
- package/dist/init-Dtl-IcXf.js.map +0 -1
- package/dist/last-dev-database-Dc8cP01o.js +0 -2
- package/dist/manifest-C3uLDrrJ.js.map +0 -1
- package/dist/pull-BMuiUyjb.js.map +0 -1
- package/dist/resolve-BY7bSFRT.js +0 -2
- package/dist/schema-Dv6nHkb0.js.map +0 -1
- package/dist/schema-reconcile-CjxLaRHB.js +0 -2
- package/dist/storage-iTqj5-Av.js.map +0 -1
- package/dist/verify-BkUVGLqo.js.map +0 -1
|
@@ -0,0 +1,947 @@
|
|
|
1
|
+
import { n as unknownCommand } from "./unknown-command-DnZ2uhGs.js";
|
|
2
|
+
import { a as wantsHelp, n as parseCommandArgs, t as UsageError } from "./args-DHyrshtI.js";
|
|
3
|
+
import { a as projectTarget, c as requestJson, d as PROJECT_TARGET_FLAGS, g as readJson, i as printProjectHelp, l as startProjectCommand, n as isRecord, o as recordsOf, r as parsedLine, s as reportTargetError, t as cellText, u as stringOf } from "./project-command-Cl9EZzjr.js";
|
|
4
|
+
import { D as isJsonMode, M as note, k as keyValues, l as confirmDestructive, m as emit, st as success, v as fail } from "./context-BOMEoKxn.js";
|
|
5
|
+
import chalk from "chalk";
|
|
6
|
+
import fs from "fs";
|
|
7
|
+
//#region src/commands/data.ts
|
|
8
|
+
/**
|
|
9
|
+
* CLI command: rebase data <action>
|
|
10
|
+
*
|
|
11
|
+
* The rows of a running app's tables, through its REST API — so row-level
|
|
12
|
+
* security, field access, hooks and validation all apply, exactly as they do
|
|
13
|
+
* for the SDK. The same target and credential every project command resolves:
|
|
14
|
+
* the local `rebase dev`, `--url`, `REBASE_BASE_URL`, or `--project <slug>` for
|
|
15
|
+
* a Rebase Cloud project.
|
|
16
|
+
*
|
|
17
|
+
* Filters are the API's own (`?status=eq.published`), passed through
|
|
18
|
+
* unchanged: `--where status=eq.published`, `--where price=gte.10`, and a bare
|
|
19
|
+
* `--where status=draft` for equality. Whatever the API documents, `--where`
|
|
20
|
+
* takes — there is no second dialect to learn or to drift.
|
|
21
|
+
*
|
|
22
|
+
* `rebase console` is the other way into the rows: a local REPL on the
|
|
23
|
+
* database itself. This one goes through the server, and so reaches a deployed
|
|
24
|
+
* project as well.
|
|
25
|
+
*/
|
|
26
|
+
/** Everything the switch below dispatches, for the did-you-mean. */
|
|
27
|
+
var DATA_SUBCOMMANDS = [
|
|
28
|
+
"query",
|
|
29
|
+
"get",
|
|
30
|
+
"count",
|
|
31
|
+
"aggregate",
|
|
32
|
+
"insert",
|
|
33
|
+
"update",
|
|
34
|
+
"delete",
|
|
35
|
+
"import",
|
|
36
|
+
"history",
|
|
37
|
+
"revert",
|
|
38
|
+
"watch"
|
|
39
|
+
];
|
|
40
|
+
/** One page of rows per request when `--all` walks a table. */
|
|
41
|
+
var PAGE_SIZE = 200;
|
|
42
|
+
/** Rows per `POST /bulk` request on an import — the server's own cap is higher; this keeps a failure cheap. */
|
|
43
|
+
var IMPORT_BATCH = 500;
|
|
44
|
+
async function dataCommand(subcommand, rawArgs) {
|
|
45
|
+
startProjectCommand(rawArgs);
|
|
46
|
+
if (!subcommand || subcommand === "--help" || wantsHelp(rawArgs)) {
|
|
47
|
+
printDataHelp();
|
|
48
|
+
return;
|
|
49
|
+
}
|
|
50
|
+
switch (subcommand) {
|
|
51
|
+
case "query":
|
|
52
|
+
await queryRows(rawArgs);
|
|
53
|
+
break;
|
|
54
|
+
case "get":
|
|
55
|
+
await getRow(rawArgs);
|
|
56
|
+
break;
|
|
57
|
+
case "count":
|
|
58
|
+
await countRows(rawArgs);
|
|
59
|
+
break;
|
|
60
|
+
case "aggregate":
|
|
61
|
+
await aggregateRows(rawArgs);
|
|
62
|
+
break;
|
|
63
|
+
case "insert":
|
|
64
|
+
await insertRows(rawArgs);
|
|
65
|
+
break;
|
|
66
|
+
case "update":
|
|
67
|
+
await updateRows(rawArgs);
|
|
68
|
+
break;
|
|
69
|
+
case "delete":
|
|
70
|
+
await deleteRows(rawArgs);
|
|
71
|
+
break;
|
|
72
|
+
case "import":
|
|
73
|
+
await importRows(rawArgs);
|
|
74
|
+
break;
|
|
75
|
+
case "history":
|
|
76
|
+
await rowHistory(rawArgs);
|
|
77
|
+
break;
|
|
78
|
+
case "revert":
|
|
79
|
+
await revertRow(rawArgs);
|
|
80
|
+
break;
|
|
81
|
+
case "watch":
|
|
82
|
+
await watchRows(rawArgs);
|
|
83
|
+
break;
|
|
84
|
+
default: unknownCommand(subcommand, DATA_SUBCOMMANDS, "data");
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
/** `/api/data/<table>`, the table as one encoded path segment. */
|
|
88
|
+
function tablePath(table, ...rest) {
|
|
89
|
+
return [
|
|
90
|
+
"/api/data",
|
|
91
|
+
encodeURIComponent(table),
|
|
92
|
+
...rest.map(encodeURIComponent)
|
|
93
|
+
].join("/");
|
|
94
|
+
}
|
|
95
|
+
/** A table name, refused when it is missing or is not one path segment. */
|
|
96
|
+
function requireTable(positionals, command) {
|
|
97
|
+
const table = positionals[0];
|
|
98
|
+
if (!table) throw new UsageError(`rebase ${command} needs a table: rebase ${command} <table>. \`rebase schema show --remote\` lists them.`);
|
|
99
|
+
if (table.includes("/")) throw new UsageError(`"${table}" is not a table name; nested paths go through \`rebase api\`.`);
|
|
100
|
+
return table;
|
|
101
|
+
}
|
|
102
|
+
/**
|
|
103
|
+
* `--where` conditions as the API's query parameters. `col=op.value` is sent
|
|
104
|
+
* as written; `col=value` is equality, which the API reads the same way.
|
|
105
|
+
* Exported for its tests.
|
|
106
|
+
*/
|
|
107
|
+
function whereParams(conditions) {
|
|
108
|
+
const query = {};
|
|
109
|
+
for (const raw of conditions ?? []) {
|
|
110
|
+
const at = raw.indexOf("=");
|
|
111
|
+
if (at <= 0) throw new UsageError(`--where takes column=op.value, e.g. status=eq.published or price=gte.10 (got "${raw}").`);
|
|
112
|
+
const column = raw.slice(0, at).trim();
|
|
113
|
+
if (RESERVED_PARAMS.has(column)) throw new UsageError(`--where ${column}=… names a query option, not a column; use its own flag (see \`rebase data --help\`).`);
|
|
114
|
+
(query[column] ??= []).push(raw.slice(at + 1));
|
|
115
|
+
}
|
|
116
|
+
return query;
|
|
117
|
+
}
|
|
118
|
+
/** Query keys the API reads as options rather than columns. */
|
|
119
|
+
var RESERVED_PARAMS = /* @__PURE__ */ new Set([
|
|
120
|
+
"limit",
|
|
121
|
+
"offset",
|
|
122
|
+
"page",
|
|
123
|
+
"after",
|
|
124
|
+
"orderBy",
|
|
125
|
+
"include",
|
|
126
|
+
"fields",
|
|
127
|
+
"distinct",
|
|
128
|
+
"count",
|
|
129
|
+
"searchString",
|
|
130
|
+
"or",
|
|
131
|
+
"and",
|
|
132
|
+
"not",
|
|
133
|
+
"where",
|
|
134
|
+
"select",
|
|
135
|
+
"groupBy",
|
|
136
|
+
"deleted",
|
|
137
|
+
"hard"
|
|
138
|
+
]);
|
|
139
|
+
/** `--order-by name` / `--order-by name:desc`, one or several, as the API's `orderBy`. Exported for tests. */
|
|
140
|
+
function orderByParam(values) {
|
|
141
|
+
if (!values || values.length === 0) return void 0;
|
|
142
|
+
if (values.length === 1) return values[0];
|
|
143
|
+
return JSON.stringify(values.map((value) => {
|
|
144
|
+
const [field, direction] = value.split(":");
|
|
145
|
+
return direction ? {
|
|
146
|
+
field,
|
|
147
|
+
direction: direction.toLowerCase()
|
|
148
|
+
} : { field };
|
|
149
|
+
}));
|
|
150
|
+
}
|
|
151
|
+
/** A JSON object from `--json-data`, `--file` or stdin (`--file -`). */
|
|
152
|
+
function readJsonInput(inline, file, what) {
|
|
153
|
+
if (inline !== void 0 && file !== void 0) throw new UsageError(`Give the ${what} once: --data or --file, not both.`);
|
|
154
|
+
let text = inline;
|
|
155
|
+
if (file !== void 0) try {
|
|
156
|
+
text = fs.readFileSync(file === "-" ? 0 : file, "utf8");
|
|
157
|
+
} catch (e) {
|
|
158
|
+
throw new UsageError(`Cannot read ${file}: ${e instanceof Error ? e.message : String(e)}`);
|
|
159
|
+
}
|
|
160
|
+
if (text === void 0) throw new UsageError(`The ${what} is missing: pass --data '{…}' or --file <path> (- for stdin).`);
|
|
161
|
+
try {
|
|
162
|
+
return JSON.parse(text);
|
|
163
|
+
} catch (e) {
|
|
164
|
+
throw new UsageError(`The ${what} is not JSON: ${e instanceof Error ? e.message : String(e)}`);
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
function resolveFormat(raw) {
|
|
168
|
+
if (raw === void 0) return isJsonMode() ? "json" : "table";
|
|
169
|
+
if (raw === "table" || raw === "json" || raw === "ndjson" || raw === "csv") return raw;
|
|
170
|
+
throw new UsageError(`--format takes table, json, ndjson or csv (got "${raw}").`);
|
|
171
|
+
}
|
|
172
|
+
/** One CSV field, quoted when it must be. */
|
|
173
|
+
function csvField(value) {
|
|
174
|
+
const text = cellText(value);
|
|
175
|
+
return /[",\n\r]/.test(text) ? `"${text.replace(/"/g, "\"\"")}"` : text;
|
|
176
|
+
}
|
|
177
|
+
/** The columns of a set of rows, in first-seen order. */
|
|
178
|
+
function columnsOf(rows) {
|
|
179
|
+
const seen = /* @__PURE__ */ new Set();
|
|
180
|
+
for (const row of rows) for (const key of Object.keys(row)) seen.add(key);
|
|
181
|
+
return [...seen];
|
|
182
|
+
}
|
|
183
|
+
/** Rows as a terminal table, cells cut at a readable width. */
|
|
184
|
+
function printTable(rows) {
|
|
185
|
+
if (rows.length === 0) {
|
|
186
|
+
console.log(chalk.gray(" No rows."));
|
|
187
|
+
return;
|
|
188
|
+
}
|
|
189
|
+
const columns = columnsOf(rows);
|
|
190
|
+
const MAX = 40;
|
|
191
|
+
const cut = (text) => text.length > MAX ? `${text.slice(0, MAX - 1)}…` : text;
|
|
192
|
+
const widths = columns.map((column) => Math.max(column.length, ...rows.map((row) => cut(cellText(row[column])).length)));
|
|
193
|
+
console.log(columns.map((column, i) => chalk.bold(column.padEnd(widths[i]))).join(" "));
|
|
194
|
+
console.log(chalk.gray(widths.map((width) => "─".repeat(width)).join(" ")));
|
|
195
|
+
for (const row of rows) console.log(columns.map((column, i) => cut(cellText(row[column])).padEnd(widths[i])).join(" "));
|
|
196
|
+
}
|
|
197
|
+
/** Print rows in a format; `header` says whether CSV starts with a header line. */
|
|
198
|
+
function printRows(rows, format, meta) {
|
|
199
|
+
switch (format) {
|
|
200
|
+
case "json":
|
|
201
|
+
process.stdout.write(`${JSON.stringify(meta === void 0 ? { data: rows } : {
|
|
202
|
+
data: rows,
|
|
203
|
+
meta
|
|
204
|
+
}, null, 2)}\n`);
|
|
205
|
+
break;
|
|
206
|
+
case "ndjson":
|
|
207
|
+
for (const row of rows) process.stdout.write(`${JSON.stringify(row)}\n`);
|
|
208
|
+
break;
|
|
209
|
+
case "csv": {
|
|
210
|
+
const columns = columnsOf(rows);
|
|
211
|
+
process.stdout.write(`${columns.map(csvField).join(",")}\n`);
|
|
212
|
+
for (const row of rows) process.stdout.write(`${columns.map((column) => csvField(row[column])).join(",")}\n`);
|
|
213
|
+
break;
|
|
214
|
+
}
|
|
215
|
+
default: printTable(rows);
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
var QUERY_FLAGS = {
|
|
219
|
+
...PROJECT_TARGET_FLAGS,
|
|
220
|
+
"--where": [String],
|
|
221
|
+
"-w": "--where",
|
|
222
|
+
"--or": String,
|
|
223
|
+
"--order-by": [String],
|
|
224
|
+
"--limit": Number,
|
|
225
|
+
"-n": "--limit",
|
|
226
|
+
"--offset": Number,
|
|
227
|
+
"--fields": String,
|
|
228
|
+
"--include": String,
|
|
229
|
+
"--search": String,
|
|
230
|
+
"--deleted": String,
|
|
231
|
+
"--all": Boolean,
|
|
232
|
+
"--format": String
|
|
233
|
+
};
|
|
234
|
+
async function queryRows(rawArgs) {
|
|
235
|
+
const { flags, positionals } = parsedLine(() => parseCommandArgs({
|
|
236
|
+
spec: QUERY_FLAGS,
|
|
237
|
+
rawArgs,
|
|
238
|
+
commandWords: 2,
|
|
239
|
+
command: "data query",
|
|
240
|
+
maxPositionals: 1
|
|
241
|
+
}));
|
|
242
|
+
const { table, query, format } = parsedLine(() => {
|
|
243
|
+
const t = requireTable(positionals, "data query");
|
|
244
|
+
const q = {
|
|
245
|
+
...whereParams(flags["--where"]),
|
|
246
|
+
or: flags["--or"],
|
|
247
|
+
orderBy: orderByParam(flags["--order-by"]),
|
|
248
|
+
limit: flags["--limit"] !== void 0 ? String(flags["--limit"]) : void 0,
|
|
249
|
+
offset: flags["--offset"] !== void 0 ? String(flags["--offset"]) : void 0,
|
|
250
|
+
fields: flags["--fields"],
|
|
251
|
+
include: flags["--include"],
|
|
252
|
+
searchString: flags["--search"],
|
|
253
|
+
deleted: flags["--deleted"]
|
|
254
|
+
};
|
|
255
|
+
if (flags["--all"] && flags["--offset"] !== void 0) throw new UsageError("--all walks every page from the start; drop --offset.");
|
|
256
|
+
return {
|
|
257
|
+
table: t,
|
|
258
|
+
query: q,
|
|
259
|
+
format: resolveFormat(flags["--format"])
|
|
260
|
+
};
|
|
261
|
+
});
|
|
262
|
+
const target = await projectTarget(flags, { command: "data query" });
|
|
263
|
+
if (!flags["--all"]) {
|
|
264
|
+
const body = await requestJson(target, tablePath(table), `Failed to query ${table}`, { query });
|
|
265
|
+
const rows = recordsOf(isRecord(body) ? body.data : void 0);
|
|
266
|
+
const meta = isRecord(body) ? body.meta : void 0;
|
|
267
|
+
printRows(rows, format, meta);
|
|
268
|
+
if (format === "table" && isRecord(meta) && meta.hasMore === true) note(chalk.gray(`More rows match; pass --all, or --offset ${(flags["--offset"] ?? 0) + rows.length}.`));
|
|
269
|
+
return;
|
|
270
|
+
}
|
|
271
|
+
const pageSize = flags["--limit"] ?? PAGE_SIZE;
|
|
272
|
+
const all = [];
|
|
273
|
+
let offset = 0;
|
|
274
|
+
let csvHeader;
|
|
275
|
+
for (;;) {
|
|
276
|
+
const body = await requestJson(target, tablePath(table), `Failed to query ${table}`, { query: {
|
|
277
|
+
...query,
|
|
278
|
+
limit: String(pageSize),
|
|
279
|
+
offset: String(offset)
|
|
280
|
+
} });
|
|
281
|
+
const rows = recordsOf(isRecord(body) ? body.data : void 0);
|
|
282
|
+
if (format === "ndjson") for (const row of rows) process.stdout.write(`${JSON.stringify(row)}\n`);
|
|
283
|
+
else if (format === "csv") {
|
|
284
|
+
csvHeader ??= columnsOf(rows);
|
|
285
|
+
if (offset === 0) process.stdout.write(`${csvHeader.map(csvField).join(",")}\n`);
|
|
286
|
+
const header = csvHeader;
|
|
287
|
+
for (const row of rows) process.stdout.write(`${header.map((column) => csvField(row[column])).join(",")}\n`);
|
|
288
|
+
} else all.push(...rows);
|
|
289
|
+
const meta = isRecord(body) ? body.meta : void 0;
|
|
290
|
+
if (!(isRecord(meta) && typeof meta.hasMore === "boolean" ? meta.hasMore : rows.length === pageSize) || rows.length === 0) break;
|
|
291
|
+
offset += rows.length;
|
|
292
|
+
}
|
|
293
|
+
if (format === "json" || format === "table") printRows(all, format);
|
|
294
|
+
}
|
|
295
|
+
var GET_ROW_FLAGS = {
|
|
296
|
+
...PROJECT_TARGET_FLAGS,
|
|
297
|
+
"--fields": String,
|
|
298
|
+
"--include": String
|
|
299
|
+
};
|
|
300
|
+
async function getRow(rawArgs) {
|
|
301
|
+
const { flags, positionals } = parsedLine(() => parseCommandArgs({
|
|
302
|
+
spec: GET_ROW_FLAGS,
|
|
303
|
+
rawArgs,
|
|
304
|
+
commandWords: 2,
|
|
305
|
+
command: "data get",
|
|
306
|
+
maxPositionals: 2
|
|
307
|
+
}));
|
|
308
|
+
const { table, id } = parsedLine(() => {
|
|
309
|
+
const t = requireTable(positionals, "data get");
|
|
310
|
+
if (!positionals[1]) throw new UsageError("rebase data get needs a row id: rebase data get <table> <id>.");
|
|
311
|
+
return {
|
|
312
|
+
table: t,
|
|
313
|
+
id: positionals[1]
|
|
314
|
+
};
|
|
315
|
+
});
|
|
316
|
+
const row = await requestJson(await projectTarget(flags, { command: "data get" }), tablePath(table, id), `Failed to read ${table}/${id}`, { query: {
|
|
317
|
+
fields: flags["--fields"],
|
|
318
|
+
include: flags["--include"]
|
|
319
|
+
} });
|
|
320
|
+
emit(() => {
|
|
321
|
+
if (!isRecord(row)) return console.log(cellText(row));
|
|
322
|
+
keyValues(Object.entries(row).map(([key, value]) => [key, cellText(value)]));
|
|
323
|
+
}, row);
|
|
324
|
+
}
|
|
325
|
+
var COUNT_FLAGS = {
|
|
326
|
+
...PROJECT_TARGET_FLAGS,
|
|
327
|
+
"--where": [String],
|
|
328
|
+
"-w": "--where",
|
|
329
|
+
"--or": String,
|
|
330
|
+
"--search": String
|
|
331
|
+
};
|
|
332
|
+
async function countRows(rawArgs) {
|
|
333
|
+
const { flags, positionals } = parsedLine(() => parseCommandArgs({
|
|
334
|
+
spec: COUNT_FLAGS,
|
|
335
|
+
rawArgs,
|
|
336
|
+
commandWords: 2,
|
|
337
|
+
command: "data count",
|
|
338
|
+
maxPositionals: 1
|
|
339
|
+
}));
|
|
340
|
+
const { table, query } = parsedLine(() => ({
|
|
341
|
+
table: requireTable(positionals, "data count"),
|
|
342
|
+
query: {
|
|
343
|
+
...whereParams(flags["--where"]),
|
|
344
|
+
or: flags["--or"],
|
|
345
|
+
searchString: flags["--search"]
|
|
346
|
+
}
|
|
347
|
+
}));
|
|
348
|
+
const body = await requestJson(await projectTarget(flags, { command: "data count" }), tablePath(table, "count"), `Failed to count ${table}`, { query });
|
|
349
|
+
const count = isRecord(body) && typeof body.count === "number" ? body.count : void 0;
|
|
350
|
+
emit(() => console.log(count === void 0 ? cellText(body) : String(count)), {
|
|
351
|
+
table,
|
|
352
|
+
count
|
|
353
|
+
});
|
|
354
|
+
}
|
|
355
|
+
var AGGREGATE_FLAGS = {
|
|
356
|
+
...PROJECT_TARGET_FLAGS,
|
|
357
|
+
"--select": String,
|
|
358
|
+
"--group-by": String,
|
|
359
|
+
"--where": [String],
|
|
360
|
+
"-w": "--where",
|
|
361
|
+
"--or": String,
|
|
362
|
+
"--format": String
|
|
363
|
+
};
|
|
364
|
+
async function aggregateRows(rawArgs) {
|
|
365
|
+
const { flags, positionals } = parsedLine(() => parseCommandArgs({
|
|
366
|
+
spec: AGGREGATE_FLAGS,
|
|
367
|
+
rawArgs,
|
|
368
|
+
commandWords: 2,
|
|
369
|
+
command: "data aggregate",
|
|
370
|
+
maxPositionals: 1
|
|
371
|
+
}));
|
|
372
|
+
const { table, query, format } = parsedLine(() => {
|
|
373
|
+
const t = requireTable(positionals, "data aggregate");
|
|
374
|
+
if (!flags["--select"]) throw new UsageError("rebase data aggregate needs --select, e.g. --select \"count(),sum(total)\" (the API's `select`).");
|
|
375
|
+
return {
|
|
376
|
+
table: t,
|
|
377
|
+
query: {
|
|
378
|
+
...whereParams(flags["--where"]),
|
|
379
|
+
or: flags["--or"],
|
|
380
|
+
select: flags["--select"],
|
|
381
|
+
groupBy: flags["--group-by"]
|
|
382
|
+
},
|
|
383
|
+
format: resolveFormat(flags["--format"])
|
|
384
|
+
};
|
|
385
|
+
});
|
|
386
|
+
const body = await requestJson(await projectTarget(flags, { command: "data aggregate" }), tablePath(table, "aggregate"), `Failed to aggregate ${table}`, { query });
|
|
387
|
+
const rows = recordsOf(isRecord(body) ? body.data : body);
|
|
388
|
+
if (rows.length > 0) printRows(rows, format);
|
|
389
|
+
else emit(() => console.log(cellText(body)), body);
|
|
390
|
+
}
|
|
391
|
+
var INSERT_FLAGS = {
|
|
392
|
+
...PROJECT_TARGET_FLAGS,
|
|
393
|
+
"--data": String,
|
|
394
|
+
"-d": "--data",
|
|
395
|
+
"--file": String,
|
|
396
|
+
"--upsert": String
|
|
397
|
+
};
|
|
398
|
+
async function insertRows(rawArgs) {
|
|
399
|
+
const { flags, positionals } = parsedLine(() => parseCommandArgs({
|
|
400
|
+
spec: INSERT_FLAGS,
|
|
401
|
+
rawArgs,
|
|
402
|
+
commandWords: 2,
|
|
403
|
+
command: "data insert",
|
|
404
|
+
maxPositionals: 1
|
|
405
|
+
}));
|
|
406
|
+
const { table, value } = parsedLine(() => ({
|
|
407
|
+
table: requireTable(positionals, "data insert"),
|
|
408
|
+
value: readJsonInput(flags["--data"], flags["--file"], "row")
|
|
409
|
+
}));
|
|
410
|
+
const target = await projectTarget(flags, { command: "data insert" });
|
|
411
|
+
const action = `Failed to insert into ${table}`;
|
|
412
|
+
if (Array.isArray(value)) {
|
|
413
|
+
const body = await requestJson(target, tablePath(table, "bulk"), action, {
|
|
414
|
+
method: "POST",
|
|
415
|
+
json: flags["--upsert"] ? {
|
|
416
|
+
rows: value,
|
|
417
|
+
upsert: true,
|
|
418
|
+
onConflict: flags["--upsert"]
|
|
419
|
+
} : { rows: value }
|
|
420
|
+
});
|
|
421
|
+
emit(() => success(`Wrote ${recordsOf(isRecord(body) ? body.data : void 0).length || value.length} row(s) to ${table}.`), body);
|
|
422
|
+
return;
|
|
423
|
+
}
|
|
424
|
+
if (!isRecord(value)) fail("A row is a JSON object (or an array of them, for several).", void 0, "usage");
|
|
425
|
+
const row = await requestJson(target, tablePath(table), action, {
|
|
426
|
+
method: "POST",
|
|
427
|
+
json: value,
|
|
428
|
+
query: flags["--upsert"] ? { on_conflict: flags["--upsert"] } : void 0
|
|
429
|
+
});
|
|
430
|
+
emit(() => {
|
|
431
|
+
success(`Inserted into ${table}${isRecord(row) && stringOf(row.id) ? ` (id ${stringOf(row.id)})` : ""}.`);
|
|
432
|
+
if (isRecord(row)) keyValues(Object.entries(row).map(([key, v]) => [key, cellText(v)]));
|
|
433
|
+
}, row);
|
|
434
|
+
}
|
|
435
|
+
var UPDATE_FLAGS = {
|
|
436
|
+
...PROJECT_TARGET_FLAGS,
|
|
437
|
+
"--data": String,
|
|
438
|
+
"-d": "--data",
|
|
439
|
+
"--file": String,
|
|
440
|
+
"--where": [String],
|
|
441
|
+
"-w": "--where",
|
|
442
|
+
"--if-match": String
|
|
443
|
+
};
|
|
444
|
+
async function updateRows(rawArgs) {
|
|
445
|
+
const { flags, positionals } = parsedLine(() => parseCommandArgs({
|
|
446
|
+
spec: UPDATE_FLAGS,
|
|
447
|
+
rawArgs,
|
|
448
|
+
commandWords: 2,
|
|
449
|
+
command: "data update",
|
|
450
|
+
maxPositionals: 2
|
|
451
|
+
}));
|
|
452
|
+
const { table, id, value, where } = parsedLine(() => {
|
|
453
|
+
const t = requireTable(positionals, "data update");
|
|
454
|
+
const id = positionals[1];
|
|
455
|
+
const w = flags["--where"];
|
|
456
|
+
if (id && w) throw new UsageError("Name one row by its id, or several with --where; not both.");
|
|
457
|
+
if (!id && !w) throw new UsageError("rebase data update needs a row id, or --where for several: rebase data update <table> <id> --data '{…}'.");
|
|
458
|
+
const v = readJsonInput(flags["--data"], flags["--file"], "change");
|
|
459
|
+
if (!isRecord(v)) throw new UsageError("The change is a JSON object of the columns to set.");
|
|
460
|
+
return {
|
|
461
|
+
table: t,
|
|
462
|
+
id,
|
|
463
|
+
value: v,
|
|
464
|
+
where: w
|
|
465
|
+
};
|
|
466
|
+
});
|
|
467
|
+
const target = await projectTarget(flags, { command: "data update" });
|
|
468
|
+
const action = `Failed to update ${table}`;
|
|
469
|
+
if (id) {
|
|
470
|
+
const row = await requestJson(target, tablePath(table, id), action, {
|
|
471
|
+
method: "PATCH",
|
|
472
|
+
json: value,
|
|
473
|
+
headers: flags["--if-match"] ? { "If-Match": flags["--if-match"] } : void 0
|
|
474
|
+
});
|
|
475
|
+
emit(() => {
|
|
476
|
+
success(`Updated ${table}/${id}.`);
|
|
477
|
+
if (isRecord(row)) keyValues(Object.entries(row).map(([key, v]) => [key, cellText(v)]));
|
|
478
|
+
}, row);
|
|
479
|
+
return;
|
|
480
|
+
}
|
|
481
|
+
const filter = parsedLine(() => whereParams(where));
|
|
482
|
+
const counted = await requestJson(target, tablePath(table, "count"), action, { query: filter });
|
|
483
|
+
const count = isRecord(counted) && typeof counted.count === "number" ? counted.count : void 0;
|
|
484
|
+
await confirmDestructive({
|
|
485
|
+
yes: flags["--yes"] === true,
|
|
486
|
+
prompt: `Update ${count ?? "the matching"} row(s) of ${table} on ${target.label}?`
|
|
487
|
+
});
|
|
488
|
+
emit(() => success(`Updated ${count ?? "the matching"} row(s) of ${table}.`), await requestJson(target, tablePath(table, "bulk"), action, {
|
|
489
|
+
method: "PATCH",
|
|
490
|
+
json: {
|
|
491
|
+
where: whereObject(filter),
|
|
492
|
+
data: value
|
|
493
|
+
}
|
|
494
|
+
}));
|
|
495
|
+
}
|
|
496
|
+
/**
|
|
497
|
+
* The API's JSON `where` from `--where` conditions — the bulk routes take a
|
|
498
|
+
* body, not a query string: `{ "status": ["==", "draft"] }` style tuples, which
|
|
499
|
+
* the shared filter codec decodes from the same `op.value` spelling.
|
|
500
|
+
*/
|
|
501
|
+
function whereObject(query) {
|
|
502
|
+
const where = {};
|
|
503
|
+
for (const [column, values] of Object.entries(query)) where[column] = values.length === 1 ? values[0] : values;
|
|
504
|
+
return where;
|
|
505
|
+
}
|
|
506
|
+
var DELETE_FLAGS = {
|
|
507
|
+
...PROJECT_TARGET_FLAGS,
|
|
508
|
+
"--where": [String],
|
|
509
|
+
"-w": "--where",
|
|
510
|
+
"--hard": Boolean
|
|
511
|
+
};
|
|
512
|
+
async function deleteRows(rawArgs) {
|
|
513
|
+
const { flags, positionals } = parsedLine(() => parseCommandArgs({
|
|
514
|
+
spec: DELETE_FLAGS,
|
|
515
|
+
rawArgs,
|
|
516
|
+
commandWords: 2,
|
|
517
|
+
command: "data delete",
|
|
518
|
+
maxPositionals: 2
|
|
519
|
+
}));
|
|
520
|
+
const { table, id, where } = parsedLine(() => {
|
|
521
|
+
const t = requireTable(positionals, "data delete");
|
|
522
|
+
const i = positionals[1];
|
|
523
|
+
const w = flags["--where"];
|
|
524
|
+
if (i && w) throw new UsageError("Name one row by its id, or several with --where; not both.");
|
|
525
|
+
if (!i && !w) throw new UsageError("rebase data delete needs a row id, or --where for several: rebase data delete <table> <id>.");
|
|
526
|
+
return {
|
|
527
|
+
table: t,
|
|
528
|
+
id: i,
|
|
529
|
+
where: w
|
|
530
|
+
};
|
|
531
|
+
});
|
|
532
|
+
const target = await projectTarget(flags, { command: "data delete" });
|
|
533
|
+
const action = `Failed to delete from ${table}`;
|
|
534
|
+
const hard = flags["--hard"] === true;
|
|
535
|
+
if (id) {
|
|
536
|
+
await confirmDestructive({
|
|
537
|
+
yes: flags["--yes"] === true,
|
|
538
|
+
prompt: `Delete ${table}/${id}${hard ? " for good" : ""} on ${target.label}?`
|
|
539
|
+
});
|
|
540
|
+
await requestJson(target, tablePath(table, id), action, {
|
|
541
|
+
method: "DELETE",
|
|
542
|
+
query: hard ? { hard: "true" } : void 0
|
|
543
|
+
});
|
|
544
|
+
emit(() => success(`Deleted ${table}/${id}.`), {
|
|
545
|
+
table,
|
|
546
|
+
id,
|
|
547
|
+
deleted: true
|
|
548
|
+
});
|
|
549
|
+
return;
|
|
550
|
+
}
|
|
551
|
+
const filter = parsedLine(() => whereParams(where));
|
|
552
|
+
const counted = await requestJson(target, tablePath(table, "count"), action, { query: filter });
|
|
553
|
+
const count = isRecord(counted) && typeof counted.count === "number" ? counted.count : void 0;
|
|
554
|
+
if (count === 0) {
|
|
555
|
+
emit(() => note("No rows match; nothing was deleted."), {
|
|
556
|
+
table,
|
|
557
|
+
deleted: 0
|
|
558
|
+
});
|
|
559
|
+
return;
|
|
560
|
+
}
|
|
561
|
+
await confirmDestructive({
|
|
562
|
+
yes: flags["--yes"] === true,
|
|
563
|
+
prompt: `Delete ${count ?? "the matching"} row(s) of ${table}${hard ? " for good" : ""} on ${target.label}?`
|
|
564
|
+
});
|
|
565
|
+
emit(() => success(`Deleted ${count ?? "the matching"} row(s) of ${table}.`), await requestJson(target, tablePath(table, "bulk", "delete"), action, {
|
|
566
|
+
method: "POST",
|
|
567
|
+
json: { where: whereObject(filter) },
|
|
568
|
+
query: hard ? { hard: "true" } : void 0
|
|
569
|
+
}));
|
|
570
|
+
}
|
|
571
|
+
var IMPORT_FLAGS = {
|
|
572
|
+
...PROJECT_TARGET_FLAGS,
|
|
573
|
+
"--file": String,
|
|
574
|
+
"--format": String,
|
|
575
|
+
"--upsert": String,
|
|
576
|
+
"--ignore-duplicates": Boolean,
|
|
577
|
+
"--batch": Number
|
|
578
|
+
};
|
|
579
|
+
/** Parse one CSV document into rows of strings. Quotes, doubled quotes and newlines in quotes. Exported for tests. */
|
|
580
|
+
function parseCsv(text) {
|
|
581
|
+
const records = [];
|
|
582
|
+
let field = "";
|
|
583
|
+
let record = [];
|
|
584
|
+
let quoted = false;
|
|
585
|
+
for (let i = 0; i < text.length; i++) {
|
|
586
|
+
const ch = text[i];
|
|
587
|
+
if (quoted) {
|
|
588
|
+
if (ch === "\"" && text[i + 1] === "\"") {
|
|
589
|
+
field += "\"";
|
|
590
|
+
i++;
|
|
591
|
+
} else if (ch === "\"") quoted = false;
|
|
592
|
+
else field += ch;
|
|
593
|
+
continue;
|
|
594
|
+
}
|
|
595
|
+
if (ch === "\"") quoted = true;
|
|
596
|
+
else if (ch === ",") {
|
|
597
|
+
record.push(field);
|
|
598
|
+
field = "";
|
|
599
|
+
} else if (ch === "\n" || ch === "\r") {
|
|
600
|
+
if (ch === "\r" && text[i + 1] === "\n") i++;
|
|
601
|
+
record.push(field);
|
|
602
|
+
records.push(record);
|
|
603
|
+
record = [];
|
|
604
|
+
field = "";
|
|
605
|
+
} else field += ch;
|
|
606
|
+
}
|
|
607
|
+
if (field !== "" || record.length > 0) {
|
|
608
|
+
record.push(field);
|
|
609
|
+
records.push(record);
|
|
610
|
+
}
|
|
611
|
+
const [header, ...rows] = records.filter((r) => !(r.length === 1 && r[0] === ""));
|
|
612
|
+
if (!header) return [];
|
|
613
|
+
return rows.map((r) => Object.fromEntries(header.map((column, i) => [column, r[i] ?? ""])));
|
|
614
|
+
}
|
|
615
|
+
/** Rows out of a file, by its `--format` or its extension. Exported for tests. */
|
|
616
|
+
function readImportRows(text, format) {
|
|
617
|
+
if (format === "csv") return parseCsv(text);
|
|
618
|
+
if (format === "ndjson") return text.split(/\r?\n/).filter((line) => line.trim()).map((line, i) => {
|
|
619
|
+
try {
|
|
620
|
+
const row = JSON.parse(line);
|
|
621
|
+
if (!isRecord(row)) throw new Error("not an object");
|
|
622
|
+
return row;
|
|
623
|
+
} catch (e) {
|
|
624
|
+
throw new UsageError(`Line ${i + 1} is not a JSON object: ${e instanceof Error ? e.message : String(e)}`);
|
|
625
|
+
}
|
|
626
|
+
});
|
|
627
|
+
let parsed;
|
|
628
|
+
try {
|
|
629
|
+
parsed = JSON.parse(text);
|
|
630
|
+
} catch (e) {
|
|
631
|
+
throw new UsageError(`The file is not JSON: ${e instanceof Error ? e.message : String(e)} (CSV and NDJSON take --format).`);
|
|
632
|
+
}
|
|
633
|
+
const rows = Array.isArray(parsed) ? parsed : isRecord(parsed) && Array.isArray(parsed.data) ? parsed.data : void 0;
|
|
634
|
+
if (!rows || !rows.every(isRecord)) throw new UsageError("A JSON import is an array of row objects (or `{ \"data\": [...] }`, what `data query --format json` writes).");
|
|
635
|
+
return rows;
|
|
636
|
+
}
|
|
637
|
+
async function importRows(rawArgs) {
|
|
638
|
+
const { flags, positionals } = parsedLine(() => parseCommandArgs({
|
|
639
|
+
spec: IMPORT_FLAGS,
|
|
640
|
+
rawArgs,
|
|
641
|
+
commandWords: 2,
|
|
642
|
+
command: "data import",
|
|
643
|
+
maxPositionals: 1
|
|
644
|
+
}));
|
|
645
|
+
const { table, rows, batch } = parsedLine(() => {
|
|
646
|
+
const t = requireTable(positionals, "data import");
|
|
647
|
+
const file = flags["--file"];
|
|
648
|
+
if (!file) throw new UsageError("rebase data import needs --file <path> (- for stdin): JSON, NDJSON or CSV.");
|
|
649
|
+
let text;
|
|
650
|
+
try {
|
|
651
|
+
text = fs.readFileSync(file === "-" ? 0 : file, "utf8");
|
|
652
|
+
} catch (e) {
|
|
653
|
+
throw new UsageError(`Cannot read ${file}: ${e instanceof Error ? e.message : String(e)}`);
|
|
654
|
+
}
|
|
655
|
+
const format = flags["--format"] ?? (file.endsWith(".csv") ? "csv" : file.endsWith(".ndjson") || file.endsWith(".jsonl") ? "ndjson" : "json");
|
|
656
|
+
if (![
|
|
657
|
+
"json",
|
|
658
|
+
"ndjson",
|
|
659
|
+
"csv"
|
|
660
|
+
].includes(format)) throw new UsageError(`--format takes json, ndjson or csv (got "${format}").`);
|
|
661
|
+
const size = flags["--batch"] ?? IMPORT_BATCH;
|
|
662
|
+
if (!Number.isInteger(size) || size <= 0) throw new UsageError("--batch takes a positive number of rows.");
|
|
663
|
+
if (flags["--ignore-duplicates"] && !flags["--upsert"]) throw new UsageError("--ignore-duplicates goes with --upsert <column>, the conflict to ignore.");
|
|
664
|
+
return {
|
|
665
|
+
table: t,
|
|
666
|
+
rows: readImportRows(text, format),
|
|
667
|
+
batch: size
|
|
668
|
+
};
|
|
669
|
+
});
|
|
670
|
+
if (rows.length === 0) {
|
|
671
|
+
emit(() => note("The file holds no rows; nothing was written."), {
|
|
672
|
+
table,
|
|
673
|
+
written: 0
|
|
674
|
+
});
|
|
675
|
+
return;
|
|
676
|
+
}
|
|
677
|
+
const target = await projectTarget(flags, { command: "data import" });
|
|
678
|
+
let written = 0;
|
|
679
|
+
for (let start = 0; start < rows.length; start += batch) {
|
|
680
|
+
const slice = rows.slice(start, start + batch);
|
|
681
|
+
try {
|
|
682
|
+
await readJson(await target.request(tablePath(table, "bulk"), {
|
|
683
|
+
method: "POST",
|
|
684
|
+
timeoutMs: 12e4,
|
|
685
|
+
json: {
|
|
686
|
+
rows: slice,
|
|
687
|
+
...flags["--upsert"] ? {
|
|
688
|
+
upsert: true,
|
|
689
|
+
onConflict: flags["--upsert"]
|
|
690
|
+
} : {},
|
|
691
|
+
...flags["--ignore-duplicates"] ? { ignoreDuplicates: true } : {}
|
|
692
|
+
}
|
|
693
|
+
}), target, `Rows ${start + 1}–${start + slice.length} of ${table} were refused (${written} written before them)`);
|
|
694
|
+
} catch (e) {
|
|
695
|
+
reportTargetError(e, target);
|
|
696
|
+
}
|
|
697
|
+
written += slice.length;
|
|
698
|
+
if (!isJsonMode() && rows.length > batch) note(chalk.gray(`${written}/${rows.length}`));
|
|
699
|
+
}
|
|
700
|
+
emit(() => success(`Imported ${written} row(s) into ${table} on ${target.label}.`), {
|
|
701
|
+
table,
|
|
702
|
+
written
|
|
703
|
+
});
|
|
704
|
+
}
|
|
705
|
+
var HISTORY_FLAGS = {
|
|
706
|
+
...PROJECT_TARGET_FLAGS,
|
|
707
|
+
"--limit": Number,
|
|
708
|
+
"-n": "--limit",
|
|
709
|
+
"--offset": Number
|
|
710
|
+
};
|
|
711
|
+
async function rowHistory(rawArgs) {
|
|
712
|
+
const { flags, positionals } = parsedLine(() => parseCommandArgs({
|
|
713
|
+
spec: HISTORY_FLAGS,
|
|
714
|
+
rawArgs,
|
|
715
|
+
commandWords: 2,
|
|
716
|
+
command: "data history",
|
|
717
|
+
maxPositionals: 2
|
|
718
|
+
}));
|
|
719
|
+
const { table, id } = parsedLine(() => {
|
|
720
|
+
const t = requireTable(positionals, "data history");
|
|
721
|
+
if (!positionals[1]) throw new UsageError("rebase data history needs a row id: rebase data history <table> <id>.");
|
|
722
|
+
return {
|
|
723
|
+
table: t,
|
|
724
|
+
id: positionals[1]
|
|
725
|
+
};
|
|
726
|
+
});
|
|
727
|
+
const body = await requestJson(await projectTarget(flags, { command: "data history" }), tablePath(table, id, "history"), `Failed to read the history of ${table}/${id}`, { query: {
|
|
728
|
+
limit: flags["--limit"]?.toString(),
|
|
729
|
+
offset: flags["--offset"]?.toString()
|
|
730
|
+
} });
|
|
731
|
+
const entries = recordsOf(isRecord(body) ? body.data : body);
|
|
732
|
+
emit(() => {
|
|
733
|
+
if (entries.length === 0) return note("No history is recorded for this row (is history on for the table?).");
|
|
734
|
+
for (const entry of entries) console.log(` ${chalk.bold(stringOf(entry.id) ?? "?")} ${chalk.gray(stringOf(entry.created_at ?? entry.createdAt) ?? "")} ${stringOf(entry.action ?? entry.operation) ?? ""}`);
|
|
735
|
+
note(chalk.gray(`Put one back with: rebase data revert ${table} ${id} <historyId>`));
|
|
736
|
+
}, body);
|
|
737
|
+
}
|
|
738
|
+
var REVERT_FLAGS = { ...PROJECT_TARGET_FLAGS };
|
|
739
|
+
async function revertRow(rawArgs) {
|
|
740
|
+
const { flags, positionals } = parsedLine(() => parseCommandArgs({
|
|
741
|
+
spec: REVERT_FLAGS,
|
|
742
|
+
rawArgs,
|
|
743
|
+
commandWords: 2,
|
|
744
|
+
command: "data revert",
|
|
745
|
+
maxPositionals: 3
|
|
746
|
+
}));
|
|
747
|
+
const { table, id, historyId } = parsedLine(() => {
|
|
748
|
+
const t = requireTable(positionals, "data revert");
|
|
749
|
+
if (!positionals[1] || !positionals[2]) throw new UsageError("rebase data revert needs a row id and a history id: rebase data revert <table> <id> <historyId> (`rebase data history` lists them).");
|
|
750
|
+
return {
|
|
751
|
+
table: t,
|
|
752
|
+
id: positionals[1],
|
|
753
|
+
historyId: positionals[2]
|
|
754
|
+
};
|
|
755
|
+
});
|
|
756
|
+
const target = await projectTarget(flags, { command: "data revert" });
|
|
757
|
+
await confirmDestructive({
|
|
758
|
+
yes: flags["--yes"] === true,
|
|
759
|
+
prompt: `Put ${table}/${id} back to version ${historyId} on ${target.label}?`
|
|
760
|
+
});
|
|
761
|
+
emit(() => success(`Reverted ${table}/${id} to ${historyId}; the revert is a new history entry.`), await requestJson(target, tablePath(table, id, "history", historyId, "revert"), `Failed to revert ${table}/${id}`, { method: "POST" }));
|
|
762
|
+
}
|
|
763
|
+
var WATCH_FLAGS = {
|
|
764
|
+
...PROJECT_TARGET_FLAGS,
|
|
765
|
+
"--where": [String],
|
|
766
|
+
"-w": "--where",
|
|
767
|
+
"--limit": Number,
|
|
768
|
+
"-n": "--limit"
|
|
769
|
+
};
|
|
770
|
+
/**
|
|
771
|
+
* Print a table's matching rows each time they change, over the app's realtime
|
|
772
|
+
* socket — the same subscription the SDK's `listen` opens, under the same RLS.
|
|
773
|
+
* One JSON line per change when piped. Runs until interrupted.
|
|
774
|
+
*
|
|
775
|
+
* Not through the Studio proxy, which carries HTTP only: on a cloud project it
|
|
776
|
+
* needs --token or --session, which go to the app's own address.
|
|
777
|
+
*/
|
|
778
|
+
async function watchRows(rawArgs) {
|
|
779
|
+
const { flags, positionals } = parsedLine(() => parseCommandArgs({
|
|
780
|
+
spec: WATCH_FLAGS,
|
|
781
|
+
rawArgs,
|
|
782
|
+
commandWords: 2,
|
|
783
|
+
command: "data watch",
|
|
784
|
+
maxPositionals: 1
|
|
785
|
+
}));
|
|
786
|
+
const { table, filter } = parsedLine(() => ({
|
|
787
|
+
table: requireTable(positionals, "data watch"),
|
|
788
|
+
filter: whereParams(flags["--where"])
|
|
789
|
+
}));
|
|
790
|
+
const target = await projectTarget(flags, { command: "data watch" });
|
|
791
|
+
if (target.credential === "studio-proxy") fail("The console's Studio proxy carries HTTP only, and `data watch` needs the app's realtime socket.", "Pass --token <bearer> (an rk_ key with data:read) or --session to reach the app's own address.", "realtime_unavailable");
|
|
792
|
+
await watchOverSocket(target, table, filter, flags["--limit"]);
|
|
793
|
+
}
|
|
794
|
+
async function watchOverSocket(target, table, filter, limit) {
|
|
795
|
+
const { createRebaseClient } = await import("@rebasepro/client");
|
|
796
|
+
const { cliUserAgent } = await import("./version-ONIeo7jl.js").then((n) => n.r);
|
|
797
|
+
const token = await target.bearer();
|
|
798
|
+
const client = createRebaseClient({
|
|
799
|
+
baseUrl: target.baseUrl,
|
|
800
|
+
...token ? { token } : {},
|
|
801
|
+
headers: { "User-Agent": cliUserAgent() },
|
|
802
|
+
auth: {
|
|
803
|
+
persistSession: false,
|
|
804
|
+
autoRefresh: false
|
|
805
|
+
}
|
|
806
|
+
});
|
|
807
|
+
const { deserializeFilter } = await import("@rebasepro/common");
|
|
808
|
+
const where = deserializeFilter(whereObject(filter));
|
|
809
|
+
if (!isJsonMode()) note(`Watching ${table} on ${target.label}. Ctrl-C to stop.`);
|
|
810
|
+
const handle = client.data.table(table).listen({
|
|
811
|
+
where,
|
|
812
|
+
...limit ? { limit } : {}
|
|
813
|
+
}, (event) => {
|
|
814
|
+
const rows = isRecord(event) && Array.isArray(event.data) ? recordsOf(event.data) : recordsOf(event);
|
|
815
|
+
if (isJsonMode()) process.stdout.write(`${JSON.stringify({
|
|
816
|
+
at: (/* @__PURE__ */ new Date()).toISOString(),
|
|
817
|
+
data: rows
|
|
818
|
+
})}\n`);
|
|
819
|
+
else {
|
|
820
|
+
console.log(chalk.gray(`── ${(/* @__PURE__ */ new Date()).toLocaleTimeString()} · ${rows.length} row(s)`));
|
|
821
|
+
printTable(rows);
|
|
822
|
+
}
|
|
823
|
+
}, (error) => fail(`The subscription to ${table} failed: ${error instanceof Error ? error.message : String(error)}`, void 0, "realtime_error"));
|
|
824
|
+
await new Promise((resolve) => {
|
|
825
|
+
const stop = () => {
|
|
826
|
+
if (typeof handle === "function") handle();
|
|
827
|
+
resolve();
|
|
828
|
+
};
|
|
829
|
+
process.once("SIGINT", stop);
|
|
830
|
+
process.once("SIGTERM", stop);
|
|
831
|
+
});
|
|
832
|
+
process.exit(0);
|
|
833
|
+
}
|
|
834
|
+
var DATA_ACTIONS = [
|
|
835
|
+
{
|
|
836
|
+
action: "query",
|
|
837
|
+
args: "<table>",
|
|
838
|
+
description: "Read rows: filtered, sorted, paged",
|
|
839
|
+
flags: [
|
|
840
|
+
["--where, -w <col=op.value>", "A condition in the API's own syntax: status=eq.published, price=gte.10 (repeatable)"],
|
|
841
|
+
["--or <(a.eq.1,b.gt.2)>", "Conditions any of which may match"],
|
|
842
|
+
["--order-by <col[:desc]>", "Sort (repeatable, in order)"],
|
|
843
|
+
["--limit, -n <n>", "Rows per page (default: the server's)"],
|
|
844
|
+
["--offset <n>", "Skip this many rows"],
|
|
845
|
+
["--fields <a,b>", "Only these columns"],
|
|
846
|
+
["--include <relation>", "Embed a relation"],
|
|
847
|
+
["--search <text>", "Full-text search, on tables that declare it"],
|
|
848
|
+
["--deleted <include|only>", "Soft-deleted rows too, or only them"],
|
|
849
|
+
["--all", "Every page, not just the first"],
|
|
850
|
+
["--format <table|json|ndjson|csv>", "How to print the rows (csv and ndjson stream with --all)"]
|
|
851
|
+
]
|
|
852
|
+
},
|
|
853
|
+
{
|
|
854
|
+
action: "get",
|
|
855
|
+
args: "<table> <id>",
|
|
856
|
+
description: "Read one row",
|
|
857
|
+
flags: [["--fields <a,b>", "Only these columns"], ["--include <relation>", "Embed a relation"]]
|
|
858
|
+
},
|
|
859
|
+
{
|
|
860
|
+
action: "count",
|
|
861
|
+
args: "<table>",
|
|
862
|
+
description: "Count the rows that match",
|
|
863
|
+
flags: [["--where, -w <col=op.value>", "As for query"], ["--search <text>", "As for query"]]
|
|
864
|
+
},
|
|
865
|
+
{
|
|
866
|
+
action: "aggregate",
|
|
867
|
+
args: "<table>",
|
|
868
|
+
description: "count, sum, avg, min, max, grouped",
|
|
869
|
+
flags: [["--select <exprs>", "The API's select: \"count(),sum(total)\""], ["--group-by <cols>", "Group by these columns"]]
|
|
870
|
+
},
|
|
871
|
+
{
|
|
872
|
+
action: "insert",
|
|
873
|
+
args: "<table>",
|
|
874
|
+
description: "Add a row, or several from a JSON array",
|
|
875
|
+
flags: [
|
|
876
|
+
["--data, -d <json>", "The row as JSON"],
|
|
877
|
+
["--file <path|->", "The row (or an array of rows) from a file or stdin"],
|
|
878
|
+
["--upsert <column>", "Update the row that conflicts on this column instead"]
|
|
879
|
+
]
|
|
880
|
+
},
|
|
881
|
+
{
|
|
882
|
+
action: "update",
|
|
883
|
+
args: "<table> [<id>]",
|
|
884
|
+
description: "Change columns on a row, or on every row --where matches",
|
|
885
|
+
flags: [
|
|
886
|
+
["--data, -d <json>", "The columns to set"],
|
|
887
|
+
["--file <path|->", "The same, from a file"],
|
|
888
|
+
["--where, -w <col=op.value>", "Update every matching row (confirms first)"],
|
|
889
|
+
["--if-match <etag>", "Refuse if the row changed since this version"]
|
|
890
|
+
]
|
|
891
|
+
},
|
|
892
|
+
{
|
|
893
|
+
action: "delete",
|
|
894
|
+
args: "<table> [<id>]",
|
|
895
|
+
description: "Delete a row, or every row --where matches (confirms first)",
|
|
896
|
+
flags: [["--where, -w <col=op.value>", "Delete every matching row"], ["--hard", "Remove a soft-deleted table's rows for good"]]
|
|
897
|
+
},
|
|
898
|
+
{
|
|
899
|
+
action: "import",
|
|
900
|
+
args: "<table>",
|
|
901
|
+
description: "Write rows from a JSON, NDJSON or CSV file, in batches",
|
|
902
|
+
flags: [
|
|
903
|
+
["--file <path|->", "The rows (format from the extension, else --format)"],
|
|
904
|
+
["--format <json|ndjson|csv>", "The file's format"],
|
|
905
|
+
["--upsert <column>", "Update rows that conflict on this column"],
|
|
906
|
+
["--ignore-duplicates", "With --upsert: skip conflicting rows instead"],
|
|
907
|
+
["--batch <n>", `Rows per request (default ${IMPORT_BATCH})`]
|
|
908
|
+
]
|
|
909
|
+
},
|
|
910
|
+
{
|
|
911
|
+
action: "history",
|
|
912
|
+
args: "<table> <id>",
|
|
913
|
+
description: "A row's recorded versions (tables with history on)",
|
|
914
|
+
flags: [["--limit, -n <n>", "At most this many"], ["--offset <n>", "Skip this many"]]
|
|
915
|
+
},
|
|
916
|
+
{
|
|
917
|
+
action: "revert",
|
|
918
|
+
args: "<table> <id> <historyId>",
|
|
919
|
+
description: "Put a row back to a recorded version"
|
|
920
|
+
},
|
|
921
|
+
{
|
|
922
|
+
action: "watch",
|
|
923
|
+
args: "<table>",
|
|
924
|
+
description: "Print the matching rows each time they change (realtime)",
|
|
925
|
+
flags: [["--where, -w <col=op.value>", "As for query"], ["--limit, -n <n>", "At most this many rows"]]
|
|
926
|
+
}
|
|
927
|
+
];
|
|
928
|
+
function printDataHelp() {
|
|
929
|
+
printProjectHelp({
|
|
930
|
+
command: "data",
|
|
931
|
+
title: "Read and write a running app's rows, through its API and its row-level security",
|
|
932
|
+
actions: DATA_ACTIONS,
|
|
933
|
+
notes: [
|
|
934
|
+
"Examples:",
|
|
935
|
+
" rebase data query posts --where status=eq.published --order-by created_at:desc -n 10",
|
|
936
|
+
" rebase data insert posts --data '{\"title\":\"Hello\"}'",
|
|
937
|
+
" rebase data import posts --file seed.csv --upsert slug",
|
|
938
|
+
" rebase data query orders --all --format csv --project acme > orders.csv",
|
|
939
|
+
"The service key is admin: row-level security still runs, as the admin role. Pass --token or --session to act as somebody else.",
|
|
940
|
+
"`rebase schema show --remote` lists the tables and their columns."
|
|
941
|
+
]
|
|
942
|
+
});
|
|
943
|
+
}
|
|
944
|
+
//#endregion
|
|
945
|
+
export { DATA_SUBCOMMANDS, dataCommand };
|
|
946
|
+
|
|
947
|
+
//# sourceMappingURL=data-BJ9AZFUC.js.map
|