@motherbase/cli 0.2.5 → 0.2.6

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.
Files changed (63) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +247 -247
  3. package/bin/motherbase.js +10 -10
  4. package/package.json +35 -26
  5. package/src/api.js +233 -241
  6. package/src/commands/_util.js +106 -93
  7. package/src/commands/backups.js +16 -16
  8. package/src/commands/branches.js +113 -113
  9. package/src/commands/completion.js +90 -90
  10. package/src/commands/config.js +47 -47
  11. package/src/commands/cron.js +65 -65
  12. package/src/commands/db-catalog.js +326 -326
  13. package/src/commands/db.js +103 -103
  14. package/src/commands/domains.js +124 -124
  15. package/src/commands/functions.js +304 -297
  16. package/src/commands/gen.js +172 -172
  17. package/src/commands/import.js +55 -55
  18. package/src/commands/index.js +85 -85
  19. package/src/commands/inspect.js +178 -178
  20. package/src/commands/keys.js +72 -72
  21. package/src/commands/link.js +35 -35
  22. package/src/commands/local.js +294 -273
  23. package/src/commands/login.js +39 -39
  24. package/src/commands/logout.js +16 -16
  25. package/src/commands/mcp.js +61 -61
  26. package/src/commands/migrate.js +207 -179
  27. package/src/commands/migration.js +108 -108
  28. package/src/commands/network.js +83 -83
  29. package/src/commands/orgs.js +40 -40
  30. package/src/commands/postgres-config.js +113 -113
  31. package/src/commands/projects.js +130 -130
  32. package/src/commands/queues.js +133 -133
  33. package/src/commands/realtime.js +35 -35
  34. package/src/commands/rls.js +176 -176
  35. package/src/commands/secrets.js +66 -66
  36. package/src/commands/signing.js +130 -130
  37. package/src/commands/snippets.js +44 -44
  38. package/src/commands/status.js +42 -42
  39. package/src/commands/storage.js +261 -261
  40. package/src/commands/test.js +9 -9
  41. package/src/commands/unlink.js +15 -15
  42. package/src/commands/users.js +142 -142
  43. package/src/commands/vault.js +82 -82
  44. package/src/commands/webhooks.js +62 -62
  45. package/src/commands/whoami.js +20 -20
  46. package/src/commands/wrappers.js +150 -150
  47. package/src/config.js +98 -98
  48. package/src/context.js +106 -102
  49. package/src/docs.js +68 -0
  50. package/src/edge-templates.js +194 -194
  51. package/src/format.js +92 -92
  52. package/src/inspect/csv.js +22 -22
  53. package/src/inspect/queries.js +562 -562
  54. package/src/main.js +224 -194
  55. package/src/mcp/platform-tools.js +233 -233
  56. package/src/mcp/protocol.js +152 -149
  57. package/src/mcp/storage-tools.js +93 -93
  58. package/src/mcp/tools.js +478 -478
  59. package/src/migration/commands.js +375 -375
  60. package/src/migration/files.js +245 -245
  61. package/src/prompt.js +91 -91
  62. package/src/storage/remote.js +62 -62
  63. package/src/ui.js +111 -111
@@ -1,326 +1,326 @@
1
- 'use strict';
2
-
3
- // `motherbase db indexes|types|roles|publications`: the Database section of
4
- // Studio from the terminal. Supabase's CLI has no equivalent for these, so they
5
- // live under `db` rather than claiming top-level names Supabase might use.
6
-
7
- const api = require('../api');
8
- const { output, requireArg } = require('./_util');
9
- const { CliError } = require('../context');
10
-
11
- const schemaQuery = flags => (flags.schema ? { schema: flags.schema } : undefined);
12
- const csv = value => String(value).split(',').map(s => s.trim()).filter(Boolean);
13
-
14
- // `--login`, `--login true` and `--login false` all read naturally; absent
15
- // means "leave as is", which ALTER ROLE needs to change one attribute only.
16
- function bool(value) {
17
- if (value === undefined) return undefined;
18
- return value === true || value === 'true';
19
- }
20
-
21
- // Parse `schema.table` (or a bare `table` in public) into the API's shape.
22
- function tableRef(ref) {
23
- const [schema, table] = ref.includes('.') ? ref.split('.', 2) : ['public', ref];
24
- return { schema, table };
25
- }
26
-
27
- function roleAttributes(flags) {
28
- const attributes = {
29
- canLogin: bool(flags.login),
30
- isSuperuser: bool(flags.superuser),
31
- canCreateDb: bool(flags.createdb),
32
- canCreateRole: bool(flags.createrole),
33
- canReplicate: bool(flags.replication),
34
- canBypassRls: bool(flags.bypassrls),
35
- inheritRole: bool(flags.inherit),
36
- connectionLimit: flags['connection-limit'] === undefined ? undefined : Number(flags['connection-limit']),
37
- password: flags.password === undefined ? undefined : String(flags.password),
38
- validUntil: flags['valid-until'] === undefined ? undefined : String(flags['valid-until']),
39
- };
40
- return Object.fromEntries(Object.entries(attributes).filter(([, v]) => v !== undefined));
41
- }
42
-
43
- function publishFlags(flags, defaults) {
44
- const actions = flags.publish === undefined ? null : csv(flags.publish);
45
- if (!actions) return defaults;
46
- return Object.fromEntries(['insert', 'update', 'delete', 'truncate'].map(a => [a, actions.includes(a)]));
47
- }
48
-
49
- const indexes = {
50
- summary: 'Indexes across a schema: list, create, drop',
51
- usage: 'motherbase db indexes <list|create|drop> ...',
52
- subcommands: {
53
- list: {
54
- summary: 'List every index in a schema',
55
- usage: 'motherbase db indexes list [--schema public]',
56
- async run(ctx, args, flags) {
57
- const data = await api.adminRequest(ctx, 'GET', '/schema/indexes', { query: schemaQuery(flags) });
58
- output(ctx, data, (d, ui) =>
59
- ui.table((d.indexes || []).map(i => ({ ...i, columns: i.columns.join(', ') })), [
60
- { key: 'table', label: 'TABLE' },
61
- { key: 'name', label: 'INDEX' },
62
- { key: 'method', label: 'METHOD' },
63
- { key: 'unique', label: 'UNIQUE' },
64
- { key: 'columns', label: 'COLUMNS' },
65
- { key: 'sizeBytes', label: 'BYTES' },
66
- ]),
67
- );
68
- },
69
- },
70
- create: {
71
- summary: 'Create an index on one or more columns',
72
- usage: 'motherbase db indexes create <table> --columns a,b [--unique] [--method btree|hash|gist|gin|brin|spgist] [--name n] [--schema s]',
73
- async run(ctx, args, flags) {
74
- const table = requireArg(args[0], 'table');
75
- if (!flags.columns) throw new CliError('--columns is required');
76
- const body = { columns: csv(flags.columns), unique: bool(flags.unique) || false };
77
- if (flags.method) body.method = String(flags.method);
78
- if (flags.name) body.name = String(flags.name);
79
- const data = await api.adminRequest(ctx, 'POST', `/schema/tables/${encodeURIComponent(table)}/indexes`, { body, query: schemaQuery(flags) });
80
- output(ctx, data, (_d, ui) => ui.success(`Created index on ${table} (${body.columns.join(', ')})`));
81
- },
82
- },
83
- drop: {
84
- summary: 'Drop an index by name',
85
- usage: 'motherbase db indexes drop <name> [--schema s]',
86
- async run(ctx, args, flags) {
87
- const name = requireArg(args[0], 'name');
88
- const data = await api.adminRequest(ctx, 'DELETE', `/schema/indexes/${encodeURIComponent(name)}`, { query: schemaQuery(flags) });
89
- output(ctx, data, (_d, ui) => ui.success(`Dropped index ${name}`));
90
- },
91
- },
92
- },
93
- };
94
-
95
- const enumPath = name => `/schema/enums/${encodeURIComponent(name)}`;
96
-
97
- const types = {
98
- summary: 'Enumerated types: list, create, add-value, rename-value, drop',
99
- usage: 'motherbase db types <list|create|add-value|rename-value|drop> ...',
100
- subcommands: {
101
- list: {
102
- summary: 'List enum types and their values',
103
- usage: 'motherbase db types list [--schema public]',
104
- async run(ctx, args, flags) {
105
- const data = await api.adminRequest(ctx, 'GET', '/schema/enums', { query: schemaQuery(flags) });
106
- output(ctx, data, (d, ui) =>
107
- ui.table((d.enums || []).map(e => ({ name: e.name, values: e.values.join(', '), usedBy: e.usedBy.length })), [
108
- { key: 'name', label: 'TYPE' },
109
- { key: 'values', label: 'VALUES' },
110
- { key: 'usedBy', label: 'COLUMNS' },
111
- ]),
112
- );
113
- },
114
- },
115
- create: {
116
- summary: 'Create an enum type',
117
- usage: 'motherbase db types create <name> --values a,b,c [--schema s]',
118
- async run(ctx, args, flags) {
119
- const name = requireArg(args[0], 'name');
120
- if (!flags.values) throw new CliError('--values is required');
121
- const data = await api.adminRequest(ctx, 'POST', '/schema/enums', { body: { name, values: csv(flags.values) }, query: schemaQuery(flags) });
122
- output(ctx, data, (_d, ui) => ui.success(`Created type ${name}`));
123
- },
124
- },
125
- 'add-value': {
126
- summary: 'Add a value to an enum (values cannot be removed)',
127
- usage: 'motherbase db types add-value <name> <value> [--before v | --after v] [--schema s]',
128
- async run(ctx, args, flags) {
129
- const name = requireArg(args[0], 'name');
130
- const value = requireArg(args[1], 'value');
131
- const body = { action: 'add-value', value, before: flags.before, after: flags.after };
132
- const data = await api.adminRequest(ctx, 'PATCH', enumPath(name), { body, query: schemaQuery(flags) });
133
- output(ctx, data, (_d, ui) => ui.success(`Added "${value}" to ${name}`));
134
- },
135
- },
136
- 'rename-value': {
137
- summary: 'Rename one value of an enum',
138
- usage: 'motherbase db types rename-value <name> <from> <to> [--schema s]',
139
- async run(ctx, args, flags) {
140
- const name = requireArg(args[0], 'name');
141
- const body = { action: 'rename-value', from: requireArg(args[1], 'from'), to: requireArg(args[2], 'to') };
142
- const data = await api.adminRequest(ctx, 'PATCH', enumPath(name), { body, query: schemaQuery(flags) });
143
- output(ctx, data, (_d, ui) => ui.success(`Renamed "${body.from}" to "${body.to}" in ${name}`));
144
- },
145
- },
146
- drop: {
147
- summary: 'Drop an enum type (refused while a column uses it)',
148
- usage: 'motherbase db types drop <name> [--schema s]',
149
- async run(ctx, args, flags) {
150
- const name = requireArg(args[0], 'name');
151
- const data = await api.adminRequest(ctx, 'DELETE', enumPath(name), { query: schemaQuery(flags) });
152
- output(ctx, data, (_d, ui) => ui.success(`Dropped type ${name}`));
153
- },
154
- },
155
- },
156
- };
157
-
158
- const ROLE_FLAGS = '[--login] [--password p] [--createdb] [--createrole] [--replication] [--bypassrls] [--superuser] [--connection-limit n] [--valid-until iso]';
159
-
160
- const roles = {
161
- summary: 'Postgres roles: list, create, alter, drop',
162
- usage: 'motherbase db roles <list|create|alter|drop> ...',
163
- subcommands: {
164
- list: {
165
- summary: 'List roles with their attributes and live connections',
166
- usage: 'motherbase db roles list',
167
- async run(ctx) {
168
- const data = await api.adminRequest(ctx, 'GET', '/database/roles');
169
- output(ctx, data, (d, ui) =>
170
- ui.table(d.roles || [], [
171
- { key: 'name', label: 'ROLE' },
172
- { key: 'canLogin', label: 'LOGIN' },
173
- { key: 'isSuperuser', label: 'SUPERUSER' },
174
- { key: 'canBypassRls', label: 'BYPASSRLS' },
175
- { key: 'connectionLimit', label: 'LIMIT' },
176
- { key: 'activeConnections', label: 'CONNECTIONS' },
177
- { key: 'reserved', label: 'RESERVED' },
178
- ]),
179
- );
180
- },
181
- },
182
- create: {
183
- summary: 'Create a role',
184
- usage: `motherbase db roles create <name> ${ROLE_FLAGS}`,
185
- async run(ctx, args, flags) {
186
- const name = requireArg(args[0], 'name');
187
- const data = await api.adminRequest(ctx, 'POST', '/database/roles', { body: { name, ...roleAttributes(flags) } });
188
- output(ctx, data, (_d, ui) => ui.success(`Created role ${name}`));
189
- },
190
- },
191
- alter: {
192
- summary: 'Change attributes of a role, or rename it with --rename',
193
- usage: `motherbase db roles alter <name> [--rename new] ${ROLE_FLAGS}`,
194
- async run(ctx, args, flags) {
195
- const name = requireArg(args[0], 'name');
196
- const body = { ...roleAttributes(flags), ...(flags.rename ? { name: String(flags.rename) } : {}) };
197
- if (!Object.keys(body).length) throw new CliError('Nothing to change: pass at least one attribute flag.');
198
- const data = await api.adminRequest(ctx, 'PATCH', `/database/roles/${encodeURIComponent(name)}`, { body });
199
- output(ctx, data, (_d, ui) => ui.success(`Updated role ${name}`));
200
- },
201
- },
202
- drop: {
203
- summary: 'Drop a role (refused for reserved roles and roles that own objects)',
204
- usage: 'motherbase db roles drop <name>',
205
- async run(ctx, args) {
206
- const name = requireArg(args[0], 'name');
207
- const data = await api.adminRequest(ctx, 'DELETE', `/database/roles/${encodeURIComponent(name)}`);
208
- output(ctx, data, (_d, ui) => ui.success(`Dropped role ${name}`));
209
- },
210
- },
211
- },
212
- };
213
-
214
- const publications = {
215
- summary: 'Logical-replication publications: list, create, alter, drop',
216
- usage: 'motherbase db publications <list|create|alter|drop> ...',
217
- subcommands: {
218
- list: {
219
- summary: 'List publications, their tables and published actions',
220
- usage: 'motherbase db publications list',
221
- async run(ctx) {
222
- const data = await api.adminRequest(ctx, 'GET', '/database/publications');
223
- output(ctx, data, (d, ui) => {
224
- ui.table((d.publications || []).map(p => ({
225
- name: p.name,
226
- publish: ['insert', 'update', 'delete', 'truncate'].filter(a => p[a]).join(', '),
227
- tables: p.allTables ? '(all tables)' : p.tables.map(t => `${t.schema}.${t.table}`).join(', '),
228
- })), [
229
- { key: 'name', label: 'PUBLICATION' },
230
- { key: 'publish', label: 'PUBLISH' },
231
- { key: 'tables', label: 'TABLES' },
232
- ]);
233
- if (d.walLevel !== 'logical') ui.warn(`wal_level is "${d.walLevel}": publications stream nothing until it is "logical".`);
234
- });
235
- },
236
- },
237
- create: {
238
- summary: 'Create a publication',
239
- usage: 'motherbase db publications create <name> [--tables a,schema.b | --all-tables] [--publish insert,update,delete,truncate]',
240
- async run(ctx, args, flags) {
241
- const name = requireArg(args[0], 'name');
242
- const body = {
243
- name,
244
- ...publishFlags(flags, { insert: true, update: true, delete: true, truncate: true }),
245
- ...(flags['all-tables'] ? { allTables: true } : {}),
246
- ...(flags.tables ? { tables: csv(flags.tables).map(tableRef) } : {}),
247
- };
248
- const data = await api.adminRequest(ctx, 'POST', '/database/publications', { body });
249
- output(ctx, data, (_d, ui) => ui.success(`Created publication ${name}`));
250
- },
251
- },
252
- alter: {
253
- summary: 'Add or drop tables, or change what is published',
254
- usage: 'motherbase db publications alter <name> [--add a,schema.b] [--drop c] [--publish insert,update]',
255
- async run(ctx, args, flags) {
256
- const name = requireArg(args[0], 'name');
257
- const body = {
258
- ...publishFlags(flags, {}),
259
- ...(flags.add ? { addTables: csv(flags.add).map(tableRef) } : {}),
260
- ...(flags.drop ? { dropTables: csv(flags.drop).map(tableRef) } : {}),
261
- };
262
- if (!Object.keys(body).length) throw new CliError('Nothing to change: pass --add, --drop or --publish.');
263
- const data = await api.adminRequest(ctx, 'PATCH', `/database/publications/${encodeURIComponent(name)}`, { body });
264
- output(ctx, data, (_d, ui) => ui.success(`Updated publication ${name}`));
265
- },
266
- },
267
- drop: {
268
- summary: 'Drop a publication',
269
- usage: 'motherbase db publications drop <name>',
270
- async run(ctx, args) {
271
- const name = requireArg(args[0], 'name');
272
- const data = await api.adminRequest(ctx, 'DELETE', `/database/publications/${encodeURIComponent(name)}`);
273
- output(ctx, data, (_d, ui) => ui.success(`Dropped publication ${name}`));
274
- },
275
- },
276
- },
277
- };
278
-
279
- function privilegeChange(grant) {
280
- return {
281
- summary: `${grant ? 'Grant' : 'Revoke'} a column privilege for a role`,
282
- usage: `motherbase db column-privileges ${grant ? 'grant' : 'revoke'} <[schema.]table> --role r --privilege select|insert|update|references --columns a,b`,
283
- async run(ctx, args, flags) {
284
- const { schema, table } = tableRef(requireArg(args[0], 'table'));
285
- if (!flags.role || !flags.privilege || !flags.columns) throw new CliError('--role, --privilege and --columns are required');
286
- const body = {
287
- schema,
288
- table,
289
- role: String(flags.role),
290
- privilege: String(flags.privilege).toUpperCase(),
291
- columns: csv(flags.columns),
292
- grant,
293
- };
294
- const data = await api.adminRequest(ctx, 'PUT', '/database/column-privileges', { body });
295
- output(ctx, data, (_d, ui) => ui.success(`${grant ? 'Granted' : 'Revoked'} ${body.privilege} on ${body.columns.join(', ')} ${grant ? 'to' : 'from'} ${body.role}`));
296
- },
297
- };
298
- }
299
-
300
- const columnPrivileges = {
301
- summary: 'Column-level GRANT / REVOKE per role',
302
- usage: 'motherbase db column-privileges <list|grant|revoke> <[schema.]table> ...',
303
- subcommands: {
304
- list: {
305
- summary: 'Show which columns each role may select, insert, update or reference',
306
- usage: 'motherbase db column-privileges list <[schema.]table>',
307
- async run(ctx, args) {
308
- const query = tableRef(requireArg(args[0], 'table'));
309
- const data = await api.adminRequest(ctx, 'GET', '/database/column-privileges', { query });
310
- output(ctx, data, (d, ui) =>
311
- ui.table((d.roles || []).map(r => ({
312
- role: r.role,
313
- ...Object.fromEntries(Object.entries(r.privileges).map(([privilege, p]) => [
314
- privilege,
315
- p.tableLevel ? '(all)' : p.columns.join(', '),
316
- ])),
317
- })), ['role', 'SELECT', 'INSERT', 'UPDATE', 'REFERENCES']),
318
- );
319
- },
320
- },
321
- grant: privilegeChange(true),
322
- revoke: privilegeChange(false),
323
- },
324
- };
325
-
326
- module.exports = { indexes, types, roles, 'column-privileges': columnPrivileges, publications };
1
+ 'use strict';
2
+
3
+ // `motherbase db indexes|types|roles|publications`: the Database section of
4
+ // Studio from the terminal. Supabase's CLI has no equivalent for these, so they
5
+ // live under `db` rather than claiming top-level names Supabase might use.
6
+
7
+ const api = require('../api');
8
+ const { output, requireArg } = require('./_util');
9
+ const { CliError } = require('../context');
10
+
11
+ const schemaQuery = flags => (flags.schema ? { schema: flags.schema } : undefined);
12
+ const csv = value => String(value).split(',').map(s => s.trim()).filter(Boolean);
13
+
14
+ // `--login`, `--login true` and `--login false` all read naturally; absent
15
+ // means "leave as is", which ALTER ROLE needs to change one attribute only.
16
+ function bool(value) {
17
+ if (value === undefined) return undefined;
18
+ return value === true || value === 'true';
19
+ }
20
+
21
+ // Parse `schema.table` (or a bare `table` in public) into the API's shape.
22
+ function tableRef(ref) {
23
+ const [schema, table] = ref.includes('.') ? ref.split('.', 2) : ['public', ref];
24
+ return { schema, table };
25
+ }
26
+
27
+ function roleAttributes(flags) {
28
+ const attributes = {
29
+ canLogin: bool(flags.login),
30
+ isSuperuser: bool(flags.superuser),
31
+ canCreateDb: bool(flags.createdb),
32
+ canCreateRole: bool(flags.createrole),
33
+ canReplicate: bool(flags.replication),
34
+ canBypassRls: bool(flags.bypassrls),
35
+ inheritRole: bool(flags.inherit),
36
+ connectionLimit: flags['connection-limit'] === undefined ? undefined : Number(flags['connection-limit']),
37
+ password: typeof flags.password === 'string' ? flags.password : undefined,
38
+ validUntil: flags['valid-until'] === undefined ? undefined : String(flags['valid-until']),
39
+ };
40
+ return Object.fromEntries(Object.entries(attributes).filter(([, v]) => v !== undefined));
41
+ }
42
+
43
+ function publishFlags(flags, defaults) {
44
+ const actions = flags.publish === undefined ? null : csv(flags.publish);
45
+ if (!actions) return defaults;
46
+ return Object.fromEntries(['insert', 'update', 'delete', 'truncate'].map(a => [a, actions.includes(a)]));
47
+ }
48
+
49
+ const indexes = {
50
+ summary: 'Indexes across a schema: list, create, drop',
51
+ usage: 'motherbase db indexes <list|create|drop> ...',
52
+ subcommands: {
53
+ list: {
54
+ summary: 'List every index in a schema',
55
+ usage: 'motherbase db indexes list [--schema public]',
56
+ async run(ctx, args, flags) {
57
+ const data = await api.adminRequest(ctx, 'GET', '/schema/indexes', { query: schemaQuery(flags) });
58
+ output(ctx, data, (d, ui) =>
59
+ ui.table((d.indexes || []).map(i => ({ ...i, columns: i.columns.join(', ') })), [
60
+ { key: 'table', label: 'TABLE' },
61
+ { key: 'name', label: 'INDEX' },
62
+ { key: 'method', label: 'METHOD' },
63
+ { key: 'unique', label: 'UNIQUE' },
64
+ { key: 'columns', label: 'COLUMNS' },
65
+ { key: 'sizeBytes', label: 'BYTES' },
66
+ ]),
67
+ );
68
+ },
69
+ },
70
+ create: {
71
+ summary: 'Create an index on one or more columns',
72
+ usage: 'motherbase db indexes create <table> --columns a,b [--unique] [--method btree|hash|gist|gin|brin|spgist] [--name n] [--schema s]',
73
+ async run(ctx, args, flags) {
74
+ const table = requireArg(args[0], 'table');
75
+ if (!flags.columns) throw new CliError('--columns is required');
76
+ const body = { columns: csv(flags.columns), unique: bool(flags.unique) || false };
77
+ if (flags.method) body.method = String(flags.method);
78
+ if (flags.name) body.name = String(flags.name);
79
+ const data = await api.adminRequest(ctx, 'POST', `/schema/tables/${encodeURIComponent(table)}/indexes`, { body, query: schemaQuery(flags) });
80
+ output(ctx, data, (_d, ui) => ui.success(`Created index on ${table} (${body.columns.join(', ')})`));
81
+ },
82
+ },
83
+ drop: {
84
+ summary: 'Drop an index by name',
85
+ usage: 'motherbase db indexes drop <name> [--schema s]',
86
+ async run(ctx, args, flags) {
87
+ const name = requireArg(args[0], 'name');
88
+ const data = await api.adminRequest(ctx, 'DELETE', `/schema/indexes/${encodeURIComponent(name)}`, { query: schemaQuery(flags) });
89
+ output(ctx, data, (_d, ui) => ui.success(`Dropped index ${name}`));
90
+ },
91
+ },
92
+ },
93
+ };
94
+
95
+ const enumPath = name => `/schema/enums/${encodeURIComponent(name)}`;
96
+
97
+ const types = {
98
+ summary: 'Enumerated types: list, create, add-value, rename-value, drop',
99
+ usage: 'motherbase db types <list|create|add-value|rename-value|drop> ...',
100
+ subcommands: {
101
+ list: {
102
+ summary: 'List enum types and their values',
103
+ usage: 'motherbase db types list [--schema public]',
104
+ async run(ctx, args, flags) {
105
+ const data = await api.adminRequest(ctx, 'GET', '/schema/enums', { query: schemaQuery(flags) });
106
+ output(ctx, data, (d, ui) =>
107
+ ui.table((d.enums || []).map(e => ({ name: e.name, values: e.values.join(', '), usedBy: e.usedBy.length })), [
108
+ { key: 'name', label: 'TYPE' },
109
+ { key: 'values', label: 'VALUES' },
110
+ { key: 'usedBy', label: 'COLUMNS' },
111
+ ]),
112
+ );
113
+ },
114
+ },
115
+ create: {
116
+ summary: 'Create an enum type',
117
+ usage: 'motherbase db types create <name> --values a,b,c [--schema s]',
118
+ async run(ctx, args, flags) {
119
+ const name = requireArg(args[0], 'name');
120
+ if (!flags.values) throw new CliError('--values is required');
121
+ const data = await api.adminRequest(ctx, 'POST', '/schema/enums', { body: { name, values: csv(flags.values) }, query: schemaQuery(flags) });
122
+ output(ctx, data, (_d, ui) => ui.success(`Created type ${name}`));
123
+ },
124
+ },
125
+ 'add-value': {
126
+ summary: 'Add a value to an enum (values cannot be removed)',
127
+ usage: 'motherbase db types add-value <name> <value> [--before v | --after v] [--schema s]',
128
+ async run(ctx, args, flags) {
129
+ const name = requireArg(args[0], 'name');
130
+ const value = requireArg(args[1], 'value');
131
+ const body = { action: 'add-value', value, before: flags.before, after: flags.after };
132
+ const data = await api.adminRequest(ctx, 'PATCH', enumPath(name), { body, query: schemaQuery(flags) });
133
+ output(ctx, data, (_d, ui) => ui.success(`Added "${value}" to ${name}`));
134
+ },
135
+ },
136
+ 'rename-value': {
137
+ summary: 'Rename one value of an enum',
138
+ usage: 'motherbase db types rename-value <name> <from> <to> [--schema s]',
139
+ async run(ctx, args, flags) {
140
+ const name = requireArg(args[0], 'name');
141
+ const body = { action: 'rename-value', from: requireArg(args[1], 'from'), to: requireArg(args[2], 'to') };
142
+ const data = await api.adminRequest(ctx, 'PATCH', enumPath(name), { body, query: schemaQuery(flags) });
143
+ output(ctx, data, (_d, ui) => ui.success(`Renamed "${body.from}" to "${body.to}" in ${name}`));
144
+ },
145
+ },
146
+ drop: {
147
+ summary: 'Drop an enum type (refused while a column uses it)',
148
+ usage: 'motherbase db types drop <name> [--schema s]',
149
+ async run(ctx, args, flags) {
150
+ const name = requireArg(args[0], 'name');
151
+ const data = await api.adminRequest(ctx, 'DELETE', enumPath(name), { query: schemaQuery(flags) });
152
+ output(ctx, data, (_d, ui) => ui.success(`Dropped type ${name}`));
153
+ },
154
+ },
155
+ },
156
+ };
157
+
158
+ const ROLE_FLAGS = '[--login] [--password p] [--createdb] [--createrole] [--replication] [--bypassrls] [--superuser] [--connection-limit n] [--valid-until iso]';
159
+
160
+ const roles = {
161
+ summary: 'Postgres roles: list, create, alter, drop',
162
+ usage: 'motherbase db roles <list|create|alter|drop> ...',
163
+ subcommands: {
164
+ list: {
165
+ summary: 'List roles with their attributes and live connections',
166
+ usage: 'motherbase db roles list',
167
+ async run(ctx) {
168
+ const data = await api.adminRequest(ctx, 'GET', '/database/roles');
169
+ output(ctx, data, (d, ui) =>
170
+ ui.table(d.roles || [], [
171
+ { key: 'name', label: 'ROLE' },
172
+ { key: 'canLogin', label: 'LOGIN' },
173
+ { key: 'isSuperuser', label: 'SUPERUSER' },
174
+ { key: 'canBypassRls', label: 'BYPASSRLS' },
175
+ { key: 'connectionLimit', label: 'LIMIT' },
176
+ { key: 'activeConnections', label: 'CONNECTIONS' },
177
+ { key: 'reserved', label: 'RESERVED' },
178
+ ]),
179
+ );
180
+ },
181
+ },
182
+ create: {
183
+ summary: 'Create a role',
184
+ usage: `motherbase db roles create <name> ${ROLE_FLAGS}`,
185
+ async run(ctx, args, flags) {
186
+ const name = requireArg(args[0], 'name');
187
+ const data = await api.adminRequest(ctx, 'POST', '/database/roles', { body: { name, ...roleAttributes(flags) } });
188
+ output(ctx, data, (_d, ui) => ui.success(`Created role ${name}`));
189
+ },
190
+ },
191
+ alter: {
192
+ summary: 'Change attributes of a role, or rename it with --rename',
193
+ usage: `motherbase db roles alter <name> [--rename new] ${ROLE_FLAGS}`,
194
+ async run(ctx, args, flags) {
195
+ const name = requireArg(args[0], 'name');
196
+ const body = { ...roleAttributes(flags), ...(flags.rename ? { name: String(flags.rename) } : {}) };
197
+ if (!Object.keys(body).length) throw new CliError('Nothing to change: pass at least one attribute flag.');
198
+ const data = await api.adminRequest(ctx, 'PATCH', `/database/roles/${encodeURIComponent(name)}`, { body });
199
+ output(ctx, data, (_d, ui) => ui.success(`Updated role ${name}`));
200
+ },
201
+ },
202
+ drop: {
203
+ summary: 'Drop a role (refused for reserved roles and roles that own objects)',
204
+ usage: 'motherbase db roles drop <name>',
205
+ async run(ctx, args) {
206
+ const name = requireArg(args[0], 'name');
207
+ const data = await api.adminRequest(ctx, 'DELETE', `/database/roles/${encodeURIComponent(name)}`);
208
+ output(ctx, data, (_d, ui) => ui.success(`Dropped role ${name}`));
209
+ },
210
+ },
211
+ },
212
+ };
213
+
214
+ const publications = {
215
+ summary: 'Logical-replication publications: list, create, alter, drop',
216
+ usage: 'motherbase db publications <list|create|alter|drop> ...',
217
+ subcommands: {
218
+ list: {
219
+ summary: 'List publications, their tables and published actions',
220
+ usage: 'motherbase db publications list',
221
+ async run(ctx) {
222
+ const data = await api.adminRequest(ctx, 'GET', '/database/publications');
223
+ output(ctx, data, (d, ui) => {
224
+ ui.table((d.publications || []).map(p => ({
225
+ name: p.name,
226
+ publish: ['insert', 'update', 'delete', 'truncate'].filter(a => p[a]).join(', '),
227
+ tables: p.allTables ? '(all tables)' : p.tables.map(t => `${t.schema}.${t.table}`).join(', '),
228
+ })), [
229
+ { key: 'name', label: 'PUBLICATION' },
230
+ { key: 'publish', label: 'PUBLISH' },
231
+ { key: 'tables', label: 'TABLES' },
232
+ ]);
233
+ if (d.walLevel !== 'logical') ui.warn(`wal_level is "${d.walLevel}": publications stream nothing until it is "logical".`);
234
+ });
235
+ },
236
+ },
237
+ create: {
238
+ summary: 'Create a publication',
239
+ usage: 'motherbase db publications create <name> [--tables a,schema.b | --all-tables] [--publish insert,update,delete,truncate]',
240
+ async run(ctx, args, flags) {
241
+ const name = requireArg(args[0], 'name');
242
+ const body = {
243
+ name,
244
+ ...publishFlags(flags, { insert: true, update: true, delete: true, truncate: true }),
245
+ ...(flags['all-tables'] ? { allTables: true } : {}),
246
+ ...(flags.tables ? { tables: csv(flags.tables).map(tableRef) } : {}),
247
+ };
248
+ const data = await api.adminRequest(ctx, 'POST', '/database/publications', { body });
249
+ output(ctx, data, (_d, ui) => ui.success(`Created publication ${name}`));
250
+ },
251
+ },
252
+ alter: {
253
+ summary: 'Add or drop tables, or change what is published',
254
+ usage: 'motherbase db publications alter <name> [--add a,schema.b] [--drop c] [--publish insert,update]',
255
+ async run(ctx, args, flags) {
256
+ const name = requireArg(args[0], 'name');
257
+ const body = {
258
+ ...publishFlags(flags, {}),
259
+ ...(flags.add ? { addTables: csv(flags.add).map(tableRef) } : {}),
260
+ ...(flags.drop ? { dropTables: csv(flags.drop).map(tableRef) } : {}),
261
+ };
262
+ if (!Object.keys(body).length) throw new CliError('Nothing to change: pass --add, --drop or --publish.');
263
+ const data = await api.adminRequest(ctx, 'PATCH', `/database/publications/${encodeURIComponent(name)}`, { body });
264
+ output(ctx, data, (_d, ui) => ui.success(`Updated publication ${name}`));
265
+ },
266
+ },
267
+ drop: {
268
+ summary: 'Drop a publication',
269
+ usage: 'motherbase db publications drop <name>',
270
+ async run(ctx, args) {
271
+ const name = requireArg(args[0], 'name');
272
+ const data = await api.adminRequest(ctx, 'DELETE', `/database/publications/${encodeURIComponent(name)}`);
273
+ output(ctx, data, (_d, ui) => ui.success(`Dropped publication ${name}`));
274
+ },
275
+ },
276
+ },
277
+ };
278
+
279
+ function privilegeChange(grant) {
280
+ return {
281
+ summary: `${grant ? 'Grant' : 'Revoke'} a column privilege for a role`,
282
+ usage: `motherbase db column-privileges ${grant ? 'grant' : 'revoke'} <[schema.]table> --role r --privilege select|insert|update|references --columns a,b`,
283
+ async run(ctx, args, flags) {
284
+ const { schema, table } = tableRef(requireArg(args[0], 'table'));
285
+ if (!flags.role || !flags.privilege || !flags.columns) throw new CliError('--role, --privilege and --columns are required');
286
+ const body = {
287
+ schema,
288
+ table,
289
+ role: String(flags.role),
290
+ privilege: String(flags.privilege).toUpperCase(),
291
+ columns: csv(flags.columns),
292
+ grant,
293
+ };
294
+ const data = await api.adminRequest(ctx, 'PUT', '/database/column-privileges', { body });
295
+ output(ctx, data, (_d, ui) => ui.success(`${grant ? 'Granted' : 'Revoked'} ${body.privilege} on ${body.columns.join(', ')} ${grant ? 'to' : 'from'} ${body.role}`));
296
+ },
297
+ };
298
+ }
299
+
300
+ const columnPrivileges = {
301
+ summary: 'Column-level GRANT / REVOKE per role',
302
+ usage: 'motherbase db column-privileges <list|grant|revoke> <[schema.]table> ...',
303
+ subcommands: {
304
+ list: {
305
+ summary: 'Show which columns each role may select, insert, update or reference',
306
+ usage: 'motherbase db column-privileges list <[schema.]table>',
307
+ async run(ctx, args) {
308
+ const query = tableRef(requireArg(args[0], 'table'));
309
+ const data = await api.adminRequest(ctx, 'GET', '/database/column-privileges', { query });
310
+ output(ctx, data, (d, ui) =>
311
+ ui.table((d.roles || []).map(r => ({
312
+ role: r.role,
313
+ ...Object.fromEntries(Object.entries(r.privileges).map(([privilege, p]) => [
314
+ privilege,
315
+ p.tableLevel ? '(all)' : p.columns.join(', '),
316
+ ])),
317
+ })), ['role', 'SELECT', 'INSERT', 'UPDATE', 'REFERENCES']),
318
+ );
319
+ },
320
+ },
321
+ grant: privilegeChange(true),
322
+ revoke: privilegeChange(false),
323
+ },
324
+ };
325
+
326
+ module.exports = { indexes, types, roles, 'column-privileges': columnPrivileges, publications };